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

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 <kapplication.h>
#include <kpopupmenu.h>
#include <kdebug.h>
#include <kglobal.h>
#include <kconfig.h>
#include <kpanelapplet.h>
#include <kprocess.h>
#include <kstandarddirs.h>
#include <dcopclient.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 "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 )
{
    // setup handle
    _handle = new AppletHandle(this);
    if (Kicker::kicker()->isImmutable())
       _handle->hide();

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

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()
{
    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(), _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) return;

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


InternalAppletContainer::~InternalAppletContainer()
{
}

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 )
{
    _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->widthForHeight(h);
}

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->heightForWidth(w);
}

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

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 );
    connect ( _embed, SIGNAL( embeddedWindowDestroyed() ),
	      this, SIGNAL( embeddedWindowDestroyed() ) );

    KProcess process;
    process << "appletproxy"
	    << QCString("--configfile")
	    << info.configFile()
	    << QCString("--callbackid")
	    << objId()
	    << info.desktopFile();
    process.start(KProcess::DontCare);

    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->widthForHeight(h);
}

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->heightForWidth(w);
}

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