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

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

#include <dcopref.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;

// The previews tend to have a 4/3 aspect ratio
static const int smallHeight = 32;
static const int smallWidth = 42;

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 *)
{
    setBackgroundOrigin( AncestorOrigin );

    bool active = isOn() || isDown();
    bool transparent = pager()->transparent();

    QPixmap buffer( width(), height() );
    QBitmap mask( buffer.size(), true );
    QPainter bp( &buffer, this );
    QPainter mp( &mask );

    // background...
    if( ! transparent ) {
        // fill with a solid background, if active Midlight, else Mid...
        QBrush background = colorGroup().brush( active ? QColorGroup::Midlight : QColorGroup::Mid );
        bp.fillRect( buffer.rect(), background );
    } else {
        // transparent windows get an 1 pixel frame...
        if( active )
            bp.setPen( colorGroup().midlight() );
        else
            bp.setPen( colorGroup().dark() );
        bp.drawRect( buffer.rect() );
        mp.setPen( Qt::color1 );
        mp.drawRect( buffer.rect() );
    }

    // window preview...
    if( pager()->desktopPreview() ) {
        int dw = QApplication::desktop()->width();
        int dh = QApplication::desktop()->height();

        QValueList<WId>::ConstIterator it;
        // SELI this needs checking for kwin_iii
        for ( it = pager()->kwin()->stackingOrder().begin();
                it != pager()->kwin()->stackingOrder().end(); ++it ) {
            KWin::WindowInfo* info = pager()->info( *it );
            NET::WindowType type;
            if( info )
                 type= info->windowType( NET::NormalMask | NET::DesktopMask | NET::DockMask
                    | NET::ToolbarMask | NET::MenuMask | NET::DialogMask | NET::OverrideMask
                    | NET::TopMenuMask | NET::UtilityMask | NET::SplashMask );
            if ( info &&
                    type != NET::Desktop && type != NET::Dock &&
                    !info->isMinimized() &&
                    (info->onAllDesktops() || info->desktop() == deskNum ) &&
                    !(info->state() & NET::SkipPager || info->state() & NET::Shaded ) ) {
                QRect r =  info->frameGeometry();
                int w = buffer.width(),
                    h = buffer.height();
                r = QRect( r.x() * w / dw, r.y() * h / dh,
                            r.width() * w / dw, r.height() * h / dh );

                QBrush fill;
                QColor line;
                if ( pager()->kwin()->activeWindow() == (*it) ) {
                    fill = QBrush( colorGroup().highlight() );
                    line = colorGroup().foreground() /*highlightedText()*/;
                } else {
                    fill = QBrush( colorGroup().background() );
                    line = colorGroup().foreground();
                }
                bp.setPen( line );
                bp.drawRect( r );
                if( r.width() > 2 && r.height() > 2 )
                    bp.fillRect( r.x()+1, r.y()+1, r.width()-2, r.height()-2, fill );
                if( pager()->transparent() )
                    mp.fillRect( r, color1 );
            }
        }
    }

    bp.end();
    mp.end();

    if( pager()->transparent() )
    {
        buffer.setMask( mask );
        erase();
    }

    QPainter p( this );
    p.drawPixmap( 0, 0, buffer );

    // label...
    if ( pager()->mode() == KMiniPager::LabelNumber ) {
        p.setPen( colorGroup().background() );
        p.translate(1,1);
        p.drawText(0, 0, width()-1, height(), AlignCenter,
                QString::number( deskNum ) );
        p.setPen( colorGroup().foreground() );
        p.translate(-1,-1);
        p.drawText(0, 0, width(), height(), AlignCenter,
                QString::number( deskNum ) );
    } else if ( pager()->mode() == KMiniPager::LabelName ) {
        p.setPen( colorGroup().background() );
        p.translate(1,1);
        p.drawText( 0, 0, width(), height(), AlignVCenter | AlignCenter,
                pager()->kwin()->desktopName( deskNum ) );
        p.setPen( colorGroup().foreground() );
        p.translate(-1,-1);
        p.drawText( 0, 0, width(), height(), AlignVCenter | AlignCenter,
                pager()->kwin()->desktopName( deskNum ) );
    }


    p.end();
}

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),
      bTransparent( false ),
      m_pPagerProcess(0),
      contextMenu(0)
{
    windows.setAutoDelete( TRUE );

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

    m_rows = conf->readUnsignedNumEntry( "NumberOfRows", 0 );
    if(m_rows > 3)
        m_rows = 0;

    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 );
    bTransparent = conf->readBoolEntry( "Transparent", bTransparent );

    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() ) );

    if (kapp->authorizeKAction("kicker_rmb") && kapp->authorizeControlModule("kde-kcmtaskbar.desktop"))
    {
        contextMenu = new QPopupMenu();
        connect(contextMenu, SIGNAL(aboutToShow()), SLOT(aboutToShowContextMenu()));
        connect(contextMenu, SIGNAL(activated(int)), SLOT(contextMenuActivated(int)));
        setCustomMenu(contextMenu);
    }

    for( QValueList<WId>::ConstIterator it = kwin_module->windows().begin();
	 it != kwin_module->windows().end();
	 ++it )
	slotWindowAdded( *it );

    slotSetDesktop( curDesk );
}

KMiniPager::~KMiniPager()
{
    KGlobal::locale()->removeCatalogue("kminipagerapplet");
    delete contextMenu;
}

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 rowNum = deskNum; // default is the number of desktops...
    if( m_rows == 0 ) {
        if( h<=32 || deskNum<=1 )
            rowNum = 1;
        else
            rowNum = 2;
    } else {
        rowNum = m_rows;
    }
    int deskCols = deskNum/rowNum;
    if(deskNum == 0 || deskNum % rowNum != 0)
        deskCols += 1;

    int nWd;
    if( mode() != LabelName ) {
        int bw = (h/rowNum);
        if ( desktopPreview() )
            bw = (int) ( bw * (double) QApplication::desktop()->width() / QApplication::desktop()->height() );
        nWd = ( deskCols * bw);
    } else {
        int bw = (h/rowNum);
        for (int i = 1; i <= deskNum; i++ ) {
            int sw = fontMetrics().width( kwin_module->desktopName( i ) ) + 16;
            if ( sw > bw )
                bw = sw;
        }
        nWd = ( deskCols * bw );
    }

    return nWd;
}

int KMiniPager::heightForWidth(int w) const
{
    int deskNum = kwin_module->numberOfDesktops();
    int rowNum = deskNum; // actually these are columns now... oh well.
    if( m_rows == 0 ) {
        if( w<=48 || deskNum<=1 )
            rowNum = 1;
        else
            rowNum = 2;
    } else {
        rowNum = m_rows;
    }
    int deskCols = deskNum/rowNum;
    if(deskNum == 0 || deskNum % rowNum != 0)
        deskCols += 1;

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

    int nHg = ( deskCols * 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::paintEvent(QPaintEvent *)
{
    // will be shown as 1 Pixel frame because of the grid's spacing...
    QPainter p(this);
    p.fillRect( rect(), transparent()?colorGroup().brush( QColorGroup::Background ):(colorGroup().mid()).dark(140) );
}

void KMiniPager::resizeEvent(QResizeEvent*)
{
    bool horiz = orientation() == Horizontal;

    int deskNum = btnList.count();
    int rowNum = deskNum;
    if( m_rows == 0 ) {
        if( ((horiz && height()<=32)||(!horiz && width()<=48)) || deskNum <= 1 )
            rowNum = 1;
        else
            rowNum = 2;
    } else {
        rowNum = m_rows;
    }
    int deskCols = deskNum/rowNum;
    if(deskNum == 0 || deskNum % rowNum != 0)
        deskCols += 1;

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

    int nDX, nDY;
    if (horiz)
    {
        nDX = rowNum;
        nDY = deskCols;
        updateDesktopLayout(Qt::Horizontal, -1, nDX);
    }
    else
    {
        nDX = deskCols;
        nDY = rowNum;
        updateDesktopLayout(Qt::Horizontal, nDY, -1);
    }

    // 1 pixel margin and spacing.
    layout = new QGridLayout(this, nDX, nDY, 1, 1);

    QValueList<KMiniPagerButton*>::Iterator it = btnList.begin();
    int c = 0,
        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 )
{
    DCOPRef("kdesktop", "KDesktopIface").send("switchDesktops", e->delta());
}

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::WindowInfo* inf1 = active ? info( active ) : NULL;
    KWin::WindowInfo* inf2 = win ? info( win ) : NULL;
    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::WindowInfo* 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::WindowInfo* 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 properties )
{
    if(( properties & ( NET::WMState | NET::XAWMState | NET::WMDesktop | NET::WMGeometry )) == 0 )
        return;
    if ( !desktopPreview() ) {
	windows.remove( win );
	return;
    }
    KWin::WindowInfo* 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::WindowInfo* KMiniPager::info( WId win )
{
    KWin::WindowInfo* info = windows[win];
    if (!info ) {
	info = new KWin::WindowInfo( win,
            NET::WMWindowType | NET::WMState | NET::XAWMState | NET::WMDesktop | NET::WMGeometry | NET::WMKDEFrameStrut, 0 );
	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::aboutToShowContextMenu()
{
    contextMenu->clear();

    contextMenu->insertItem( SmallIcon("kpager"), i18n("&Launch Pager"), 96 );
    contextMenu->insertSeparator();

    QPopupMenu* showMenu = new QPopupMenu( contextMenu );
    showMenu->setCheckable( true );
    QPopupMenu* rowMenu = new QPopupMenu( showMenu );
    rowMenu->setCheckable( true );
    rowMenu->insertItem( i18n("&Automatic"), 0+2000 );
    rowMenu->insertItem( i18n("one row or column", "&1"), 1+2000 );
    rowMenu->insertItem( i18n("two rows or columns", "&2"), 2+2000 );
    rowMenu->insertItem( i18n("three rows or columns", "&3"), 3+2000 );
    connect(rowMenu, SIGNAL(activated(int)), SLOT(contextMenuActivated(int)));
    showMenu->insertItem( (orientation()==Horizontal)?i18n("&Rows"):i18n("&Columns"), rowMenu );
    showMenu->insertSeparator();
    showMenu->insertItem( i18n("N&umber"), LabelNumber );
    showMenu->insertItem( i18n("N&ame"), LabelName );
    showMenu->insertItem( i18n("N&one"), LabelNone );
    showMenu->insertSeparator();
    showMenu->insertItem( i18n("&Preview"), 97 );
    showMenu->insertSeparator();
    showMenu->insertItem( i18n( "&Transparent" ), 100 );
    connect(showMenu, SIGNAL(activated(int)), SLOT(contextMenuActivated(int)));
    contextMenu->insertItem( i18n("&Show"),showMenu );

    contextMenu->insertItem( SmallIcon("configure"), i18n("&Configure Virtual Desktops..."), 98);
    contextMenu->insertSeparator();
    contextMenu->insertItem( i18n("&Rename Virtual Desktop"), 99 );

    rowMenu->setItemChecked( m_rows+2000, true );
    contextMenu->setItemChecked( m_mode, showMenu );
    contextMenu->setItemChecked( 97, bDesktopPreview );
    contextMenu->setItemEnabled( 99, m_mode == LabelName );
    contextMenu->setItemChecked( 100, bTransparent );
}

void KMiniPager::slotShowMenu( const QPoint& pos, int desktop )
{
    if (!contextMenu)
        return;

    rmbDesk = desktop;
    contextMenu->exec( pos );
    rmbDesk = -1;
}

void KMiniPager::contextMenuActivated(int result)
{
    if ( result <= 0 || result == m_mode )
      return;

    switch (result)
      {
      case 96:
	showPager();
	return;
      case 98:
	kapp->startServiceByDesktopName("desktop");
	return;
      case 99:
	btnList[(rmbDesk == -1) ? curDesk - 1 : rmbDesk - 1]->rename();
	return;
      }

    KConfig* conf = config();
    conf->setGroup("minipager");

    if (result >= 2000) {
      m_rows = result-2000;
      conf->writeEntry( "NumberOfRows", m_rows );
      resizeEvent(0);
    }

    switch (result)
      {
      case 97:
	bDesktopPreview = !bDesktopPreview;  //toggle preview
	conf->writeEntry( "Preview", bDesktopPreview );
	break;
      case 100:
	bTransparent = !bTransparent;  //toggle preview
	conf->writeEntry( "Transparent", bTransparent );
	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);
 }
}
