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

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 <qcursor.h>
#include <qxembed.h>
#include <qframe.h>
#include <qlayout.h>
#include <qhbox.h>
#include <qfile.h>
#include <qtimer.h>
#include <qtooltip.h>

#include <dcopclient.h>
#include <kapplication.h>
#include <kconfig.h>
#include <kdebug.h>
#include <kglobal.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kpanelapplet.h>
#include <kpopupmenu.h>
#include <kprocess.h>
#include <kstandarddirs.h>

#include "global.h"
#include "kicker.h"
#include "panel.h"
#include "appletop_mnu.h"
#include "pluginloader.h"
#include "applethandle.h"
#include "appletinfo.h"
#include "popupposition.h"

#include "containerarea.h"
#include "container_applet.h"
#include "container_applet.moc"

AppletContainer::AppletContainer( const AppletInfo& info, QPopupMenu* opMenu, QWidget* parent )
  : BaseContainer( opMenu, parent, QString( info.library() + "container" ).latin1() )
  , _info(info)
  , _layout(0)
  , _type(KPanelApplet::Normal)
  , _widthForHeightHint(0)
  , _heightForWidthHint(0)
  , _firstuse( TRUE )
{
    setBackgroundOrigin( AncestorOrigin );

    // setup handle
    _handle = new AppletHandle(this);
    if (Kicker::kicker()->isImmutable() || !kapp->authorizeKAction("kicker_rmb"))
       _handle->hide();
    else
        QToolTip::add( _handle, info.name() );

    connect( Kicker::kicker(), SIGNAL(configurationChanged()),
             this, SLOT(slotReconfigure()));
    connect( _handle, SIGNAL(moveApplet(const QPoint&)), this, SLOT(moveApplet(const QPoint&)) );
    connect( _handle, SIGNAL(removeApplet()), this, SLOT(removeApplet()) );
    connect( _handle, SIGNAL(showAppletMenu()), this, SLOT(showAppletMenu()) );

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

    if (orientation() == Horizontal)
    {
        _layout = new QBoxLayout(this, QBoxLayout::LeftToRight, 0, 0);
    }
    else
    {
        _layout = new QBoxLayout(this, QBoxLayout::TopToBottom, 0, 0);
    }

    _layout->setResizeMode( QLayout::FreeResize );

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

void AppletContainer::configure()
{
    KConfig *config = KGlobal::config();
    config->setGroup("General");
    _handle->setFadeOutHandle(config->readBoolEntry("FadeOutAppletHandles", false));
    if (config->readBoolEntry("HideAppletHandles", false) || Kicker::kicker()->isImmutable() || !kapp->authorizeKAction("kicker_rmb"))
        _handle->hide();
    else
        _handle->show();
}

void AppletContainer::slotReconfigure()
{
    configure();
}

void AppletContainer::slotSetPopupDirection(Direction d)
{
    if (!_firstuse && _dir == d) return;

    _firstuse = FALSE;
    BaseContainer::slotSetPopupDirection(d);

    resetLayout();
}

void AppletContainer::slotSetOrientation(Orientation o)
{
    if (_orient == o) return;

    BaseContainer::slotSetOrientation(o);

    resetLayout();
}

void AppletContainer::resetLayout()
{
    _handle->resetLayout();

    if (orientation() == Horizontal) {
        _layout->setDirection( QApplication::reverseLayout() ?
                               QBoxLayout::RightToLeft :
                               QBoxLayout::LeftToRight );
    } else {
        _layout->setDirection( QBoxLayout::TopToBottom );
    }
    _layout->activate();
}

void AppletContainer::moveApplet( const QPoint& moveOffset )
{
    _moveOffset = moveOffset;
    emit moveme(this);
}

void AppletContainer::removeApplet()
{
    emit removeme(this);
}

void AppletContainer::showAppletMenu()
{
    if (!kapp->authorizeKAction("kicker_rmb"))
        return;

    QPopupMenu *menu = opMenu();

    switch( menu->exec( popupPosition( popupDirection(), menu, this ) ) ) {
	case PanelAppletOpMenu::Move:
	    moveApplet( QPoint(_handle->width()/2, _handle->height()/2) );
	    break;
	case PanelAppletOpMenu::Remove:
	    emit removeme(this);
	    return; // Above signal will cause this to be deleted.
	    break;
	case PanelAppletOpMenu::Help:
	    help();
	    break;
	case PanelAppletOpMenu::About:
	    about();
	    break;
	case PanelAppletOpMenu::Preferences:
	    preferences();
	    break;
	case PanelAppletOpMenu::ReportBug:
	    reportBug();
	    break;
	default:
	    break;
	}

    if (!_handle->onMenuButton(QCursor::pos()))
        _handle->toggleMenuButtonOff();
}

void AppletContainer::slotRemoved()
{
    BaseContainer::slotRemoved();

    if (_configFile.isEmpty()) return;
    if (_info.isUniqueApplet()) return;

    if( QFile::exists( locate( "config", _configFile ) ) ) {
        QFile::remove( locate( "config", _configFile ) );
    }
}

void AppletContainer::doLoadConfiguration( KConfigGroup& config )
{
    setWidthForHeightHint( config.readNumEntry( "WidthForHeightHint", 0 ) );
    setHeightForWidthHint( config.readNumEntry( "HeightForWidthHint", 0 ) );
}

void AppletContainer::doSaveConfiguration( KConfigGroup& config,
                                           bool layoutOnly ) const
{
    if (orientation() == Horizontal)
	config.writeEntry( "WidthForHeightHint", widthForHeight(height()) );
    else
	config.writeEntry( "HeightForWidthHint", heightForWidth(width()) );

    if (!layoutOnly) {
	config.writeEntry( "ConfigFile", _configFile );
	config.writeEntry( "DesktopFile", _deskFile );
    }
}

QPopupMenu* AppletContainer::createOpMenu() const
{
    QPopupMenu* opMenu = new PanelAppletOpMenu(_actions, appletOpMenu(), const_cast<QPopupMenu*>(appletsOwnMenu()),
                                               _info.name(), _info.icon(),
                                               const_cast<AppletContainer*>(this));
    connect(opMenu, SIGNAL(escapePressed()),
            _handle, SLOT(toggleMenuButtonOff()));
    return opMenu;
}

InternalAppletContainer::InternalAppletContainer( const AppletInfo& info, QPopupMenu* opMenu, QWidget *parent)
  : AppletContainer(info, opMenu, parent)
{
    _deskFile = info.desktopFile();
    _configFile = info.configFile();
    _applet = PluginLoader::pluginLoader()->loadApplet( info, _appletframe );

    if (!_applet) 
    {
        _valid = false;
        KMessageBox::error(this, 
                           i18n("The %1 applet could not be loaded. Please check your installation.").arg(info.name()), 
                           i18n("Applet Loading Error"));
        return;
    }
    _valid = true;

    // FIXME: Do we really want to do this here?
    _applet->setPosition(  (KPanelApplet::Position)directionToPosition( popupDirection() ) );
    _applet->setAlignment( (KPanelApplet::Alignment)alignment() );

    _actions = _applet->actions();
    _type = _applet->type();

    connect(_applet, SIGNAL(updateLayout()), SIGNAL(updateLayout()));
    connect(_applet, SIGNAL(requestFocus()), SLOT(activateWindow()));

    connect( this, SIGNAL(alignmentChange(Alignment)),
             this, SLOT(slotAlignmentChange(Alignment)) );
}

const QPopupMenu* InternalAppletContainer::appletsOwnMenu() const
{
    if (!_applet)
    {
        return 0;
    }

    return _applet->customMenu();
}

InternalAppletContainer::~InternalAppletContainer()
{
}

void InternalAppletContainer::slotDelayedDestruct()
{
    delete this;
}

void InternalAppletContainer::slotSetPopupDirection(Direction d)
{
    if (!_firstuse && _dir == d) return;

    AppletContainer::slotSetPopupDirection(d);

    if ( !_applet ) return;
    _applet->setPosition( (KPanelApplet::Position)directionToPosition(d) );
}

void InternalAppletContainer::slotAlignmentChange( Alignment a )
{
    if (!_applet) return;
    _applet->setAlignment( (KPanelApplet::Alignment)a );
}

int InternalAppletContainer::widthForHeight(int h) const
{
    if (!_applet) {
	if (_widthForHeightHint > 0)
	    return _widthForHeightHint + _handle->widthForHeight(h);
	else
	    return h + _handle->widthForHeight(h);
    }
    return _applet->widthForHeight(h) + ( _handle->isVisible()
                                        ? _handle->widthForHeight(h)
                                        : 0 );
}

int InternalAppletContainer::heightForWidth(int w) const
{
    if (!_applet) {
	if (_heightForWidthHint > 0)
	    return _heightForWidthHint + _handle->heightForWidth(w);
	else
	    return w + _handle->heightForWidth(w);
    }
    return _applet->heightForWidth(w) + ( _handle->isVisible()
                                        ? _handle->heightForWidth(w)
                                        : 0 );
}

void InternalAppletContainer::about()
{
    if (!_applet) return;
    _applet->action( KPanelApplet::About );
}

void InternalAppletContainer::help()
{
    if (!_applet) return;
    _applet->action( KPanelApplet::Help );
}

void InternalAppletContainer::preferences()
{
    if (!_applet) return;
    _applet->action( KPanelApplet::Preferences );
}

void InternalAppletContainer::reportBug()
{
    if (!_applet) return;
    _applet->action( KPanelApplet::ReportBug );
}

void InternalAppletContainer::setBackground()
{
    // can happen in perverse moments when an applet isn't loaded but the contanier
    // get's asked to update it's bground anyways
    if (!_applet)
        return;

    if( !Panel::the()->containerArea()->transparent() ) {
        setBackgroundOrigin(AncestorOrigin);
        _applet->unsetPalette();
        _applet->repaint();
        _handle->unsetPalette();
        _handle->repaint();
        return;
    }
    
    int srcx = x();
    int srcy = y();

    KConfig *config = KGlobal::config();
    config->setGroup("General");

    ContainerArea* area = static_cast<ContainerArea*>(parent()->parent());
    const QPixmap* containerBG = area->completeBackgroundPixmap();

    if( !containerBG ) return;
    if( containerBG->isNull() ) return;
    
    if (!config->readBoolEntry("HideAppletHandles", false)) 
        if( orientation() == Horizontal ) 
            srcx += _handle->width();
        else
            srcy += _handle->height();

    QPixmap p( _applet->width(), _applet->height() );
    copyBlt( &p, 0, 0, containerBG, srcx, srcy, _applet->width(), _applet->height());
    _applet->blockSignals(true);
    _applet->setBackgroundOrigin(WidgetOrigin);
    _applet->setPaletteBackgroundPixmap(p);
    repaint();
    _applet->blockSignals(false);

    // and let's not forget the handle
    QPixmap handle_p( _handle->width(), _handle->height() );       
    copyBlt( &handle_p, 0, 0, 
             containerBG, x(), y(), 
              _handle->width(), _handle->height());
    _handle->setPaletteBackgroundPixmap(handle_p);
}

ExternalAppletContainer::ExternalAppletContainer( const AppletInfo& info, QPopupMenu* opMenu, QWidget *parent)
  : AppletContainer(info, opMenu, parent)
, DCOPObject(QCString("ExternalAppletContainer_") + QString::number( (ulong) this ).latin1() )
, _isdocked(false)
{
    _deskFile = info.desktopFile();
    _configFile = info.configFile();

    // init QXEmbed
    _embed = new QXEmbed( _appletframe );
    _embed->setBackgroundOrigin(AncestorOrigin);
    connect ( _embed, SIGNAL( embeddedWindowDestroyed() ),
              this, SIGNAL( embeddedWindowDestroyed() ) );

    QStringList args;
    args << "--caption" << info.name()
         << "--configfile" << info.configFile()
         << "--callbackid" << objId()
         << info.desktopFile();
    KApplication::kdeinitExec( "appletproxy", args );

    connect( this, SIGNAL(alignmentChange(Alignment)),
             this, SLOT(slotAlignmentChange(Alignment)) );
}

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

void ExternalAppletContainer::slotSetPopupDirection(Direction d)
{
    if (!_firstuse && _dir == d) return;

    AppletContainer::slotSetPopupDirection(d);

    if (!_isdocked) return;

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

    kapp->dcopClient()->send( _app, "AppletProxy", "setDirection(int)", data);
}

void ExternalAppletContainer::slotAlignmentChange( Alignment a )
{
    if (!_isdocked) return;

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

    kapp->dcopClient()->send( _app, "AppletProxy", "setAlignment(int)", data );
}

void ExternalAppletContainer::about()
{
    if (!_isdocked) return;

    QByteArray data;
    kapp->dcopClient()->send( _app, "AppletProxy", "about()", data );
}

void ExternalAppletContainer::help()
{
    if (!_isdocked) return;

    QByteArray data;
    kapp->dcopClient()->send( _app, "AppletProxy", "help()", data );
}

void ExternalAppletContainer::preferences()
{
    if (!_isdocked) return;

    QByteArray data;
    kapp->dcopClient()->send( _app, "AppletProxy", "preferences()", data );
}

void ExternalAppletContainer::reportBug()
{
    if (!_isdocked) return;

    QByteArray data;
    kapp->dcopClient()->send( _app, "AppletProxy", "reportBug()", data );
}

int ExternalAppletContainer::widthForHeight(int h) const
{
    int w = h;
    if (_widthForHeightHint > 0)
        w = _widthForHeightHint;

    if (!_isdocked) return w;

    DCOPClient* dcop = kapp->dcopClient();

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

    if (dcop->call( _app, "AppletProxy", "widthForHeight(int)", data, replyType, replyData ) )
    {
        QDataStream reply( replyData, IO_ReadOnly );
        reply >> w;
    }
    return w + ( _handle->isVisible()
               ? _handle->widthForHeight(h)
               : 0 );
}

int ExternalAppletContainer::heightForWidth(int w) const
{
    int h = w;
    if (_heightForWidthHint > 0)
        h = _heightForWidthHint;

    if (!_isdocked) return h;

    DCOPClient* dcop = kapp->dcopClient();

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

    if (dcop->call( _app, "AppletProxy", "heightForWidth(int)", data, replyType, replyData ) )
    {
        QDataStream reply( replyData, IO_ReadOnly );
        reply >> h;
    }
    return h + ( _handle->isVisible()
               ? _handle->heightForWidth(w)
               : 0 );
}

bool ExternalAppletContainer::process(const QCString &fun, const QByteArray &data,
				      QCString& replyType, QByteArray & replyData)
{
    if ( fun == "dockRequest(int,int)" )
	{
	    QDataStream reply( replyData, IO_WriteOnly );
	    replyType = "WId";
	    reply << _embed->winId();

	    QDataStream sdata( data, IO_ReadOnly );
	    int actions, type;
	    sdata >> actions;
	    sdata >> type;

	    dockRequest(kapp->dcopClient()->senderId(), actions, type);
	    return true;
	}
    else if(fun == "updateLayout()")
	{
	    emit updateLayout();
	    return(true);
	}
    else if(fun == "requestFocus()")
	{
	    activateWindow();
	    return(true);
	}
    else if(fun == "getBackground()")
	{
	    setBackground();
	    return(true);
	}

    return true;
}

void ExternalAppletContainer::dockRequest(QCString app, int actions, int type)
{
    _app = app;

    _type = static_cast<KPanelApplet::Type>(type);
    _actions = actions;

    // set orientation
    {
	QByteArray data;
	QDataStream dataStream( data, IO_WriteOnly );
	dataStream << static_cast<int>(_orient);

	kapp->dcopClient()->send( _app, "AppletProxy", "setOrientation(int)", data );
    }
    // set popup menu direction
    {
	QByteArray data;
	QDataStream dataStream( data, IO_WriteOnly );
	dataStream << static_cast<int>(_dir);

	kapp->dcopClient()->send( _app, "AppletProxy", "setDirection(int)", data);
    }

    _isdocked = true;
    emit docked(this);
    emit updateLayout();
}

void ExternalAppletContainer::setBackground()
{   
    QPixmap* p; 
    if( Panel::the()->containerArea()->transparent() ) {
    
        // Compute background and send it to the proxy
        int srcx = x();
        int srcy = y();

        KConfig *config = KGlobal::config();
        config->setGroup("General");
    
        if (!config->readBoolEntry("HideAppletHandles", false)) 
            if( orientation() == Horizontal ) 
                srcx += _handle->width();
            else
                srcy += _handle->height();

        ContainerArea* area = static_cast<ContainerArea*>(parent()->parent());
        const QPixmap* containerBG = area->completeBackgroundPixmap();

        if( !containerBG ) return;
        if( containerBG->isNull() ) {
            p = new QPixmap(0,0);
            _handle->unsetPalette();
        }
        else {
            int awidth  = _appletframe->width();
            int aheight = _appletframe->height();

            p = new QPixmap( awidth, aheight );
            copyBlt( p, 0, 0, containerBG, srcx, srcy, awidth, aheight);

            // and let's not forget the handle
            QPixmap handle_p( _handle->width(), _handle->height() );       
            copyBlt( &handle_p, 0, 0, 
                     containerBG, x(), y(), 
                     _handle->width(), _handle->height());
            _handle->setPaletteBackgroundPixmap(handle_p);
        }
    }
    else if( Panel::the()->containerArea()->useBackgroundTheme() ) {
        
        ContainerArea* area = static_cast<ContainerArea*>(parent()); 
        const QPixmap* containerBG = area->paletteBackgroundPixmap();
        
        if( !containerBG ) {
            p = new QPixmap(0,0);
            _handle->unsetPalette();
        }
        else {
            p = new QPixmap(*containerBG);
            _handle->setPaletteBackgroundPixmap(*p);
        }
    } 
    else {   // plain background
        
        p = new QPixmap(0,0);
        _handle->unsetPalette();	 
    }

    _handle->repaint();
    
    QByteArray data;
    QDataStream dataStream( data, IO_WriteOnly );
    dataStream << *p;
    kapp->dcopClient()->send( _app, 
                              "AppletProxy", 
                              "setBackground(QPixmap)", 
                              data);
    delete p;
}
