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

Copyright (c) 2001 Matthias Elter <elter@kde.org>

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 <qlayout.h>
#include <qstringlist.h>

#include <kdebug.h>
#include <kglobal.h>
#include <kconfig.h>
#include <kstandarddirs.h>
#include <klocale.h>

#include "taskbar.h"
#include "taskbar.moc"
#include "taskcontainer.h"

TaskManager *TaskBar::manager = 0;

#define WINDOWLISTBUTTON_SIZE 12

#define BUTTON_MIN_HEIGHT 18
#define BUTTON_HEIGHT 20
#define BUTTON_MAX_WIDTH 200
#define BUTTON_MIN_WIDTH 20

TaskBar::TaskBar( QWidget *parent, const char *name )
    : Panner( parent, name )
{
    setFrameStyle( NoFrame );

    arrowType = LeftArrow;
    blocklayout = TRUE;

    // init
    setMinimumSize( WINDOWLISTBUTTON_SIZE, WINDOWLISTBUTTON_SIZE );
    setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ) );
    containers.setAutoDelete( FALSE );

    // setup animation frames
    frames = new PixmapList();

    frames->setAutoDelete( true );

    for ( int i=1; i<11; i++ )
	frames->append( new QPixmap( locate("data", "kicker/pics/disk" + QString::number(i) + ".png") ) );

    // configure
    configure();

    // connect manager
    connect( taskManager(), SIGNAL( taskAdded( Task* ) ), SLOT( add( Task* ) ) );
    connect( taskManager(), SIGNAL( taskRemoved( Task* ) ), SLOT( remove( Task* ) ) );
    connect( taskManager(), SIGNAL( startupAdded( Startup* ) ), SLOT( add( Startup* ) ) );
    connect( taskManager(), SIGNAL( startupRemoved( Startup* ) ), SLOT( remove( Startup* ) ) );
    connect( taskManager(), SIGNAL( desktopChanged( int ) ), SLOT( desktopChanged( int ) ) );
    connect( taskManager(), SIGNAL( windowDesktopChanged( WId ) ), SLOT( windowDesktopChanged( WId ) ) );

    // register existant tasks
    TaskList tasks = taskManager()->tasks();
    for (Task* t = tasks.first(); t!=0; t = tasks.next())
	add( t );

    // register existant startups
    StartupList startups = taskManager()->startups();
    for (Startup* s = startups.first(); s!=0; s = startups.next())
	add( s );

    blocklayout = FALSE;
}

TaskBar::~TaskBar()
{
    delete frames;
}

QSize TaskBar::sizeHint() const
{
    return QSize( BUTTON_MIN_WIDTH, BUTTON_MIN_HEIGHT );
}

QSize TaskBar::sizeHint( KPanelExtension::Position p, QSize maxSize) const
{
    if ( p == KPanelExtension::Left || p == KPanelExtension::Right ) {
	return QSize( maxButtonWidth, BUTTON_HEIGHT * containerCount() );
    } else {
	return QSize( maxSize.width(), BUTTON_HEIGHT );
    }
}

// These are the strings that are actually stored in the config file.
// They must be synchronized with kcmtaskbar. They are not translated.
const QStringList& TaskBar::actionList()
{
    static QStringList list(
            QStringList() << "Show Task List" << "Show Operations Menu"
            << "Activate, Raise or Minimize Task"
            << "Activate Task" << "Raise Task"
            << "Lower Task" << "Minimize Task" );
    return list;
}

// Translate from config entry name to enumeration
enum TaskBar::Action TaskBar::buttonAction( ButtonState button, const QString& actionName )
{
   int index = actionList().findIndex( actionName );
   if( index != -1 ) return static_cast<Action>(index);

   // Otherwise return the default.
   switch( button ) {
   case MidButton: return ActivateRaiseOrIconify;
   case RightButton: return ShowOperationsMenu;
   case LeftButton: // fall through
   default: return ShowTaskList;
   }
}

void TaskBar::configure()
{
   // read settings
    KConfig c( "ktaskbarrc", false, false );
    c.setGroup( "General" );

    showAllWindows = c.readBoolEntry( "ShowAllWindows", true );
    groupTasks = c.readBoolEntry( "GroupTasks", true );
    sortByDesktop = c.readBoolEntry( "SortByDesktop", true );
    showIcon = c.readBoolEntry( "ShowIcon", true );
    maxButtonWidth = c.readNumEntry( "MaximumButtonWidth", BUTTON_MAX_WIDTH );

    for ( TaskContainerIterator it(containers); it.current(); ++it ) {
	TaskContainer* c = it.current();
	c->setShowAll( showAllWindows );
	c->setSortByDesktop( sortByDesktop );
    }

    Action leftButtonAction = buttonAction(LeftButton, c.readEntry("LeftButtonAction"));
    Action middleButtonAction = buttonAction(MidButton, c.readEntry("MiddleButtonAction"));
    Action rightButtonAction = buttonAction(RightButton, c.readEntry("RightButtonAction"));

    TaskContainer::setLeftButtonAction( leftButtonAction );
    TaskContainer::setMiddleButtonAction( middleButtonAction );
    TaskContainer::setRightButtonAction( rightButtonAction );

    if ( !blocklayout )
	reLayout();
}

TaskManager* TaskBar::taskManager()
{
    if ( !manager )
	manager = new TaskManager( this );
    return manager;
}

void TaskBar::setOrientation( Orientation o )
{
    Panner::setOrientation( o );
    reLayout();
}

void TaskBar::resizeEvent( QResizeEvent* e )
{
    Panner::resizeEvent( e );
    reLayout();
}

void TaskBar::add( Task* task )
{
    if ( !task ) return;

    // try to group
    if ( groupTasks ) {
	for ( TaskContainerIterator it(containers); it.current(); ++it ) {
	    TaskContainer* c = it.current();
	    if ( idMatch( task->classClass().lower(), c->id().lower() ) ) {
		c->add( task );

		if ( !blocklayout )
		    reLayout();
		return;
	    }
	}
    }

    // create new container
    TaskContainer *c = new TaskContainer( task, taskManager(), showAllWindows, sortByDesktop, showIcon, viewport() );
    addChild( c );
    containers.append( c );
    emit containerCountChanged();

    if ( !blocklayout )
	reLayout();
}

void TaskBar::add( Startup* startup )
{
    if ( !startup ) return;

    // try to group
    if ( groupTasks ) {
	for ( TaskContainerIterator it(containers); it.current(); ++it ) {
	    TaskContainer* c = it.current();
	    if ( idMatch( startup->text().lower(), c->id().lower() ) ) {
		c->add( startup );

		if ( !blocklayout )
		    reLayout();
		return;
	    }
	}
    }

    // create new container
    TaskContainer *c = new TaskContainer( startup, frames, taskManager(), showAllWindows, sortByDesktop, showIcon, viewport() );
    addChild( c );
    containers.append( c );
    emit containerCountChanged();

    if ( !blocklayout )
	reLayout();
}

void TaskBar::remove( Task *task )
{
    TaskContainerList killList;
    for ( TaskContainerIterator it(containers); it.current(); ++it ) {
	TaskContainer* c = it.current();
	if ( c->contains( task ) ) {
	    c->remove( task );

	    if ( c->isEmpty() )
		killList.append( c );
	    break;
	}
    }

    for ( TaskContainerIterator it(killList); it.current(); ++it ) {
	TaskContainer* c = it.current();
	containers.removeRef( c );
	delete c;
	emit containerCountChanged();
    }
    reLayout();
}

void TaskBar::remove( Startup *startup )
{
    bool found = false;
    TaskContainerList killList;
    for ( TaskContainerIterator it(containers); it.current(); ++it ) {
	TaskContainer* c = it.current();
	if ( c->contains( startup ) ) {
	    c->remove( startup );
        found = true;

	    if ( c->isEmpty() )
		killList.append( c );
	    break;
	}
    }

    for ( TaskContainerIterator it(killList); it.current(); ++it ) {
	TaskContainer* c = it.current();
	containers.removeRef( c );
	delete c;
	emit containerCountChanged();
    }

    if (found)
      reLayout();
}

void TaskBar::desktopChanged( int desktop )
{
    if ( !showAllWindows ) {
	for ( TaskContainerIterator it(containers); it.current(); ++it ) {
	    TaskContainer* c = it.current();
	    c->desktopChanged( desktop );
	}
        emit containerCountChanged();
	reLayout();
    }
}

void TaskBar::windowDesktopChanged( WId win )
{
    for ( TaskContainerIterator it(containers); it.current(); ++it ) {
	TaskContainer* c = it.current();
	if ( c->contains( win ) )
	    c->windowDesktopChanged( win );
    }

    if ( !showAllWindows )
        emit containerCountChanged();
    reLayout();
}

void TaskBar::reLayout()
{
    // filter task container list
    TaskContainerList list = filteredContainers();
    if ( list.count() < 1 ) return;

    // sort container list by desktop
    if ( sortByDesktop ) {
	TaskContainerList sorted;
	for ( int desktop = -1; desktop <= taskManager()->numberOfDesktops(); desktop++ ) {
	    for ( TaskContainerIterator it(list); it.current(); ++it ) {
		TaskContainer* c = it.current();
		if ( c->desktop() == desktop )
		    sorted.append( c );
	    }
	}
	list = sorted;
    }

    // init content size
    resizeContents( contentsRect().width(), contentsRect().height() );

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

	int bwidth = BUTTON_MIN_WIDTH;

	// number of rows simply depends on our height
	int rows = contentsRect().height() / BUTTON_MIN_HEIGHT;
	if ( rows < 1 ) rows = 1;

	// actual button height
	int bheight = contentsRect().height() / rows;

	// buttons per row
	int bpr = (int)ceil( (double)list.count() / rows);

	// adjust content size
	if ( contentsRect().width() < bpr * BUTTON_MIN_WIDTH ) {
	    resizeContents( bpr * BUTTON_MIN_WIDTH, contentsRect().height() );
	}

	// maximum number of buttons per row
	int mbpr = contentsRect().width() / BUTTON_MIN_WIDTH;

	// expand button width if space permits
	if ( mbpr > bpr ) {
	    bwidth = contentsRect().width() / bpr;
	    if ( bwidth > maxButtonWidth )
		bwidth = maxButtonWidth;
	}

	// layout containers
	int i = 0;
	for ( TaskContainerIterator it(list); it.current(); ++it ) {
	    TaskContainer* c = it.current();

	    int row = i % rows;
	    c->setArrowType( arrowType );
	    c->resize( bwidth, bheight );
	    c->show();

	    moveChild( c, ( i / rows ) * bwidth, row * bheight );
	    i++;
	}

    }
    // vertical layout
    else {

	// adjust content size
	if ( contentsRect().height() < (int)list.count() * BUTTON_HEIGHT ) {
	    resizeContents( contentsRect().width(), list.count() * BUTTON_HEIGHT );
	}

	// layout containers
	int i = 0;
	for ( TaskContainerIterator it(list); it.current(); ++it ) {
	    TaskContainer* c = it.current();

	    c->setArrowType( arrowType );
	    c->resize( contentsRect().width(), BUTTON_HEIGHT );
	    c->show();

	    moveChild( c, 0, i * BUTTON_HEIGHT );
	    i++;
	}
    }
    QTimer::singleShot( 100, this, SLOT( publishIconGeometry() ) );
}

void TaskBar::setArrowType( Qt::ArrowType at )
{
    arrowType = at;
    for ( TaskContainerIterator it(containers); it.current(); ++it ) {
	TaskContainer* c = it.current();
	c->setArrowType( arrowType );
    }
}

void TaskBar::publishIconGeometry()
{
    QPoint p = mapToGlobal( QPoint( 0,0 ) ); // roundtrip, don't do that too often

    for ( TaskContainerIterator it(containers); it.current(); ++it ) {
	TaskContainer* c = it.current();
        c->publishIconGeometry( p );
    }
}

void TaskBar::viewportMousePressEvent( QMouseEvent* e )
{
    propagateMouseEvent( e );
}

void TaskBar::viewportMouseReleaseEvent( QMouseEvent* e )
{
    propagateMouseEvent( e );
}

void TaskBar::viewportMouseDoubleClickEvent( QMouseEvent* e )
{
    propagateMouseEvent( e );
}

void TaskBar::viewportMouseMoveEvent( QMouseEvent* e )
{
    propagateMouseEvent( e );
}

void TaskBar::propagateMouseEvent( QMouseEvent* e )
{
    if ( !isTopLevel()  ) {
	QMouseEvent me( e->type(), mapTo( topLevelWidget(), e->pos() ),
			e->globalPos(), e->button(), e->state() );
	QApplication::sendEvent( topLevelWidget(), &me );
    }
}

bool TaskBar::idMatch( const QString& id1, const QString& id2 )
{
    if ( id1.isEmpty() || id2.isEmpty() )
        return FALSE;

    if ( id1.contains( id2 ) > 0 )
	return TRUE;

    if ( id2.contains( id1 ) > 0 )
	return TRUE;

    return FALSE;
}

int TaskBar::containerCount() const
{
    int i = 0;
    TaskContainerListIterator it(containers);
    for ( ; it.current(); ++it ) {
	if ( showAllWindows ||  (*it)->onCurrentDesktop() ) {
	    i++;
	}
    }
    return i;
}

TaskContainerList TaskBar::filteredContainers()
{
    // filter task container list
    TaskContainerList list;
    for ( TaskContainerIterator it(containers); it.current(); ++it ) {
	TaskContainer* c = it.current();
	if ( showAllWindows ) {
	    list.append( c );
	    c->show();
	}
	else if ( c->onCurrentDesktop() ) {
	    list.append( c );
	    c->show();
	}
	else
	    c->hide();
    }
    return list;
}
