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

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 <math.h>
#include <unistd.h>

#include <qpixmap.h>
#include <qfileinfo.h>
#include <qtimer.h>
#include <qfile.h>
#include <qstyle.h>
#include <qtextstream.h>
#include <qpainter.h>
#include <qwmatrix.h>

#include <kapplication.h>
#include <kglobal.h>
#include <kstandarddirs.h>
#include <kurl.h>
#include <kdebug.h>
#include <kdesktopfile.h>
#include <kmimetype.h>
#include <kprocess.h>
#include <kpixmap.h>
#include <klocale.h>
#include <kio/netaccess.h>

#include "kicker.h"
#include "pluginmanager.h"
#include "dirdrop_mnu.h"
#include "exe_dlg.h"
#include "panel.h"
#include "panelbutton.h"
#include "container_applet.h"
#include "container_button.h"

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

// for multihead
extern int kicker_screen_number;

ContainerArea::ContainerArea( KConfig* _c, QWidget* parent, QPopupMenu* opMenu, const char* name )
    : Panner( parent, name )
    , _block_relayout(false)
    , _movingAC(false)
    , _moveAC(0)
    , _pos(::Left)
    , _config(_c)
    , _dragIndicator(0)
    , _dragMoveAC(0)
    , _dragMoveOffset(QPoint(0,0))
    , _opMenu(opMenu)
{
    setAcceptDrops( !Kicker::kicker()->isImmutable() );
    connect(&_autoScrollTimer, SIGNAL(timeout()), SLOT(autoScroll()));
}

void ContainerArea::initialize( PanelContainer* panel, bool useDefaultConfig )
{
    // restore applet layout or load a default panel layout
    _config->setGroup("General");

    if(_config->hasKey("Applets")) {
        loadContainerConfig();
    } else {
        defaultContainerConfig( panel, useDefaultConfig );
    }
}

ContainerArea::~ContainerArea()
{
    // don't emit signals from destructor
    blockSignals( true );
    // clear applets
    removeAllContainers();
}

void ContainerArea::defaultContainerConfig( PanelContainer* panel, bool useDefaultConfig )
{
    // only the main area has a default container config
    if ( !useDefaultConfig || panel == 0 ) {
	removeAllContainers();
	layoutChildren();
	saveContainerConfig();
	return;
    }

    // clear applets
    removeAllContainers();

    ContainerList containers;

    containers.append( new KMenuButtonContainer( _opMenu, viewport() ) );
    containers.append( new DesktopButtonContainer( _opMenu, viewport() ) );

    QRect r = panel->initialGeometry( panel->position(), panel->alignment(), panel->xineramaScreen() );

    int dsize;
    if (orientation() == Horizontal)
	dsize = r.width();
    else
	dsize = r.height();

    dsize -= 560;

    QStringList buttons;

    QFile f(locate("data", "kicker/default-apps"));
    if (f.open(IO_ReadOnly)) {
        QTextStream is(&f);

        while (!is.eof())
            buttons << is.readLine();

        f.close();
    } else {
        buttons << "menuext/prefmenu.desktop";
        buttons << "System/konsole.desktop";
        buttons << "Home.desktop";
        buttons << "Internet/konqbrowser.desktop";
        buttons << "Internet/KMail.desktop";
        buttons << "Editors/kwrite.desktop";
        buttons << "Office/kword.desktop";
        buttons << "Help.desktop";
    }

    int size = dsize;
    for (QStringList::ConstIterator it = buttons.begin(); it != buttons.end(); ++it) {
        size -= 42;
        if (size <= 0)
            break;

        BaseContainer *button;
        QString s = locate("apps", *it);
        if (s.isEmpty()) {
            // look for a special button
            s = locate("appdata", *it);
            if (s.isEmpty()) continue;
            QString itExt = (*it).section('/', 1);
            button = new ExtensionButtonContainer(itExt, _opMenu, viewport());
        }
        else
            button = new ServiceButtonContainer(*it, _opMenu, viewport());
        
        if (button->isValid())
            containers.append( button );
        else
            delete button;
    }

    PluginManager* manager = PluginManager::pluginManager();

    // pager applet
    containers.append( manager->createAppletContainer(
        "minipagerapplet.desktop",
        true,
        QString::null,
	_opMenu,
        viewport() ) );

    // taskbar applet
    containers.append( manager->createAppletContainer(
        "taskbarapplet.desktop",
        true,
        QString::null,
	_opMenu,
        viewport() ) );

    // system tray applet
    AppletContainer *a = manager->createAppletContainer(
        "systemtrayapplet.desktop",
        true,
        QString::null,
	_opMenu,
        viewport() );
    a->setFreeSpace( 1 );
    containers.append( a );

    // clock applet
    a = manager->createAppletContainer(
        "clockapplet.desktop",
        true,
        QString::null,
	_opMenu,
        viewport() );
    a->setFreeSpace( 1 );
    containers.append( a );

    if( QApplication::reverseLayout() ) {
         ContainerIterator it(containers);
         it.toLast();
         for( ; it.current(); --it ) {
             addContainer( it.current() );
         }
    } else {
        ContainerIterator it(containers);
        for( ; it.current(); ++it ) {
             addContainer( it.current() );
        }
    }

    layoutChildren();
    saveContainerConfig();
}

void ContainerArea::saveContainerConfig( bool layoutOnly )
{
//    kdDebug(1210) << "ContainerArea::saveContainerConfig( " << layoutOnly << " )" << endl;

    // build the applet list
    QStringList alist;

    for( ContainerIterator it(_containers); it.current(); ++it )
    {
        BaseContainer* a = it.current();

        alist.append( a->appletId() );

        KConfigGroup group( _config, a->appletId().latin1() );
        a->saveConfiguration( group, layoutOnly );
    }

    KConfigGroup group( _config, "General" );
    group.writeEntry("Applets", alist);

    _config->sync();
}

void ContainerArea::loadContainerConfig()
{
    removeAllContainers();

    // read applet list
    KConfigGroup group( _config, "General" );
    QStringList alist = group.readListEntry("Applets");

    // now restore the applets
    for( QStringList::Iterator it = alist.begin(); it != alist.end(); ++it )
    {
        QString appletId(*it);

        // is there a config group for this applet?
        if (!_config->hasGroup(appletId)) continue;

        KConfigGroup group(_config, appletId.latin1());

        BaseContainer* a = 0;

        int sep = appletId.findRev('_');
        Q_ASSERT(sep != -1);
        QString appletType = appletId.left(sep);

        // create a matching applet container
        if (appletType == "KMenuButton")
            a = new KMenuButtonContainer(_opMenu, viewport());
        else if (appletType == "DesktopButton")
            a = new DesktopButtonContainer(_opMenu, viewport());
        else if (appletType == "WindowListButton")
            a = new WindowListButtonContainer(_opMenu, viewport());
        else if ((appletType == "BookmarksButton") && kapp->authorizeKAction("bookmarks"))
            a = new BookmarksButtonContainer(_opMenu, viewport());
        else if (appletType == "ServiceButton")
            a = new ServiceButtonContainer(group, _opMenu, viewport());
        else if (appletType == "URLButton")
            a = new URLButtonContainer(group, _opMenu, viewport());
        else if (appletType == "BrowserButton")
            a = new BrowserButtonContainer(group, _opMenu, viewport());
        else if (appletType == "ServiceMenuButton")
            a = new ServiceMenuButtonContainer(group, _opMenu, viewport());
        else if (appletType == "ExeButton")
            a = new NonKDEAppButtonContainer(group, _opMenu, viewport());
        else if (appletType == "ExtensionButton")
            a = new ExtensionButtonContainer(group, _opMenu, viewport());
        else if (appletType == "Applet")
            a = PluginManager::pluginManager()->createAppletContainer(
                   group.readPathEntry("DesktopFile"),
                   true, // isStartup
                   group.readPathEntry("ConfigFile"),
		   _opMenu,
                   viewport() );
        if (a != 0 && a->isValid()) {
            a->setAppletId(appletId);
            a->loadConfiguration(group);
            addContainer(a);
        }
        else {
            delete a;
        }
    }

    layoutChildren();
}

void ContainerArea::removeAllContainers()
{
    while ( !_containers.isEmpty() ) {
	BaseContainer* b = _containers.first();
	_containers.removeRef( b );
	delete b;
    }
    emit sizeHintChanged();
}

void ContainerArea::configure()
{
    setBackgroundTheme();

    for( ContainerIterator it(_containers); it.current(); ++it ) {
        (*it)->configure();
    }
}

void ContainerArea::addKMenuButton()
{
    KMenuButtonContainer *b = new KMenuButtonContainer(_opMenu, viewport());
    addContainer(b);
    moveToFirstFreePosition(b);
    scrollTo(b);
    saveContainerConfig();
}

void ContainerArea::addDesktopButton()
{
    DesktopButtonContainer *b = new DesktopButtonContainer(_opMenu, viewport());
    addContainer(b);
    moveToFirstFreePosition(b);
    scrollTo(b);
    saveContainerConfig();
}

void ContainerArea::addWindowListButton()
{
    WindowListButtonContainer *b = new WindowListButtonContainer(_opMenu, viewport());
    addContainer(b);
    moveToFirstFreePosition(b);
    scrollTo(b);
    saveContainerConfig();
}

void ContainerArea::addBookmarksButton()
{
    BookmarksButtonContainer *b = new BookmarksButtonContainer(_opMenu, viewport());
    addContainer(b);
    moveToFirstFreePosition(b);
    scrollTo(b);
    saveContainerConfig();
}

void ContainerArea::addServiceButton(const QString& desktopFile)
{
    ServiceButtonContainer *b = new ServiceButtonContainer(desktopFile, _opMenu, viewport());
    addContainer(b);
    moveToFirstFreePosition(b);
    scrollTo(b);
    saveContainerConfig();
}

void ContainerArea::addURLButton(const QString &url)
{
    URLButtonContainer *b = new URLButtonContainer(url, _opMenu, viewport());
    addContainer(b);
    moveToFirstFreePosition(b);
    scrollTo(b);
    saveContainerConfig();
}

void ContainerArea::addBrowserButton( const QString &startDir, const QString& icon )
{
    BrowserButtonContainer *b = new BrowserButtonContainer(startDir, _opMenu, icon, viewport());
    addContainer(b);
    moveToFirstFreePosition(b);
    scrollTo(b);
    saveContainerConfig();
}

void ContainerArea::addServiceMenuButton(const QString& relPath)
{
    ServiceMenuButtonContainer *b = new ServiceMenuButtonContainer(relPath, _opMenu, viewport());
    addContainer(b);
    moveToFirstFreePosition(b);
    scrollTo(b);
    saveContainerConfig();
}

void ContainerArea::addNonKDEAppButton(const QString &filePath, const QString &icon,
				 const QString &cmdLine, bool inTerm)
{
    NonKDEAppButtonContainer *b = new NonKDEAppButtonContainer(filePath, icon, cmdLine, inTerm, _opMenu, viewport());
    addContainer(b);
    moveToFirstFreePosition(b);
    scrollTo(b);
    saveContainerConfig();
}

void ContainerArea::addExtensionButton(const QString& df)
{
    ExtensionButtonContainer *b = new ExtensionButtonContainer(df, _opMenu, viewport());
    addContainer(b);
    moveToFirstFreePosition(b);
    scrollTo(b);
    saveContainerConfig();
}

void ContainerArea::addApplet( const QString& desktopFile )
{
    AppletContainer* a = PluginManager::pluginManager()->createAppletContainer(
        desktopFile,
        false,         // not startup
        QString::null, // no config
	_opMenu,
        viewport() );

    if(!a) return;

    addContainer(a);
    moveToFirstFreePosition(a);
    scrollTo(a);
    saveContainerConfig();
}

void ContainerArea::addContainer(BaseContainer* a)
{
    if (!a) return;

    if (a->appletId().isNull())
	a->setAppletId(createUniqueId(a->appletType()));

    _containers.append(a);

    emit sizeHintChanged();

    connect(a, SIGNAL(moveme(BaseContainer*) ),
	    SLOT( startContainerMove(BaseContainer*)));
    connect(a, SIGNAL(removeme(BaseContainer*) ),
	    SLOT( slotRemoveContainer(BaseContainer*)));
    connect(a, SIGNAL(requestSave()),
	    SLOT(slotSaveContainerConfig()));

    if (a->inherits("ExternalAppletContainer"))
	connect(a, SIGNAL(embeddedWindowDestroyed() ), this,
		SLOT( embeddedWindowDestroyed()));
    if (a->inherits("InternalAppletContainer")
	|| a->inherits("ExternalAppletContainer"))
	connect(a, SIGNAL(updateLayout() ), this,
		SLOT( slotLayoutChildren()));

    a->slotSetOrientation( orientation() );
    a->slotSetPopupDirection( popupDirection() );
    a->configure();
    addChild(a);
    a->show();
}

void ContainerArea::removeContainer(BaseContainer *a)
{
    if (a) {
	removeChild(a);
	a->slotRemoved();
	_containers.removeRef(a);
        a->deleteLater();
        a = 0;
	//delete a;
    }

    updateContainerList();
    emit sizeHintChanged();
    layoutChildren();
    saveContainerConfig(true);
}

QString ContainerArea::createUniqueId(const QString& appletType) const
{
    QString idBase = appletType + "_%1";
    QString newId;
    int i = 0;
    bool unique = false;

    while(!unique) {
        i++;
        newId = idBase.arg(i);

        unique = true;
        for( ContainerIterator it(_containers); it.current() ; ++it ) {
            BaseContainer* b = it.current();
            if (b->appletId() == newId) {
                unique = false;
                break;
            }
        }
    }
    return newId;
}

void ContainerArea::disableStretch()
{
    for( ContainerIterator it(_containers); it.current() ; ++it ) {
        BaseContainer* b = it.current();
        if( orientation() == Horizontal ) {
            if( QApplication::reverseLayout() )
                b->move( b->geometry().right() - b->widthForHeight( height() ) + 1, b->y() );
            b->resize( b->widthForHeight(height()), height() );
        } else {
            b->resize( width(), b->heightForWidth(width()) );
        }
    }
}

void ContainerArea::restoreStretch()
{
    ContainerIterator it(_containers);
    if( !QApplication::reverseLayout() || orientation() == Vertical ) {
        BaseContainer* next = 0;
        for( it.toLast(); it.current(); --it ) {
            BaseContainer* b = it.current();
            if( b->isStretch() ) {
                if( orientation() == Horizontal ) {
                    if( next ) b->resize( next->x() - b->x(), height() );
                    else       b->resize( width()   - b->x(), height() );
                } else {
                    if( next ) b->resize( width(), next->y() - b->y() );
                    else       b->resize( width(),  height() - b->y() );
                }
            }
            next = b;
        }
    } else {
        BaseContainer* prev = 0;
        for( it.toFirst(); it.current(); ++it ) {
            BaseContainer* b = it.current();
            if( b->isStretch() ) {
                if( prev )
                    b->setGeometry( QRect(
                        prev->geometry().right() + 1, 0,
                        b->geometry().right() - prev->geometry().right(), height() ) );
                else
                    b->setGeometry( QRect(
                        0, 0,
                        b->geometry().right() - 0, height() ) );
            }
            prev = b;
        }
    }
}

void ContainerArea::startContainerMove(BaseContainer *a)
{
    if (!a) return;

    _moveAC = a;
    _movingAC = true;

    if(_moveAC->inherits("ButtonContainer")) {
        static_cast<ButtonContainer*>(_moveAC)->button()->setZoomEnabled(false);
    }

    setMouseTracking(true);
    grabMouse(sizeAllCursor);

    _block_relayout = true;
    disableStretch();
    a->raise();
}

void ContainerArea::stopContainerMove(BaseContainer *b)
{
    if (_moveAC != b) return;

    _autoScrollTimer.stop();
    releaseMouse();
    setCursor(arrowCursor);
    _movingAC = false;
    setMouseTracking(false);

    if(_moveAC->inherits("ButtonContainer"))
    {
	static_cast<ButtonContainer*>(_moveAC)->completeMoveOperation();
        static_cast<ButtonContainer*>(_moveAC)->button()->setZoomEnabled(true);
    }

    _moveAC = 0;
    _block_relayout = false;

    updateContainerList();
    restoreStretch();
    saveContainerConfig(true);
}

void ContainerArea::mouseReleaseEvent(QMouseEvent *)
{
    if (_movingAC && _moveAC)
	stopContainerMove(_moveAC);
}

void ContainerArea::mouseMoveEvent(QMouseEvent *ev)
{
    if (!(_movingAC && _moveAC)) {
	Panner::mouseMoveEvent(ev);
	return;
    }

    int s;
    if (orientation() == Horizontal)
	s = width();
    else
	s = height();

    if (ev->state() & ShiftButton && s >= minimumUsedSpace( orientation(), width(), height() )) {

	if (orientation() == Horizontal) {
	    int oldX = _moveAC->x() + _moveAC->moveOffset().x();
	    int x = ev->pos().x();
	    moveContainerPush(_moveAC, x - oldX);
	}
	else if (orientation() == Vertical) {
	    int oldY = _moveAC->y() + _moveAC->moveOffset().y();
	    int y = ev->pos().y();
	    moveContainerPush(_moveAC, y - oldY);
	}
    }
    else {

	if (orientation() == Horizontal) {
	    int oldX = _moveAC->x() + _moveAC->moveOffset().x();
	    int x = ev->pos().x();
	    moveContainerSwitch(_moveAC, x - oldX);
	}
	else if (orientation() == Vertical) {
	    int oldY = _moveAC->y() + _moveAC->moveOffset().y();
	    int y = ev->pos().y();
	    moveContainerSwitch(_moveAC, y - oldY);
	}
    }
}

void ContainerArea::moveContainerSwitch(BaseContainer* moving, int distance)
{
    int nx =0;
    int ny = 0;
    bool scroll = false;

    // horizontal panel
    if (orientation() == Horizontal) {

	if (distance > 0) { // left to right

	    _containers.findRef(moving);
	    BaseContainer *next = _containers.next();
	    BaseContainer *last = moving;

	    while (next) {

		// 'moving' has completely passed applet 'next'.
		if ( next->x() + next->width() <= moving->x() + distance ) {
                    viewportToContents(next->x() - moving->width(), next->y(), nx, ny);
		    moveChild(next, nx, ny);
		    last = next;
		    next = _containers.next();
		    continue;
		}

		// 'next' has not been completely passed by 'moving', but
		// still may be covered by it.
		int switchMargin = 0;

		// calculate the position and width of the 'virtual' container
		// containing 'moving' and 'next'.
		int tx = next->x() - moving->width();
		int twidth = moving->width() + next->width();

		// determine the middle of the containers.
		int tmiddle = tx + twidth/2;
		int movingMiddle = moving->x() + distance + moving->width()/2;

		// move 'next' from the right side of the virtual container to
		// the left side if the middle of 'moving' has moved far enough
		// to the left, i.e. past the middle of the virtual container
		// plus the switchMargin. The switchMargin prevents rapidly
		// switching when 'moving' and 'next' have the same size.
		if (movingMiddle >= tmiddle + switchMargin) {
                    viewportToContents(next->x() - moving->width(), next->y(), nx, ny);
		    moveChild(next, nx, ny);
		    // store 'next', because it may become null in the next
		    // step.
		    last = next;
		    next = _containers.next();
		    continue;
		}

		// 'moving' doesn't cover 'next', and hasn't passed it. Then
		// we know that this also yields for the rest of the applets,
		// so leave the loop.
		break;
	    }

	    int newX;

	    if (last != moving) {
		newX = QMAX(last->x() + last->width(), moving->x() + distance);
                viewportToContents(newX, moving->y(), nx, ny);
		moveChild(moving, nx, ny);

		// Move 'moving' to its new position in the container list.
		_containers.removeRef(moving);
		_containers.insert( _containers.findRef(last) + 1, moving );
	    }
	    else
		if (next && moving->x() + distance >= next->x() - moving->width())
		    newX = next->x() - moving->width();
		else
		    newX = moving->x() + distance;

            if(newX >= width() - moving->width() - 80)
                scroll = true;

	    // Make sure the container isn't moved outside of the panel.
            viewportToContents(newX, moving->y(), nx, ny);
	    nx = QMIN(nx, contentsWidth() - moving->width());
	    moveChild(moving, nx, ny);

            if(scroll) {
                if(!_autoScrollTimer.isActive())
                    _autoScrollTimer.start(50);
                scrollBy(10, 0);
            }
	}

	else if (distance < 0) { // right to left

	    _containers.findRef(moving);
	    BaseContainer *prev = _containers.prev();
	    BaseContainer *last = moving;

	    while (prev) {

		if ( moving->x() + distance + moving->width() <= prev->x() ) {
                    viewportToContents(prev->x() + moving->width(), prev->y(), nx, ny);
		    moveChild(prev, nx, ny);
		    last = prev;
		    prev = _containers.prev();
		    continue;
		}

		int switchMargin = 0;

		// calculate the position and width of the 'virtual' container
		// containing 'moving' and 'prev'.
		int tx = prev->x();
		int twidth = moving->width() + prev->width();

		// determine the middle of the containers.
		int tmiddle = tx + twidth/2;
		int movingMiddle = moving->x() + distance + moving->width()/2;

		// move a from the left side of the virtual container to the
		// right side if the middle of 'moving' has moved past the
		// middle of the virtual container plus the switchMargin. The
		// switchMargin prevents rapidly switching when 'moving' and
		// 'prev' have the same size.
		if (movingMiddle <= tmiddle + switchMargin) {
                    viewportToContents(prev->x() + moving->width(), prev->y(), nx, ny);
		    moveChild(prev, nx, ny);
		    last = prev;
		    prev = _containers.prev();
		    continue;
		}

		break;
	    }

	    int newX;

	    if (last != moving) {
		newX = QMIN(last->x() - moving->width(), moving->x() + distance);
		// Move 'moving' to its new position in the container list.
		_containers.removeRef(moving);
		_containers.insert( _containers.findRef(last), moving );
	    }
	    else
		if (prev && moving->x() + distance < prev->x() + prev->width())
		    newX = prev->x() + prev->width();
		else
		    newX = moving->x() + distance;

            if(newX <= 80)
                scroll = true;

	    // Make sure the container isn't moved outside of the panel.
            viewportToContents(newX, moving->y(), nx, ny);
	    nx = QMAX(nx, 0);
            moveChild(moving, nx, ny);

            if(scroll) {
                if(!_autoScrollTimer.isActive())
                    _autoScrollTimer.start(50);
                scrollBy(-10, 0);
            }
	}
    }

    // vertical panel
    else if (orientation() == Vertical) {

	if (distance > 0) { // top to bottom

	    _containers.findRef(moving);
	    BaseContainer *next = _containers.next();
	    BaseContainer *last = moving;

	    while (next) {

		if ( next->y() + next->height() <= moving->y() + distance) {
                    viewportToContents(next->x(), next->y() - moving->height(), nx, ny);
		    moveChild(next, nx, ny);
		    last = next;
		    next = _containers.next();
		    continue;
		}

		int switchMargin = 0;

		// calculate the position and height of the 'virtual' container
		// containing 'moving' and 'next'.
		int ty = next->y() - moving->height();
		int theight = moving->height() + next->height();

		// determine the middle of the containers.
		int tmiddle = ty + theight/2;
		int movingMiddle = moving->y() + distance + moving->height()/2;

		// move 'next' from the bottom of the virtual container to the
		// top side if the middle of 'moving' has moved past the middle
		// of the virtual container plus the switchMargin. The
		// switchMargin prevents rapidly switching when 'moving' and
		// 'next' have the same size.
		if (movingMiddle >= tmiddle + switchMargin) {
                    viewportToContents(next->x(), next->y() - moving->height(), nx, ny);
		    moveChild(next, nx, ny);
		    last = next;
		    next = _containers.next();
		    continue;
		}

		break;
	    }

	    int newY;

	    if (last != moving) {
		newY = QMAX(last->y() + last->height(), moving->y() + distance);

		// Move 'moving' to its new position in the container list.
		_containers.removeRef(moving);
		_containers.insert( _containers.findRef(last) + 1, moving );
	    }
	    else
		if (next && moving->y() + distance >= next->y() - moving->height())
		    newY = next->y() - moving->height();
		else
		    newY = moving->y() + distance;

            if(newY >= height() - moving->height() - 80)
                scroll = true;

	    // Make sure the container isn't moved outside of the panel.
            viewportToContents(moving->x(), newY, nx, ny);
	    ny = QMIN(ny, contentsHeight() - moving->height());
	    moveChild(moving, nx, ny);

            if(scroll) {
                if(!_autoScrollTimer.isActive())
                    _autoScrollTimer.start(50);
                scrollBy(0, 10);
            }
	}

	else if (distance < 0) { // bottom to top

	    _containers.findRef(moving);
	    BaseContainer *prev = _containers.prev();
	    BaseContainer *last = moving;

	    while (prev) {

		if ( moving->y() + moving->height() <= prev->y() ) {
                    viewportToContents(prev->x(), prev->y() + moving->height(), nx, ny);
		    moveChild(prev, nx, ny);
		    last = prev;
		    prev = _containers.prev();
		    continue;
		}

		int switchMargin = 0;

		// calculate the position and height of the 'virtual' container
		// containing 'moving' and 'prev'.
		int ty = prev->y();
		int theight = moving->height() + prev->height();

		// determine the middle of the containers.
		int tmiddle = ty + theight/2;
		int movingMiddle = moving->y() + distance + moving->height()/2;

		// move 'prev' from the top of the virtual container to the
		// bottom if the middle of 'moving' has moved past the middle
		// of the virtual container plus the switchMargin. The
		// switchMargin prevents rapidly switching when 'moving' and
		// 'prev' have the same size.
		if (movingMiddle <= tmiddle + switchMargin) {
                    viewportToContents(prev->x(), prev->y() + moving->height(), nx, ny);
		    moveChild(prev, nx, ny);
		    last = prev;
		    prev = _containers.prev();
		    continue;
		}

		break;
	    }

	    int newY;

	    if (last != moving) {
		newY = QMIN(last->y() - moving->height(), moving->y() + distance);
                viewportToContents(moving->x(), newY, nx, ny);
		moveChild(moving, nx, ny);

		// Move 'moving' to its new position in the container list.
		_containers.removeRef(moving);
		_containers.insert( _containers.findRef(last), moving );
	    }
	    else
		if (prev && moving->y() + distance < prev->y() + prev->height())
		    newY = prev->y() + prev->height();
		else
		    newY = moving->y() + distance;

            if(newY <= 80)
                scroll = true;

	    // Make sure the container isn't moved outside of the panel.
            viewportToContents(moving->x(), newY, nx, ny);
	    ny = QMAX(ny, 0);
	    moveChild(moving, nx, ny);

            if(scroll) {
                if(!_autoScrollTimer.isActive())
                    _autoScrollTimer.start(50);
                scrollBy(0, - 10);
            }
	}
    }
}

int ContainerArea::moveContainerPush(BaseContainer* a, int distance)
{
    // Point the iterator 'it' to 'a'.
    ContainerIterator it(_containers);
    while (it.current() && it.current() != a)
	++it;

    return moveContainerPushRecursive(it, distance);
}

int ContainerArea::moveContainerPushRecursive(ContainerIterator it, int distanceRequest)
{
    int distanceAvailable, distanceMoved;
    BaseContainer* a = it.current();
    BaseContainer* b;

    if (orientation() == Horizontal) {

	if (distanceRequest < 0) {
	    // Find the previous container. If it exists, determine the
	    // distance between the two containers.
	    b = --it;
	    if (!b)
		distanceAvailable = -a->x();
	    else {
		distanceAvailable = b->x() - a->x() + b->width();
		if (distanceRequest - distanceAvailable < 0)
		    distanceAvailable += moveContainerPushRecursive(it, distanceRequest - distanceAvailable);
	    }
	    distanceMoved = QMAX(distanceRequest, distanceAvailable);
	}
	else if (distanceRequest > 0) {
	    // Find the next container. If it exists, determine the distance
	    // between the two containers.
	    b = ++it;
	    if (!b)
		distanceAvailable = width() - a->x() - a->width();
	    else {
		distanceAvailable = b->x() - a->x() - a->width();
		if (distanceRequest - distanceAvailable > 0)
		    distanceAvailable += moveContainerPushRecursive(it, distanceRequest - distanceAvailable);
	    }
	    distanceMoved = QMIN(distanceRequest, distanceAvailable);
	}
	else
	    return 0;

	moveChild(a, a->x() + distanceMoved, a->y());
	return distanceMoved;
    }
    else if (orientation() == Vertical) {

	if (distanceRequest < 0) {
	    // Find the previous container. If it exists, determine the
	    // distance between the current and the previous container.
	    // If this distance is not enough to comply to the request,
	    // try to push the previous container.
	    b = --it;
	    if (!b)
		distanceAvailable = -a->y();
	    else {
		distanceAvailable = b->y() - a->y() + b->height();
		if (distanceRequest - distanceAvailable < 0)
		    distanceAvailable += moveContainerPushRecursive(it, distanceRequest - distanceAvailable);
	    }
	    distanceMoved = QMAX(distanceRequest, distanceAvailable);
	}
	else if (distanceRequest > 0) {
	    // Find the next container. If it exists, determine the distance
	    // between the current and the next container. If this distance is
	    // not enough to comply to the request, try to push the next
	    // container.
	    b = ++it;
	    if (!b)
		distanceAvailable = height() - a->y() - a->height();
	    else {
		distanceAvailable = b->y() - a->y() - a->height();
		if (distanceRequest - distanceAvailable > 0)
		    distanceAvailable += moveContainerPushRecursive(it, distanceRequest - distanceAvailable);
	    }
	    distanceMoved = QMIN(distanceRequest, distanceAvailable);
	}
	else
	    return 0;

	moveChild(a, a->x(), a->y() + distanceMoved);
	return distanceMoved;
    }

    return 0;
}

int ContainerArea::position() const
{
    return static_cast<int>(_pos);
}

Direction ContainerArea::popupDirection() const
{
    Direction dir;
    switch (_pos)
	{
	case ::Left:
	    dir = ::dRight;
	    break;
	case ::Right:
	    dir = ::dLeft;
	    break;
	case ::Top:
	    dir = ::dDown;
	    break;
	case ::Bottom:
	default:
	    dir = ::dUp;
	    break;
	}
    return dir;
}

void ContainerArea::slotLayoutChildren()
{
    layoutChildren();
    emit sizeHintChanged();
}

void ContainerArea::embeddedWindowDestroyed()
{
    if (sender() && sender()->inherits("ExternalAppletContainer"))
	removeContainer((ExternalAppletContainer*)sender());
}

void ContainerArea::layoutChildren()
{
    if (_block_relayout) return;

//    kdDebug(1210) << "ContainerArea::layoutChildren()" << endl;

    QSize newsize = size();
    int mus = minimumUsedSpace( orientation(), width(), height() );

    if (orientation() == Horizontal) {
	if (newsize.width() < mus)
	    newsize.setWidth(mus);
    }
    else {
	if (newsize.height() < mus)
	    newsize.setHeight(mus);
    }
    resizeContents(newsize.width(), newsize.height());

    int pos = 0;

    int occupiedspace = 0;
    int freespace = totalFreeSpace();

    ContainerIterator it(_containers);
    for ( ; it.current(); ++it )
	{
	    BaseContainer* a = (*it);

	    // get pointer to the nextapplet
	    ++it;
	    BaseContainer *next = (*it);
	    --it;

            float fs = a->freeSpace();
            if(fs > 1) fs = 1;

            float nfs = 0;
            if(next) {
                nfs = next->freeSpace();
                if(nfs > 1) nfs = 1;
            }

	    double fspace = fs * freespace;

	    if ((fspace - floor(fspace)) > 0.5)
		fspace += 1;
	    pos = static_cast<int>(fspace) + occupiedspace;

	    if (orientation() == Horizontal) {
		moveChild(a, pos, 0);
		int w = a->widthForHeight(height());
		if( a->isStretch() ) {
		    if (next)
			a->resize(w + int((nfs - fs)*freespace), height());
		    else
			a->resize(width() - a->x(), height()); // FIXME
		}
		else
		    a->resize(w, height());
		occupiedspace += w;
	    }
	    else {
		moveChild(a, 0, pos);
		int h = a->heightForWidth(width());
		if( a->isStretch() ) {
		    if (next)
			a->resize(width(), h + int((nfs - fs)*freespace));
		    else
			a->resize(width(), height() - a->y());
		}
		else
		    a->resize(width(), h);
		occupiedspace += h;
	    }
	}
}

void ContainerArea::dragEnterEvent(QDragEnterEvent *ev)
{
    ev->accept(QUriDrag::canDecode(ev));
    disableStretch();

    if (!_dragIndicator)
        _dragIndicator = new DragIndicator(this);
    if (orientation() == Horizontal)
        _dragIndicator->setPreferredSize(QSize(height(), height()));
    else
        _dragIndicator->setPreferredSize(QSize(width(), width()));

    _dragMoveOffset =
        QPoint(_dragIndicator->width()/2, _dragIndicator->height()/2);

    // Find the container before the position of the dragindicator.
    ContainerIterator it(_containers);
    it.toLast();
    while (it.current())
    {
        BaseContainer* a = it.current();

        if (orientation() == Horizontal &&
                a->x() < ev->pos().x() - _dragMoveOffset.x()
         || orientation() == Vertical &&
                a->y() < ev->pos().y() - _dragMoveOffset.y() )
        {
            _dragMoveAC = a;
            break;
        }

        --it;
    }

    if (orientation() == Horizontal)
        moveDragIndicator((ev->pos() - _dragMoveOffset).x());
    else
        moveDragIndicator((ev->pos() - _dragMoveOffset).y());

    _dragIndicator->show();
    QTimer::singleShot(30000, _dragIndicator, SLOT(hide()));
}

void ContainerArea::dragMoveEvent(QDragMoveEvent* ev)
{
    if (orientation() == Horizontal)
        moveDragIndicator((ev->pos() - _dragMoveOffset).x());
    else
        moveDragIndicator((ev->pos() - _dragMoveOffset).y());
}

void ContainerArea::dragLeaveEvent(QDragLeaveEvent*)
{
    _dragIndicator->hide();
    restoreStretch();
}

void ContainerArea::dropEvent(QDropEvent *ev)
{
    QStringList uriList;

    if( !QUriDrag::decodeToUnicodeUris(ev, uriList) ) {
        _dragIndicator->hide();
        restoreStretch();
        return;
    }

    kdDebug() << "dropEvent()" << endl;

    QStringList::ConstIterator it(uriList.begin());
    for (; it != uriList.end(); ++it) {

        BaseContainer* a;
        KURL url(*it);
        // see if it's a executable or directory
        if( url.isLocalFile() ) {

            QFileInfo fi(url.path());
            if( fi.isDir() ) { // directory

                PanelDirDropMenu mnu;
                switch(mnu.exec(mapToGlobal(ev->pos()))) {
                case PanelDirDropMenu::Browser:
                    a = new BrowserButtonContainer(url.path(), _opMenu, KMimeType::iconForURL(url), viewport());
                    break;
                case PanelDirDropMenu::Url:
                    a = new URLButtonContainer(*it, _opMenu, viewport());
                    break;
                default:
                    _dragIndicator->hide();
                    restoreStretch();
                    return;
                }

            } else if( fi.isExecutable() ) { // non-KDE executable

                QString pixmapFile;
                KMimeType::pixmapForURL( url.path(), 0, KIcon::Panel, 0,
                                         KIcon::DefaultState, &pixmapFile );
                PanelExeDialog dlg( url.path(), pixmapFile,
                                    QString::null, false, 0 );
                if(dlg.exec() != QDialog::Accepted) {
                    _dragIndicator->hide();
                    restoreStretch();
                    return;
                }
                // KIconloader returns a full path, we only want name
                QFileInfo iconfi(dlg.icon());
                a = new NonKDEAppButtonContainer(
		         url.path(), iconfi.fileName(),
                         dlg.commandLine(), dlg.useTerminal(), _opMenu, viewport() );
            } else if ( KMimeType::findByURL(url)->name() == "application/x-desktop" ) {
                // a local desktop file being dragged from an external program.
                // Make a copy first.
                KURL dest;
                dest.setPath( locateLocal("appdata",url.fileName()) );
                KIO::NetAccess::upload(url.path(), dest); // Copy

                a = new URLButtonContainer(dest.path(), _opMenu, viewport());
            } else { // some unknown local file
		a = new URLButtonContainer(*it, _opMenu, viewport());
            }
        } else { // a internet URL
            a = new URLButtonContainer(*it, _opMenu, viewport());
        }

        // Move the neighbour containers if there isn't enough space
        if (_dragIndicator->size() != _dragIndicator->preferredSize()) {
            int neededSpace;
            int distanceMoved;
            BaseContainer* next;

            if (_dragMoveAC) {
               _containers.findRef(_dragMoveAC);
                next = _containers.next();
            } else {
                next = _containers.first();
            }

            if (orientation() == Horizontal) {
                neededSpace = _dragIndicator->preferredSize().width() - _dragIndicator->width();
                if (_dragMoveAC) {
                    distanceMoved = moveContainerPush(_dragMoveAC, -neededSpace/2);
                    _dragIndicator->move(
                         _dragIndicator->x() + distanceMoved,
                         _dragIndicator->y());
                    neededSpace += distanceMoved;
                }
                if (next)
                    neededSpace -= moveContainerPush(next, neededSpace);
                if (_dragMoveAC) {
                    distanceMoved = moveContainerPush(_dragMoveAC, -neededSpace);
                   _dragIndicator->move(
                       _dragIndicator->x() + distanceMoved,
                       _dragIndicator->y());
                }
            } else {
                neededSpace = _dragIndicator->preferredSize().height() - _dragIndicator->height();
                if (_dragMoveAC) {
                    distanceMoved = moveContainerPush(_dragMoveAC, -neededSpace/2);
                    _dragIndicator->move(
                        _dragIndicator->x(),
                        _dragIndicator->y() + distanceMoved);
                    neededSpace += distanceMoved;
                }
                if (next)
                    neededSpace -= moveContainerPush(next, neededSpace);
                if (_dragMoveAC) {
                    distanceMoved = moveContainerPush(_dragMoveAC, -neededSpace);
                    _dragIndicator->move(
                        _dragIndicator->x(),
                        _dragIndicator->y() + distanceMoved);
                }
            }
        }

        addContainer(a);
        moveChild(a, _dragIndicator->x(), _dragIndicator->y());
        updateContainerList();
	saveContainerConfig();
    }
    _dragIndicator->hide();
    restoreStretch();
    layoutChildren();
}

void ContainerArea::resizeEvent(QResizeEvent *ev)
{
    Panner::resizeEvent(ev);
    layoutChildren();
    setBackgroundTheme();
}

void ContainerArea::setBackgroundTheme()
{
    // set background pixmap
    KConfigGroupSaver saver(_config, "General");

    if (_config->readBoolEntry("UseBackgroundTheme", false)) {
	QString bgStr = _config->readEntry("BackgroundTheme", "");
        bgStr = locate("appdata", bgStr);
	if(!bgStr.isEmpty()){
	    QPixmap bgPix(bgStr);
	    if(!bgPix.isNull()){
		// Do we need to rotate the image
		QPixmap bgPixNew;

		if ( _config->readBoolEntry("RotateBackground", false) &&
		     orientation() == Vertical )
		    {
				// Rotate the pixmap before scaling
			QWMatrix m;
			m.rotate( -90.0 );
			bgPixNew = bgPix.xForm( m );
		    }
		else
		    {
				// Don't rotate the image - just copy it
			bgPixNew = bgPix;
		    }

		// Scale the image but keep the same aspect ratio
		QImage bgImage = bgPixNew.convertToImage();
		double dAspect = (double)bgPixNew.width() / (double)bgPixNew.height();

		int nNewWidth = width();
		int nNewHeight = height();
		if (orientation() == Vertical )
		    nNewHeight = (int)( (double)nNewWidth / dAspect );
		else
		    nNewWidth  = (int)( (double)nNewHeight * dAspect);
		QImage bgImageNew = bgImage.smoothScale( nNewWidth, nNewHeight );

		// Convert back to a QPixmap
		bgPixNew.convertFromImage( bgImageNew );

		QBrush bgBrush(colorGroup().background(), bgPixNew);
		QPalette pal = kapp->palette();
		pal.setBrush(QColorGroup::Background, bgBrush);
		setPalette(pal);
	    }
	    else {
		unsetPalette();
		kdWarning() << "Kicker: Error loading background theme pixmap\n";
	    }
	}
    }
    else {
	unsetPalette();
    }
}

QRect ContainerArea::availableSpaceFollowing(BaseContainer* a)
{
    QRect availableSpace = rect();
    BaseContainer* b;

    if (a)
    {
        _containers.findRef(a);
        b = _containers.next();
    }
    else
        b = _containers.first();

    if (orientation() == Horizontal)
    {
        if (a)
            availableSpace.setLeft(a->x() + a->width());
        if (b)
            availableSpace.setRight(b->x() - 1);
    }
    else
    {
        if (a)
            availableSpace.setTop(a->y() + a->height());
        if (b)
            availableSpace.setBottom(b->y() - 1);
    }

    return availableSpace;
}

void ContainerArea::moveDragIndicator(int pos)
{
    QRect availableSpace = availableSpaceFollowing(_dragMoveAC);

    // Move _dragIndicator to position pos, restricted by availableSpace.
    // Resize _dragIndicator if necessary.
    if (orientation() == Horizontal)
    {
        if (availableSpace.size().width() <
                _dragIndicator->preferredSize().width())
        {
            _dragIndicator->resize(availableSpace.size());
            _dragIndicator->move(availableSpace.topLeft());
        }
        else
        {
            int newX = pos;
            _dragIndicator->resize(_dragIndicator->preferredSize());
            newX = QMAX(newX, availableSpace.left());
            newX = QMIN(newX,
                availableSpace.right() + 1 - _dragIndicator->width() );
            _dragIndicator->move(newX, availableSpace.top());
        }
    }
    else
    {
        if (availableSpace.size().height() <
                _dragIndicator->preferredSize().height())
        {
            _dragIndicator->resize(availableSpace.size());
            _dragIndicator->move(availableSpace.topLeft());
        }
        else
        {
            int newY = pos;
            _dragIndicator->resize(_dragIndicator->preferredSize());
            newY = QMAX(newY, availableSpace.top());
            newY = QMIN(newY,
                availableSpace.bottom() + 1 - _dragIndicator->height() );
            _dragIndicator->move(availableSpace.left(), newY);
        }
    }
}

void ContainerArea::moveToFirstFreePosition(BaseContainer* a)
{
    Orientation orient = orientation();

    int w = a->widthForHeight(height());
    int h = a->heightForWidth(width());

    bool stretch = false;
    bool found = false;

    ContainerIterator it(_containers);
    for(; it.current() ; ++it)
	{
	    BaseContainer* b = it.current();

	    int space = relativeContainerPos(b);

	    if (orient == Horizontal) {
		if (space >= w)
		    {
			if(stretch)
			    moveChild(a, b->x() - w, a->y());
			else
			    moveChild(a, b->x() - space, a->y());
			found = true;
			break;
		    }
	    }
	    else {
		if (space >= h)
		    {
			if(stretch)
			    moveChild(a, a->x(), b->y() - h);
			else
			    moveChild(a, a->x(), b->y() - space);
			found = true;
			break;
		    }
	    }
	    stretch = b->isStretch();
	}

    if (found)
	updateContainerList();
    else {
//        kdDebug() << "ContainerArea::moveToFirstFreePosition: trail" << endl;
        BaseContainer* last = _containers.last();

        if(orient == Horizontal)
            moveChild(a, last->x() + last->width() + 1, a->y());
        else
            moveChild(a, a->x(), last->y() + last->height() + 1);
    }
    layoutChildren();
}

BaseContainer* ContainerArea::coversContainer(BaseContainer *a, bool strict)
{
    BaseContainer *b;
    ContainerIterator it(_containers);

    for(; it.current() ; ++it)
	{
	    b = (BaseContainer*)it.current();

	    if (b == a) continue;

	    if ( orientation() == Horizontal ) {
		int bl, br;
		if (strict) {
		    bl = b->x();
		    br = b->x() + b->width();
		}
		else {
		    bl = b->x() + 10;
		    br = b->x() + b->width() - 10;
		}

		int btnl = a->x();
		int btnr = btnl + a->width();

		if ((btnl >= bl) && (btnl <= br))
		    return b;
		else if ((btnr >= bl) && (btnr <= br))
		    return b;
	    }
	    else {
		int bt, bb;
		if (strict) {
		    bt = b->y();
		    bb = b->y() + b->height();
		}
		else {
		    bt = b->y() + 10;
		    bb = b->y() + b->height() - 10;
		}
		int btnt = a->y();
		int btnb = btnt + a->height();

		if ((btnt >= bt) && (btnt <= bb))
		    return b;
		else if ((btnb >= bt) && (btnb <= bb))
		    return b;
	    }
	}
    return 0;
}

void ContainerArea::updateContainerList()
{
    ContainerList sorted;

    while(!_containers.isEmpty())
	{
	    BaseContainer *b = 0;
	    int pos = 9999;

	    ContainerIterator it(_containers);

	    for(; it.current() ; ++it)
		{
		    BaseContainer* a = it.current();

		    if(orientation() == Horizontal)
			{
			    if (a->x() < pos) {
				b = a;
				pos = a->x();
			    }
			}
		    else
			{
			    if (a->y() < pos) {
				b = a;
				pos = a->y();
			    }
			}
		}

	    if (b) {
		sorted.append(b);
		_containers.remove(b);
	    }
	}
    _containers = sorted;

    float freespace = totalFreeSpace();
    float fspace = 0;

    ContainerIterator it(_containers);
    for(; it.current() ; ++it)
	{
	    fspace += relativeContainerPos(it.current());
	    if (fspace < 0) fspace = 0;
            double ssf = ( freespace == 0 ? 0 : fspace/freespace );
            if (ssf > 1) ssf = 1;
            if(ssf < 0) ssf = 0;
	    it.current()->setFreeSpace(ssf);
	}
}

int ContainerArea::totalFreeSpace() const
{
    int availablespace;

    if(orientation() == Horizontal) {
	if(contentsWidth() > width())
	    availablespace = contentsWidth();
	else
	    availablespace = width();
    }
    else {
	if (contentsHeight() > height())
	    availablespace = contentsHeight();
	else
	    availablespace = height();
    }

    int freespace = availablespace - minimumUsedSpace( orientation(), width(), height() );
    if (freespace < 0) freespace = 0;

    return freespace;
}

int ContainerArea::minimumUsedSpace( Orientation o, int w, int h ) const
{
    int usedspace = 0;

    ContainerIterator it(_containers);
    for(; it.current() ; ++it)
	{
	    BaseContainer* a = it.current();

	    int space;
	    if(o == Horizontal) {
		space = a->widthForHeight(h);
	    } else
		space = a->heightForWidth(w);

	    if (space > 0)
		usedspace += space;
	}
    return usedspace;
}

int ContainerArea::relativeContainerPos(BaseContainer* b) const
{
    if (!b) return 0;
    if (!_containers.contains(b)) return 0;

    uint pos = 0;

    ContainerIterator it(_containers);
    for(; it.current() ; ++it) {
	BaseContainer* a = it.current();

	if (orientation() == Horizontal) {
	    if (a == b)  {
		int p = b->x() - pos;
		if (b < 0) return 0;
		return p;
	    } else
		pos = a->x() + a->widthForHeight(height());
	} else  {
	    if (a == b) {
		int p = b->y() - pos;
		if (b < 0) return 0;
		return p;
	    }
	    else
		pos = a->y() + a->heightForWidth(width());
	}
    }
    return 0;
}

void ContainerArea::slotSaveContainerConfig()
{
    saveContainerConfig();
}

void ContainerArea::slotRemoveContainer(BaseContainer* a)
{
    removeContainer(a);
}

void ContainerArea::setOrientation(Orientation o)
{
    Panner::setOrientation(o);

//    kdDebug(1210) << "ContainerArea::setOrientation()" << endl;

    ContainerIterator it(_containers);
    for ( ; it.current(); ++it )
        (*it)->slotSetOrientation(o);
}

void ContainerArea::setPosition(Position p)
{
    _pos = p;

    ContainerIterator it(_containers);
    for ( ; it.current(); ++it )
        (*it)->slotSetPopupDirection( popupDirection() );
}

void ContainerArea::setAlignment(Alignment a)
{
    ContainerIterator it(_containers);
    for ( ; it.current(); ++it )
        (*it)->setAlignment( a );
}

void ContainerArea::autoScroll()
{
    if(!_moveAC) return;

    if(orientation() == Horizontal) {
        if(_moveAC->pos().x() <= 80)
            scrollBy(-10, 0);
        else if(_moveAC->pos().x() >= width() - _moveAC->width() - 80)
            scrollBy(10, 0);
    }
    else {
        if(_moveAC->pos().y() <= 80)
            scrollBy(0, -10);
        else if(_moveAC->pos().y() >= height() - _moveAC->height() - 80)
            scrollBy(0, 10);
    }
}

void ContainerArea::scrollTo(BaseContainer* b)
{
    if(!b) return;

    int x, y;
    viewportToContents(b->pos().x(), b->pos().y(), x, y);
    ensureVisible(x, y);
}

ContainerList ContainerArea::containers( const QString& type ) const
{
    if ( type.isEmpty() || type == "All" )
	return _containers;

    ContainerList list;
    for( ContainerIterator it(_containers); it.current() ; ++it ) {
	if ( it.current()->appletType() == type )
	    list.append( it.current() );
    }
    return list;
}

void DragIndicator::paintEvent(QPaintEvent*)
{
    QPainter painter(this);
    QRect rect(0, 0, width(), height());
    style().drawPrimitive( QStyle::PE_FocusRect, &painter, rect, colorGroup(),
                           QStyle::Style_Default, colorGroup().base() );
}

void DragIndicator::mousePressEvent(QMouseEvent*)
{
    hide();
}


