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

Copyright (c) 1996-2001 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()
  : PanelContainer( 0, "Panel" )
  , DCOPObject( "Panel" )
  , _size( Normal )
  , _panelsize( 0 )
{
    setAcceptDrops( !Kicker::kicker()->isImmutable() );

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

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

    QVBoxLayout* layout = new QVBoxLayout( _frame );
    layout->setMargin( _frame->frameWidth() );

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

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

    connect(this, SIGNAL(positionChange(Position)), SLOT(slotSetPosition(Position)));
    connect( this, SIGNAL(alignmentChange(Alignment)),
             this, SLOT(slotAlignmentChange(Alignment)) );

    _opMnu = new PanelOpMenu( this, this );
}

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

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

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

    KConfig *config = KGlobal::config();
    _containerArea->configure();

    config->setGroup("General");

    _panelsize = config->readNumEntry( "Size", sizeValue( Normal ) );

    // backward compatibility
    if ( _panelsize == 0 ) _panelsize = sizeValue( Tiny );
    else if ( _panelsize == 1 ) _panelsize = sizeValue( Small );
    else if ( _panelsize == 2 ) _panelsize = sizeValue( Normal );
    else if ( _panelsize == 3 ) _panelsize = sizeValue( Large );

    _panelsize = QMIN( QMAX( _panelsize, MIN_PANEL_SIZE ), MAX_PANEL_SIZE );

    _frame->enableResizeHandle( size() == ::Custom && !Kicker::kicker()->isImmutable() );

    PanelContainer::readConfig( config );
}

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

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

    config->writeEntry( "Size", _panelsize );

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

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

Size Panel::size() const
{
    if( _panelsize == sizeValue(::Tiny) ) return ::Tiny;
    if( _panelsize == sizeValue(::Small) ) return ::Small;
    if( _panelsize == sizeValue(::Normal) ) return ::Normal;
    if( _panelsize == sizeValue(::Large) ) return ::Large;
    return ::Custom;
}

void Panel::setSize( int s )
{
    _panelsize = QMIN( QMAX( s, MIN_PANEL_SIZE ), MAX_PANEL_SIZE );

    _frame->enableResizeHandle( size() == ::Custom && !Kicker::kicker()->isImmutable() );

    updateLayout();
    writeConfig();
}

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

void Panel::slotSetPosition( 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( QPoint globalPos )
{
    QPopupMenu *menu = BaseContainer::reduceMenu(_opMnu);

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

bool Panel::vetoAutoHide()
{
    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::addServiceMenuButton(const QString &name, const QString& relPath)
{
    _containerArea->addServiceMenuButton(name, relPath);
}

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

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

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

QSize Panel::sizeHint( Position p, 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 );
}
