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

Copyright (c) 1996-2003 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 "panelop_mnu.h"

#include <qtooltip.h>
#include <qlayout.h>

#include <kglobal.h>
#include <kdebug.h>
#include <kconfig.h>
#include <ksimpleconfig.h>
#include <dcopclient.h>
#include <kicontheme.h>

#include "kicker.h"
#include "fittslawframe.h"
#include "containerarea.h"
#include "popupposition.h"

#include "panel.h"
#include "panel.moc"

Panel* _thePanel = 0;

Panel* Panel::the()
{
    if( _thePanel == 0 ) {
         _thePanel = new Panel();
    }
    return _thePanel;
}

Panel::Panel()
  : DCOPObject( "Panel" )
  , PanelContainer( 0, "Panel" )
  , _opMnu( 0 )
{
    setAcceptDrops( !Kicker::kicker()->isImmutable() );

    _frame = new FittsLawFrame( this );
    setMainWidget( _frame );

    KConfig *config = KGlobal::config();
    config->setGroup("General");
    if ( config->readBoolEntry("Transparent", false) )
        _frame->setFrameStyle( QFrame::NoFrame );
    else
        _frame->setFrameStyle(QFrame::StyledPanel  | QFrame::Raised);
    _frame->setLineWidth(2);
    _frame->enableResizeHandle( false );
    _frame->setResizePosition( FittsLawFrame::Top );

    connect( _frame, SIGNAL( resizeRequest( int, int ) ),
	     SLOT( slotResizeRequest( int, int ) ) );

    _layout = new QVBoxLayout( _frame );
    _layout->setMargin( _frame->frameWidth() );

    // applet area
    _containerArea = new ContainerArea( KGlobal::config(), _frame, opMenu() );
    _layout->addWidget( _containerArea, 1 );

    _containerArea->setFrameStyle( QFrame::NoFrame );
    _containerArea->viewport()->installEventFilter( this );
    connect(_containerArea, SIGNAL(sizeHintChanged()), SLOT(updateLayout()));

    connect( this, SIGNAL(resizeablehandleChange(bool)),
             this, SLOT(slotResizeableHandleChange(bool)) );
    connect( this, SIGNAL(sizeChange(Size, int)),
             this, SLOT(slotSizeChange(Size, int)) );
    connect( this, SIGNAL(positionChange(Position)),
             this, SLOT(slotPositionChange(Position)) );
    connect( this, SIGNAL(alignmentChange(Alignment)),
             this, SLOT(slotAlignmentChange(Alignment)) );
}

Panel::~Panel()
{
    if(_containerArea)
        _containerArea->slotSaveContainerConfig();
}

void Panel::initialize()
{
    _containerArea->initialize( this, true );
}

void Panel::setFrameStyle( int style )
{
  if ( style == QFrame::NoFrame )
    _frame->setLineWidth(0);
  else
    _frame->setLineWidth(2);
  _layout->setMargin( _frame->frameWidth() );
  _frame->setFrameStyle( style );
}

void Panel::readConfig()
{
//    kdDebug() << "Panel::readConfig()" << endl;

    KConfig *config = KGlobal::config();
    config->setGroup("General");
    if ( config->readBoolEntry("Transparent", false) )
        _frame->setFrameStyle( QFrame::NoFrame );
    else
        _frame->setFrameStyle(QFrame::StyledPanel  | QFrame::Raised);
    _containerArea->configure();

    PanelContainer::readConfig( config );
}

void Panel::writeConfig()
{
//    kdDebug() << "Panel::writeConfig()" << endl;

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

    KSimpleConfig kdeglobals("kdeglobals", false);
    kdeglobals.setGroup("PanelIcons");
    if ( panelSize() >= sizeValue( Large ) )
	kdeglobals.writeEntry("Size", static_cast<int>(KIcon::SizeLarge) );
    else if ( panelSize() >= sizeValue( Normal ) )
	kdeglobals.writeEntry("Size", static_cast<int>(KIcon::SizeMedium) );
    else
	kdeglobals.writeEntry("Size", static_cast<int>(KIcon::SizeSmall) );

    PanelContainer::writeConfig( config );
    config->sync();
}

void Panel::slotResizeRequest( int dx, int dy )
{
    int offset;
    switch( position() ) {
	case Left:
	    offset = dx;
	    break;
	case Right:
	    offset = -dx;
	    break;
	case Top:
	    offset = dy;
	    break;
	case Bottom:
	default:
	    offset = -dy;
	    break;
    }
    setSize( size(), panelSize() + offset );
}

void Panel::slotResizeableHandleChange( bool resizeablehandle )
{
    _frame->enableResizeHandle( resizeablehandle && size() == Custom && !Kicker::kicker()->isImmutable() );
}

void Panel::slotSizeChange( Size s, int /*customSize*/ )
{
    _frame->enableResizeHandle( resizeablehandle() && s == Custom && !Kicker::kicker()->isImmutable() );
}

void Panel::slotPositionChange( Position p )
{
    switch ( p ) {
	case Top:
	    _frame->setResizePosition( FittsLawFrame::Bottom );
	    break;
	case Bottom:
	    _frame->setResizePosition( FittsLawFrame::Top );
	    break;
	case Left:
	    _frame->setResizePosition( FittsLawFrame::Right );
	    break;
	case Right:
	    _frame->setResizePosition( FittsLawFrame::Left );
	    break;
    }
    _containerArea->setOrientation(orientation());
    _containerArea->setPosition(position());
}

void Panel::slotAlignmentChange( Alignment a )
{
    _containerArea->setAlignment( a );
}

void Panel::showPanelMenu( const QPoint &globalPos )
{
    if (!kapp->authorizeKAction("kicker_rmb"))
       return;
    PanelOpMenu *menu = opMenu();
    menu->buildMenu();
    menu = static_cast<PanelOpMenu*>(BaseContainer::reduceMenu(menu));

    menu->exec( popupPosition(
       positionToDirection( position() ), opMenu(),
       this, mapFromGlobal( globalPos ) ) );
}

bool Panel::vetoAutoHide() const
{
    return PanelContainer::vetoAutoHide() || _containerArea->inMoveOperation();
}

void Panel::closeEvent( QCloseEvent *e )
{
    e->ignore();
}

// For backwards compatibility with scripts.
void Panel::restart()
{
    Kicker::kicker()->restart();
}

// For backwards compatibility with scripts.
void Panel::configure()
{
    Kicker::kicker()->configure();
}

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::addServiceButton(const QString& desktopEntry)
{
    _containerArea->addServiceButton(desktopEntry);
}

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

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

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

QSize Panel::sizeHint( Position p, const QSize &maxSize )
{
    QSize size = PanelContainer::sizeHint( p, maxSize );

    QSize ourSize;
    int w = panelSize() - size.width() - _frame->lineWidth() * 2;
    int h = panelSize() - size.height() - _frame->lineWidth() * 2;
    if( p == ::Top || p == ::Bottom ) {
	ourSize = QSize( _containerArea->minimumUsedSpace( Horizontal, w, h ), h ) +
	          QSize( _frame->lineWidth() * 2,  _frame->lineWidth() * 2 );
    } else {
	ourSize = QSize( w, _containerArea->minimumUsedSpace( Vertical, w, h ) ) +
	          QSize( _frame->lineWidth() * 2,  _frame->lineWidth() * 2 );
    }
    return (size + ourSize).boundedTo( maxSize );
}

PanelOpMenu* Panel::opMenu()
{
    if ( _opMnu == 0 )
        _opMnu = new PanelOpMenu( this, this );

    return _opMnu;
}

int Panel::panelSize()
{
    if( size() == Custom ) {
        return customSize();
    } else {
        return sizeValue( size() );
    }
}

void Panel::setPanelSize(int size)
{
    if (size == sizeValue(Tiny))
    {
        setSize(Tiny);
    }
    else if (size == sizeValue(Small))
    {
        setSize(Small);
    }
    else if (size == sizeValue(Normal))
    {
        setSize(Normal);
    }
    else if (size == sizeValue(Large))
    {
        setSize(Large);
    }
    else
    {
        setSize(Custom, size);
    }
}

