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

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 <kglobalaccel.h>
#include <kapplication.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 )
{
    setBackgroundOrigin( AncestorOrigin );

    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( windowChanged( WId ) ), SLOT( windowChanged( WId ) ) );

    isGrouping = shouldGroup();

    // 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;
    
    connect( kapp, SIGNAL(settingsChanged(int)),
        SLOT(slotSettingsChanged(int)));
    keys = new KGlobalAccel( this );
#include "taskbarbindings.cpp"
    keys->readSettings();
    keys->updateConnections();
}

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 )
    {
        int actualMax = BUTTON_HEIGHT * containerCount();

        if (actualMax > maxSize.height())
        {
            return maxSize;
        }
        else
        {
            return QSize( maxSize.width(), actualMax );
        }
    }
    else
    {
        int rows = contentsRect().height() / BUTTON_MIN_HEIGHT;
        if ( rows < 1 )
        {
            rows = 1;
        }

        int actualMax = maxButtonWidth * (containerCount() / rows);
        if (containerCount() % rows > 0)
        {
            actualMax += maxButtonWidth;
        }

        if (actualMax > maxSize.width())
        {
           return maxSize;
        }
        else
        {
           return QSize( actualMax, maxSize.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;
   }
}

// These are the strings that are actually stored in the config file.
const QStringList& TaskBar::groupModeList()
{
    static QStringList list(
            QStringList() << I18N_NOOP("Never") << I18N_NOOP("When Taskbar Full")
            << I18N_NOOP("Always"));
    return list;
}

// Translate from config entry name to enumeration
enum TaskBar::GroupMode TaskBar::groupMode(const QString& groupModeName )
{
   int index = groupModeList().findIndex( groupModeName );
   if( index != -1 ) return static_cast<GroupMode>(index);

   // Translate old entries
   if( groupModeName == "true" ) return GroupAlways;
   if( groupModeName == "false" ) return GroupNever;

   // Otherwise return the default.
   return GroupWhenFull;
}

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

    showAllWindows = c.readBoolEntry( "ShowAllWindows", true );
    showOnlyIconified = c.readBoolEntry( "ShowOnlyIconified", false );
    currentGroupMode = groupMode( c.readEntry( "GroupTasks" ) );
    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* container = it.current();
	container->setShowAll( showAllWindows );
	container->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 ( isGrouping ) {
	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, showOnlyIconified, viewport() );
    addChild( c );
    containers.append( c );

    if ( !blocklayout )
    {
        emit containerCountChanged();
	reLayout();
    }
}

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

    // try to group
    if ( isGrouping ) {
	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, showOnlyIconified, viewport() );
    addChild( c );
    containers.append( c );

    if ( !blocklayout )
    {
        emit containerCountChanged();
	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 );
	c->deleteLater();
    }

    if ( !blocklayout )
    {
        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 );
	c->deleteLater();
    }

    if (found && !blocklayout )
    {
        emit containerCountChanged();
	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::windowChanged( WId win )
{
    for ( TaskContainerIterator it(containers); it.current(); ++it ) {
	TaskContainer* c = it.current();
	if ( c->contains( win ) )
	    c->windowChanged( win );
    }

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

void TaskBar::reLayout()
{
    // filter task container list
    TaskContainerList list = filteredContainers();
    if ( list.count() < 1 ) {
        resizeContents( contentsRect().width(), contentsRect().height() );
        return;
    }

    if ( isGrouping != shouldGroup() ) {
        reGroup();
        return;
    }

    // sort container list by desktop
    if ( sortByDesktop )
        list = sortContainersByDesktop( list );

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

    return id1.lower() == id2.lower();
}

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

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

int TaskBar::maximumButtonsWithoutShrinking() const
{
    int rows = contentsRect().height() / BUTTON_MIN_HEIGHT;
    if ( rows < 1 ) rows = 1;

    if ( orientation() == Horizontal ) {
       // They squash a bit before they pop, hence the 2
       return rows * (contentsRect().width() / maxButtonWidth) + 2;
    } else {
        // Overlap slightly and ugly arrows appear, hence -1
        return rows - 1;
    }
}

bool TaskBar::shouldGroup() const
{
    return currentGroupMode == GroupAlways ||
        ( currentGroupMode == GroupWhenFull &&
          taskCount() > maximumButtonsWithoutShrinking() );
}

void TaskBar::reGroup()
{
    isGrouping = shouldGroup();
    blocklayout = TRUE;

    TaskList tasks = taskManager()->tasks();
    for (Task* t = tasks.first(); t!=0; t = tasks.next())
	remove( t );

    StartupList startups = taskManager()->startups();
    for (Startup* s = startups.first(); s!=0; s = startups.next())
	remove( s );

    for (Task* t = tasks.first(); t!=0; t = tasks.next())
	add( t );

    for (Startup* s = startups.first(); s!=0; s = startups.next())
	add( s );

    blocklayout = FALSE;
    reLayout();
}

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

void TaskBar::activateNextTask( bool forward )
{
    bool forcenext = false;
    TaskContainerList list = containers;
    if( sortByDesktop )
        list = sortContainersByDesktop( list );
    TaskContainerIterator it( list );
    for ( forward ? it.toFirst() : it.toLast(); it.current(); forward ? ++it : --it ) {
	TaskContainer* c = it.current();
	if ( c->activateNextTask( forward, forcenext ) )
            return;
    }
    if( forcenext ) // moving forward from the last, or backward from the first
        return;
    forcenext = true; // select first
    for ( forward ? it.toFirst() : it.toLast(); it.current(); forward ? ++it : --it ) {
        TaskContainer* c = it.current();
        if( sortByDesktop )
            if( forward ? c->desktop() < taskManager()->currentDesktop()
                : c->desktop() > taskManager()->currentDesktop())
                continue;
        if ( c->activateNextTask( forward, forcenext ) )
            return;
    }
}

void TaskBar::slotActivateNextTask()
{
    activateNextTask( true );
}

void TaskBar::slotActivatePreviousTask()
{
    activateNextTask( false );
}

void TaskBar::slotSettingsChanged( int category )
{
    if( category == (int) KApplication::SETTINGS_SHORTCUTS ) {
        keys->readSettings();
        keys->updateConnections();
    }
}

TaskContainerList TaskBar::sortContainersByDesktop( TaskContainerList list )
{
    TaskContainerList sorted;
    /* antlarr: look for commentary about "residue" in
      TaskContainer::updateFilteredTaskList() */
    TaskContainerList residue = list;
    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 );
	        residue.remove( c );
	    }    
	}
    }
    list = sorted;
    for ( TaskContainer *c = residue.first(); c; c = residue.next() )
        list.append( c );
    return list;
}
