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

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 <stdio.h>

#include <qpainter.h>
#include <qdrawutil.h>
#include <qtooltip.h>
#include <qlineedit.h>
#include <qtoolbutton.h>
#include <qpopupmenu.h>

#include <dcopclient.h>

#include <kconfig.h>
#include <kglobalsettings.h>
#include <kwin.h>
#include <kwinmodule.h>
#include <kapplication.h>
#include <kglobal.h>
#include <klocale.h>
#include <kdebug.h>
#include <kprocess.h>
#include <kstandarddirs.h>
#include <kiconloader.h>
#include <dcopclient.h>
#include <netwm.h>

#include <qxembed.h>

#include "pagerapplet.h"
#include "pagerapplet.moc"

#ifdef FocusOut
#undef FocusOut
#endif

const int knDesktopPreviewSize = 12;
const int knBtnSpacing = 1;

extern "C"
{
    KPanelApplet* init(QWidget *parent, const QString& configFile)
    {
      KGlobal::locale()->insertCatalogue("kminipagerapplet");
      return new KMiniPager(configFile, KPanelApplet::Normal,
			    0, parent, "kminipagerapplet");
    }
}

KMiniPagerButton::KMiniPagerButton(int desk, KMiniPager *parent, const char *name)
    : QButton(parent, name, WRepaintNoErase )
{
    setToggleButton( TRUE );
    setAcceptDrops( TRUE );
    deskNum = desk;
    lineedit = 0;
    connect(this, SIGNAL(clicked()), SLOT(slotClicked()) );
    connect(this, SIGNAL(toggled(bool)), SLOT(slotToggled(bool)));
    connect(&dragSwitchTimer, SIGNAL( timeout() ),
            this, SLOT( slotDragSwitch() ) );
}

KMiniPager* KMiniPagerButton::pager()
{
    return (KMiniPager*) parentWidget();
}

void KMiniPagerButton::resizeEvent(QResizeEvent *ev)
{
    if ( lineedit )
	lineedit->setGeometry( rect() );
    QButton::resizeEvent( ev );
}

void KMiniPagerButton::paintEvent(QPaintEvent *)
{
    QPainter p;

    QBrush bg = colorGroup().brush( (!isOn() && !isDown()) ? QColorGroup::Dark : QColorGroup::Base );
    QColor fg = (!isOn() && !isDown()) ? colorGroup().base() : colorGroup().text();

    if ( pager()->desktopPreview() ) {
	QPixmap pm( width() - 2, height() - 2 );
	if (pm.isNull()) return;
	QPainter pp( &pm, this  );

	pp.fillRect( pm.rect(), bg );
	pp.setPen(fg);
	int dw = QApplication::desktop()->width();
	int dh = QApplication::desktop()->height();
	QValueList<WId>::ConstIterator it;
	for ( it = pager()->kwin()->stackingOrder().begin();
	      it != pager()->kwin()->stackingOrder().end(); ++it )
        {
	    KWin::Info* info = pager()->info( *it );

	    if ( info && info->windowType != NET::Desktop && !info->isIconified() &&
                 (info->onAllDesktops || info->desktop == deskNum ) &&
                 !(info->state & NET::SkipPager || info->state & NET::Shaded ) )
            {
		QRect r =  info->frameGeometry;
		r = QRect( r.x() * pm.width() / dw, 2 + r.y() * pm.height() / dh,
			   r.width() * pm.width() / dw, r.height() * pm.height() / dh );
		if ( pager()->kwin()->activeWindow() == (*it) ) {
		    qDrawShadeRect( &pp, r, colorGroup(), false, 1, 0, &colorGroup().brush( QColorGroup::Highlight ) );
		} else {
		    pp.fillRect( r, colorGroup().brush(  QColorGroup::Button ) );
		    qDrawShadeRect( &pp, r, colorGroup(), true, 1, 0 );
		}
	    }
	}
	pp.end();
	p.begin( this );
	p.drawPixmap( 1, 1, pm );
    } else {
	p.begin( this );
	p.fillRect( rect(), bg );
    }

    p.setPen( fg );

    if ( pager()->mode() == KMiniPager::LabelNumber ) {
	p.drawText(0, 0, width(), height(), AlignCenter, QString::number( deskNum ) );
    } else if ( pager()->mode() == KMiniPager::LabelName ) {
	p.drawText( 0, 0, width(), height(), AlignVCenter | AlignCenter, pager()->kwin()->desktopName( deskNum ) );
    }

    if(!isOn() && !isDown()){
	p.setPen(colorGroup().light());
	p.drawLine(0, 0, width()-1, 0);
	p.drawLine(0, 0, 0, height()-1);
	p.setPen(Qt::black);
	p.drawLine(0, height()-1, width()-1, height()-1);
	p.drawLine(width()-1, 0, width()-1, height()-1);
    } else {
	p.drawRect(rect());
    }
}

void KMiniPagerButton::mousePressEvent( QMouseEvent * e)
{
    if ( e->button() == RightButton ) {
	// prevent LMB down -> RMB down -> LMB up sequence
	if ( ( e->state() & MouseButtonMask ) == NoButton )
	    emit showMenu( e->globalPos(), deskNum );
    } else {
	QButton::mousePressEvent( e );
    }
}

void KMiniPagerButton::dragEnterEvent( QDragEnterEvent* e )
{
    // if a dragitem is held for over a pager button for two seconds,
    // activate corresponding desktop
    dragSwitchTimer.start( 1000, TRUE );

    QButton::dragEnterEvent( e );
}

void KMiniPagerButton::dragLeaveEvent( QDragLeaveEvent* e )
{
    dragSwitchTimer.stop();

    QButton::dragLeaveEvent( e );
}

void KMiniPagerButton::slotDragSwitch()
{
    emit buttonSelected( deskNum );
}

void KMiniPagerButton::slotClicked()
{
//    if ( isOn() )
      emit buttonSelected( deskNum );
//    else
//      setOn( true );
}

void KMiniPagerButton::rename()
{
  if ( !lineedit ) {
    lineedit = new QLineEdit( this );
    connect( lineedit, SIGNAL( returnPressed() ), lineedit, SLOT( hide() ) );
    lineedit->installEventFilter( this );
  }
  lineedit->setGeometry( rect() );
  lineedit->setText( pager()->kwin()->desktopName( deskNum ) );
  lineedit->show();
  lineedit->setFocus();
  lineedit->selectAll();
  pager()->emitRequestFocus();
}

void KMiniPagerButton::slotToggled( bool b )
{
    if ( !b && lineedit )
	lineedit->hide();
}

bool KMiniPagerButton::eventFilter( QObject *o, QEvent * e)
{
  if ( o && o == lineedit && ( e->type() == QEvent::FocusOut || e->type() == QEvent::Hide ) ) {
 	pager()->kwin()->setDesktopName( deskNum, lineedit->text() );
	QTimer::singleShot( 0, lineedit, SLOT( deleteLater() ) );
	lineedit = 0;
	return TRUE;
    }
    return QButton::eventFilter( o, e );
}

KMiniPager::KMiniPager(const QString& configFile, Type type, int actions,
		       QWidget *parent, const char *name)
    : KPanelApplet(configFile, type, actions, parent, name),
      layout(0), m_mode(LabelNumber), bDesktopPreview(true),
      m_pPagerProcess(0)
{
    windows.setAutoDelete( TRUE );

    KConfig *conf = config();
    conf->setGroup("minipager");
    QFont defFont(KGlobalSettings::taskbarFont());
    defFont = conf->readFontEntry("Font", &defFont);
    setFont(defFont);

    QString ms = conf->readEntry( "Label", "Number" );
    if ( ms == "None" )
	m_mode = LabelNone;
    else if ( ms == "Name" )
	m_mode = LabelName;
    else
	m_mode = LabelNumber;

    int scnum = QApplication::desktop()->screenNumber(this);
    QRect desk = QApplication::desktop()->screenGeometry(scnum);
    if (desk.width() <= 800)
        bDesktopPreview = false;

    bDesktopPreview = conf->readBoolEntry( "Preview", bDesktopPreview );

    kwin_module = new KWinModule(this);
    active = kwin_module->activeWindow();
    curDesk = kwin_module->currentDesktop();
    if (curDesk == 0) // kwin not yet launched
        curDesk = 1;

    desktopLayoutOrientation = Qt::Horizontal;
    desktopLayoutX = -1;
    desktopLayoutY = -1;

    allocateButtons();

    connect( kwin_module, SIGNAL( currentDesktopChanged(int)), SLOT( slotSetDesktop(int) ) );
    connect( kwin_module, SIGNAL( numberOfDesktopsChanged(int)), SLOT( slotSetDesktopCount(int) ) );
    connect( kwin_module, SIGNAL( activeWindowChanged(WId)), SLOT( slotActiveWindowChanged(WId) ) );
    connect( kwin_module, SIGNAL( windowAdded(WId) ), this, SLOT( slotWindowAdded(WId) ) );
    connect( kwin_module, SIGNAL( windowRemoved(WId) ), this, SLOT( slotWindowRemoved(WId) ) );
    connect( kwin_module, SIGNAL( windowChanged(WId,unsigned int) ), this, SLOT( slotWindowChanged(WId,unsigned int) ) );
    connect( kwin_module, SIGNAL( stackingOrderChanged() ), this, SLOT( slotStackingOrderChanged() ) );
    connect( kwin_module, SIGNAL( desktopNamesChanged() ), this, SLOT( slotDesktopNamesChanged() ) );

    slotSetDesktop( curDesk );
}

KMiniPager::~KMiniPager()
{
}

void KMiniPager::slotSetDesktop(int desktop)
{
//    if ( curDesk == desktop )
//	return;

    if ( kwin_module->numberOfDesktops() > static_cast<int>(btnList.count()))
	slotSetDesktopCount( kwin_module->numberOfDesktops() );

//    if ( (int) btnList.count() >= curDesk )
	for (unsigned int i=0; i < btnList.count(); i++)
	    btnList[i]->setOn(false);
    curDesk = desktop;
    if ( (int) btnList.count() >= curDesk )
	btnList[curDesk-1]->setOn(true);
}

void KMiniPager::slotButtonSelected( int desk )
{
    KWin::setCurrentDesktop( desk );
    slotSetDesktop( desk );
}

int KMiniPager::widthForHeight(int h) const
{
    int deskNum = kwin_module->numberOfDesktops();
    int deskHalf = (deskNum+1)/2;

    int bw = h < 32 ? h : (h/2);
    if ( desktopPreview() )
	bw = (int) ( bw * (double) QApplication::desktop()->width() / QApplication::desktop()->height() );
    if ( mode() == LabelName ) {
	for (int i = 1; i <= deskNum; i++ ) {
	    int sw = fontMetrics().width( kwin_module->desktopName( i ) ) + 6;
	    if ( sw > bw )
		bw = sw;
	}
    }

    int nWd = ( h <= 32 ? deskNum * bw : deskHalf * bw);

    return nWd;
}

int KMiniPager::heightForWidth(int w) const
{
    int deskNum = kwin_module->numberOfDesktops();
    int deskHalf = (deskNum+1)/2;

    bool small = w <= 32;

    int bh = small ? w : (w/2);
    if ( desktopPreview() )
	bh = (int) ( bh *  (double) QApplication::desktop()->height() / QApplication::desktop()->width() );
    else if ( mode() == LabelName ) {
	bh = fontMetrics().lineSpacing() + 8;
	small = true;
    }

    int nHg = ( small ? deskNum * bh : deskHalf * bh);

    return nHg;
}

void KMiniPager::updateDesktopLayout(int o, int x, int y)
{
   if ((desktopLayoutOrientation == o) &&
       (desktopLayoutX == x) &&
       (desktopLayoutY == y))
      return;

   QCString replyType;
   QByteArray data, replyData;
   QDataStream arg(data, IO_WriteOnly);
   arg << o << x << y;
   if ( !(kapp->dcopClient()->call( "kwin", "KWinInterface",
				    "setDesktopLayout(int, int, int)",
				    data, replyType, replyData)))
   {
      kdDebug() << "KMiniPager: Call to KWinInterface::setDesktopLayout(int, int, int) failed" << endl;
      return;
   }

   desktopLayoutOrientation = o;
   desktopLayoutX = x;
   desktopLayoutY = y;
}

void KMiniPager::resizeEvent(QResizeEvent*)
{
    int deskNum = btnList.count();
    int deskHalf = (deskNum+1)/2;
    bool horiz = orientation() == Horizontal;
    bool small = (horiz && height() <=32) || (!horiz && width() <=32);

    if ( !horiz && mode() == LabelName )
	small = TRUE;

    if (layout)
    {
        delete layout;
        layout = 0;
    }

    int nDX, nDY;
    if (horiz)
    {
        if (small)
	    nDX = 1, nDY = deskNum;
        else
	    nDX = 2, nDY = deskHalf;

        updateDesktopLayout(Qt::Horizontal, -1, nDX);
    }
    else
    {
        if (small)
	    nDX = deskNum, nDY = 1;
        else
	    nDX = deskHalf, nDY = 2;
        updateDesktopLayout(Qt::Horizontal, nDY, -1);
    }

    layout = new QGridLayout(this, nDX, nDY);

    int c = 0;
    QValueList<KMiniPagerButton*>::Iterator it = btnList.begin();

    if (small) {
	while( it != btnList.end() ) {
	    if (horiz)
		layout->addWidget( *it, 0, c);
	    else
		layout->addWidget( *it, c, 0);
	    ++it;
	    ++c;
	}
    } else {
	int r = 0;
	while(it != btnList.end())
	{
	   c = 0;
	   while( (it != btnList.end()) && (c < nDY) ) {
             layout->addWidget( *it, r, c);
             ++it;
	     ++c;
	   }
	   ++r;
  	}
    }

    layout->activate();
    updateGeometry();
}

void KMiniPager::wheelEvent( QWheelEvent* e )
{
    if( e->delta() < 0 ) {
        // this could be "( curDesk - 1 ) + 1" for clarity, but that seems superfluous
        const int next = curDesk % KWin::numberOfDesktops() + 1;
        KWin::setCurrentDesktop( next );
    }
    else {
        // again, a little ugly -- the addition of the number of desktops makes sure that we are
        // not taking the modulo of a negative number and the "curDesk - 2" could be "curDesk - 1 - 1"
        const int previous = ( KWin::numberOfDesktops() + curDesk - 2 ) % KWin::numberOfDesktops() + 1;
        KWin::setCurrentDesktop( previous );
    }
}

void KMiniPager::allocateButtons()
{
    int i;
    int deskNum = kwin_module->numberOfDesktops();
//    int act = kwin_module->currentDesktop();
    KMiniPagerButton *btn;
    for (i=1; i <= deskNum; ++i) {
	btn = new KMiniPagerButton(i, this);
//	btn->setOn(i == act);
	btn->show();
	if ( mode() != KMiniPager::LabelName )
	QToolTip::add(btn, kwin()->desktopName(i));

	btnList.append(btn);
	connect(btn, SIGNAL(buttonSelected(int)), SLOT(slotButtonSelected(int)));
	connect(btn, SIGNAL(showMenu(const QPoint&, int )), SLOT(slotShowMenu(const QPoint&, int )));
    }
}

void KMiniPager::slotSetDesktopCount(int)
{
    QValueList<KMiniPagerButton*>::Iterator it;
    for(it=btnList.begin(); it != btnList.end(); ++it)
	delete (*it);
    btnList.clear();
    allocateButtons();
    curDesk = kwin_module->currentDesktop();
    if (curDesk == 0) // kwin not yet launched
	curDesk = 1;
    if ( (int) btnList.count() >= curDesk )
            btnList[curDesk-1]->setOn(true);
    resizeEvent(0);
    updateLayout();
}

void KMiniPager::slotActiveWindowChanged( WId win )
{
    if ( !desktopPreview() )
	return;
    KWin::Info* inf1 = active ? info( active ) : NULL;
    KWin::Info* inf2 = info( win );
    active = win;
    for ( int i=1; i <= (int) btnList.count(); ++i) {
	if ( (inf1 && (inf1->onAllDesktops || inf1->desktop == i ) )
	     || (inf2 && (inf2->onAllDesktops || inf2->desktop == i ) ) )
	    btnList[i-1]->update();
    }
}

void KMiniPager::slotWindowAdded( WId win)
{
    if ( !desktopPreview() )
	return;
    KWin::Info* inf = info( win );
    for ( int i=1; i <= (int) btnList.count(); ++i) {
	if ( inf->onAllDesktops || inf->desktop == i )
	    btnList[i-1]->update();
    }
}

void KMiniPager::slotWindowRemoved( WId win )
{
    if ( !desktopPreview() ) {
	windows.remove( win );
	return;
    }
    KWin::Info* inf = info( win );
    bool onAllDesktops = inf->onAllDesktops;
    int desktop = inf->desktop;

    if (win == active)
        active = 0;

    windows.remove( (long) win );

    for ( int i=1; i <= (int) btnList.count(); ++i) {
	if ( onAllDesktops || desktop == i )
	    btnList[i-1]->update();
    }
}

void KMiniPager::slotWindowChanged( WId win , unsigned int )
{
    if ( !desktopPreview() ) {
	windows.remove( win );
	return;
    }
    KWin::Info* inf = windows[win];
    bool onAllDesktops = inf ? inf->onAllDesktops : false;
    int desktop = inf ? inf->desktop : 0;
    windows.remove( (long) win );
    inf = info( win );
    for ( int i=1; i <= (int) btnList.count(); ++i) {
	if ( inf->onAllDesktops || inf->desktop == i  || onAllDesktops || desktop == i )
	    btnList[i-1]->update();
    }
}

KWin::Info* KMiniPager::info( WId win )
{
    KWin::Info* info = windows[win];
    if (!info ) {
	info = new KWin::Info( KWin::info( win ) );
	windows.insert( (long) win, info );
    }
    return info;
}

void KMiniPager::slotStackingOrderChanged()
{
    if ( !desktopPreview() )
	return;
    slotRefresh();
}

void KMiniPager::slotRefresh()
{
    for ( int i=1; i <= (int) btnList.count(); ++i)
	btnList[i-1]->update();
}

void KMiniPager::slotShowMenu( const QPoint& pos, int desktop )
{
    QPopupMenu* p = new QPopupMenu;
    QPopupMenu* t = new QPopupMenu( p );
    p->insertItem( SmallIcon("kpager"), i18n("&Launch Pager"), 96 );
    p->insertSeparator();
    t->setCheckable( true );
    t->insertItem( i18n("N&umber"), LabelNumber );
    t->insertItem( i18n("N&ame"), LabelName );
    t->insertItem( i18n("N&one"), LabelNone );
    t->insertSeparator();
    t->insertItem( i18n("&Preview"), 97 );
    p->insertItem( i18n("&Show"), t );
    p->insertItem( SmallIcon("desktop"), i18n("&Configure Virtual Desktops..."), 98);
    p->insertSeparator();
    p->insertItem( i18n("&Rename Virtual Desktop"), 99 );

    p->setItemChecked( m_mode, true );
    p->setItemChecked( 97, bDesktopPreview );
    p->setItemEnabled( 99, m_mode == LabelName );

    int result = p->exec( pos );
    delete p;
    if ( result <= 0 || result == m_mode )
      return;
    switch (result)
      {
      case 96:
	showPager();
	return;
      case 98:
	kapp->startServiceByDesktopName("desktop");
	return;
      case 99:
	btnList[desktop-1]->rename();
	return;
      }

    KConfig* conf = config();
    conf->setGroup("minipager");
    switch (result)
      {
      case 97:
	bDesktopPreview = !bDesktopPreview;  //toggle preview
	conf->writeEntry( "Preview", bDesktopPreview );
	break;
      case LabelNone:
      case LabelNumber:
      case LabelName:
	m_mode = (KMiniPager::Mode)result;
	if ( m_mode == LabelNone )
	  conf->writeEntry( "Label", "None" );
	else if ( m_mode == LabelName )
	  conf->writeEntry( "Label", "Name" );
	else
	  conf->writeEntry( "Label", "Number" );
	break;
      }
    conf->sync();
    slotRefresh();
    emit updateLayout();
}

void KMiniPager::slotDesktopNamesChanged()
{
    for ( int i=1; i <= (int) btnList.count(); ++i)
      {
	QToolTip::remove(btnList[i-1]);
	QToolTip::add(btnList[i-1], kwin()->desktopName(i));
      }

    if ( m_mode != LabelName )
      return;

    slotRefresh();
    emit updateLayout();
}

void KMiniPager::showPager()
{
   DCOPClient *dcop=kapp->dcopClient();

   if (dcop->isApplicationRegistered("kpager"))
     showKPager(true);
   else
   {
   // Let's run kpager if it isn't running
     connect( dcop, SIGNAL( applicationRegistered(const QCString &) ), this, SLOT(applicationRegistered(const QCString &)) );
     dcop->setNotifications(true);
     QString strAppPath(locate("exe", "kpager"));
     if (!strAppPath.isEmpty())
     {
       KProcess process;
       process << strAppPath;
       process << "--hidden";
       process.start(KProcess::DontCare);
     }
   }
}

void KMiniPager::showKPager(bool toggleShow)
{
   QPoint pt;
   switch ( position() )
     {
     case pTop:
       pt = mapToGlobal( QPoint(x(), y() + height()) );
       break;
     case pLeft:
       pt = mapToGlobal( QPoint(x() + width(), y()) );
       break;
     case pRight:
     case pBottom:
     default:
       pt=mapToGlobal( QPoint(x(), y()) );
     }
   DCOPClient *dcop=kapp->dcopClient();
   QByteArray data;
   QDataStream arg(data, IO_WriteOnly);
   arg << pt.x() << pt.y() ;
   if (toggleShow)  dcop->send("kpager", "KPagerIface", "toggleShow(int,int)", data);
   else dcop->send("kpager", "KPagerIface", "showAt(int,int)", data);

}

void KMiniPager::applicationRegistered( const QCString  & appName )
{
 if (appName == "kpager")
 {
   disconnect( kapp->dcopClient(), SIGNAL( applicationRegistered(const QCString &) ),
       this, SLOT(applicationRegistered(const QCString &)) );
   showKPager(false);
 }
}
