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

Copyright (c) 2002 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 <qpopupmenu.h>
#include <qwidget.h>
#include <qapp.h>

#include <kdebug.h>

#include "popupposition.h"

QPoint popupPosition( Direction d, const QPopupMenu* m, const QWidget* w )
{
	if( !QApplication::reverseLayout() || d == ::dLeft || d == ::dRight ) {
		return popupPosition( d, m, w, QPoint( 0, 0 ) );
	} else {
		return popupPosition( d, m, w, QPoint( w->width(), w->height() ) );
	}
}

QPoint popupPosition( Direction d, const QPopupMenu* m, const QWidget* w, const QPoint& p )
{
//	kdDebug(1210) << "popupPosition():" << endl;
//	kdDebug(1210) << m->width() << ", " << m->height() << endl;

	QRect r;
	if( w->isTopLevel() ) {
		r = w->geometry();
	} else {
		r = QRect( w->mapToGlobal( QPoint( 0, 0 ) ),
		           w->mapToGlobal( QPoint( w->width(), w->height() ) ) );
		switch( d ) {
		case ::dLeft:
		case ::dRight:
			r.setLeft( w->topLevelWidget()->x() );
			r.setWidth( w->topLevelWidget()->width() );
			break;
		case ::dUp:
		case ::dDown:
			r.setTop( w->topLevelWidget()->y() );
			r.setHeight( w->topLevelWidget()->height() );
			break;
		}
	}
	switch( d ) {
	case( ::dLeft ):
		return QPoint( r.left() - m->width(), r.top() + p.y()      );
	case( ::dRight ):
		return QPoint( r.right() + 1,         r.top() + p.y()      );
	case( ::dDown ):
		return QApplication::reverseLayout() ?
			QPoint( r.right() - m->width() - (r.width() - p.x()) + 1, r.bottom() + 1 ) :
			QPoint( r.left() + p.x(),      r.bottom() + 1       );
	default:
	case( ::dUp ):
		return QApplication::reverseLayout() ?
			QPoint( r.right() - m->width() - (r.width() - p.x()) + 1, r.top() - m->height() ) :
			QPoint( r.left() + p.x(),      r.top() - m->height() );
	}
}
