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

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

#include <qpainter.h>
#include <qstyle.h>

#include <kaboutkde.h>
#include <kglobal.h>
#include <kglobalsettings.h>
#include <kiconloader.h>
#include <kiconeffect.h>
#include <klocale.h>
#include <kconfig.h>
#include <kwin.h>
#include <kapplication.h>
#include <dcopclient.h>
#include <kaction.h>
#include <konqbookmarkmanager.h>
#include <kbookmarkmenu.h>
#include <kstandarddirs.h>
#include <kdebug.h>

#include "k_mnu.h"
#include "k_mnu.moc"

#include "kicker.h"
#include "panel.h"
#include "quickbrowser_mnu.h"
#include "panelop_mnu.h"
#include "recent_mnu.h"
#include "client_mnu.h"

#include "menuinfo.h"

PanelKMenu::PanelKMenu( ::Panel* panel )
  : PanelServiceMenu(QString::null, QString::null, 0, "KMenu")
  , bookmarkMenu(0)
  , bookmarkOwner(0)
  , _panel( panel )
{
    // set the first client id to some arbitrarily large value.
    client_id = 10000;
    // Don't automatically clear the main menu.
    disableAutoClear();
    actionCollection = new KActionCollection( this );
    setCaption( i18n( "K Menu" ) );

    connect( Kicker::kicker(), SIGNAL(configurationChanged()),
             this, SLOT(configChanged()) );
}

bool PanelKMenu::loadSidePixmap()
{
  KConfig *config = KGlobal::config();
  QColor color = palette().active().highlight();
  QImage image;

  config->setGroup("WM");
  QColor activeTitle = config->readColorEntry("activeBackground", &color);
  QColor inactiveTitle = config->readColorEntry("inactiveBackground", &color);

  config->setGroup("KMenu");
  if (!config->readBoolEntry("UseSidePixmap", true))
      return false;

  // figure out which color is most suitable for recoloring to
  int h1, s1, v1, h2, s2, v2, h3, s3, v3;
  activeTitle.hsv(&h1, &s1, &v1);
  inactiveTitle.hsv(&h2, &s2, &v2);
  palette().active().background().hsv(&h3, &s3, &v3);

  if ( (abs(h1-h3)+abs(s1-s3)+abs(v1-v3) < abs(h2-h3)+abs(s2-s3)+abs(v2-v3)) &&
       ((abs(h1-h3)+abs(s1-s3)+abs(v1-v3) < 32) || (s1 < 32)) && (s2 > s1))
    color = inactiveTitle;
  else
    color = activeTitle;

  // limit max/min brightness
  int r, g, b;
  color.rgb(&r, &g, &b);
  int gray = qGray(r, g, b);
  if (gray > 180) {
    r = (r - (gray - 180) < 0 ? 0 : r - (gray - 180));
    g = (g - (gray - 180) < 0 ? 0 : g - (gray - 180));
    b = (b - (gray - 180) < 0 ? 0 : b - (gray - 180));
  } else if (gray < 76) {
    r = (r + (76 - gray) > 255 ? 255 : r + (76 - gray));
    g = (g + (76 - gray) > 255 ? 255 : g + (76 - gray));
    b = (b + (76 - gray) > 255 ? 255 : b + (76 - gray));
  }
  color.setRgb(r, g, b);

  QString sideName = config->readEntry("SideName", "kside.png");
  QString sideTileName = config->readEntry("SideTileName", "kside_tile.png");

  image.load(locate("data", "kicker/pics/" + sideName));

  if (image.isNull())
  {
    kdDebug(1210) << "Can't find a side pixmap" << endl;
    return false;
  }

  KIconEffect::colorize(image, color, 1.0);
  sidePixmap.convertFromImage(image);

  image.load(locate("data", "kicker/pics/" + sideTileName));

  if (image.isNull())
  {
    kdDebug(1210) << "Can't find a side tile pixmap" << endl;
    return false;
  }

  KIconEffect::colorize(image, color, 1.0);
  sideTilePixmap.convertFromImage(image);

  if (sidePixmap.width() != sideTilePixmap.width())
  {
    kdDebug(1210) << "Pixmaps have to be the same size" << endl;
    return false;
  }

  // pretile the pixmap to a height of at least 100 pixels
  if (sideTilePixmap.height() < 100)
  {
    int tiles = (int)(100 / sideTilePixmap.height()) + 1;
    QPixmap preTiledPixmap(sideTilePixmap.width(), sideTilePixmap.height() * tiles);
    QPainter p(&preTiledPixmap);
    p.drawTiledPixmap(preTiledPixmap.rect(), sideTilePixmap);
    sideTilePixmap = preTiledPixmap;
  }

  return true;
}

void PanelKMenu::paletteChanged()
{
    if (!loadSidePixmap())
      sidePixmap = sideTilePixmap = QPixmap();
}

void PanelKMenu::configChanged()
{
    reinitialize();
    updateGeometry();
}

PanelKMenu::~PanelKMenu()
{
    delete bookmarkMenu;
    delete bookmarkOwner;
}

void PanelKMenu::initialize()
{
//    kdDebug(1210) << "PanelKMenu::initialize()" << endl;

    updateRecent();

    if (initialized()) return;

    if (!loadSidePixmap())
      sidePixmap = sideTilePixmap = QPixmap();
    else
      connect(kapp, SIGNAL(kdisplayPaletteChanged()), SLOT(paletteChanged()));

    // add services
    PanelServiceMenu::initialize();
    insertSeparator();

    // create recent menu section
    createRecentMenuItems();

    KConfig *config = KGlobal::config();
    config->setGroup("menus");

    bool need_separator = false;

    // insert bookmarks
    if(config->readBoolEntry("UseBookmarks", true))
    {
        // Need to create a new popup each time, it's deleted by subMenus.clear()
        KPopupMenu * bookmarkParent = new KPopupMenu( this, "bookmarks" );
        if(!bookmarkOwner)
            bookmarkOwner = new KBookmarkOwner;
        if(bookmarkMenu)
            delete bookmarkMenu; // can't reuse old one, the popup has been deleted
        bookmarkMenu = new KBookmarkMenu( KonqBookmarkManager::self(), bookmarkOwner, bookmarkParent, actionCollection, true, false );

        QString bookmarkstring = i18n( "&Bookmarks" );
        int p;
        while ( ( p = bookmarkstring.find( '&' ) ) >= 0 )
            bookmarkstring.remove( p, 1 );
        insertItem( SmallIconSet( "bookmark" ), bookmarkstring, bookmarkParent );
        subMenus.append(bookmarkParent);
        need_separator = true;
    }

    // insert recent documents menu
    if(config->readBoolEntry("UseRecent", true))
    {
        PanelRecentMenu *recentMnu = new PanelRecentMenu(this);
        insertItem(SmallIconSet("document"), i18n("Recent Documents"), recentMnu);
        subMenus.append(recentMnu);
        need_separator = true;
    }

    // insert quickbrowser
    if(config->readBoolEntry("UseBrowser", true))
    {
        PanelQuickBrowser *browserMnu = new PanelQuickBrowser(this);
        insertItem(SmallIconSet("kdisknav"), i18n("Quick Browser"), browserMnu);
        subMenus.append(browserMnu);
        need_separator = true;
    }

    // insert dynamic menus
    QStringList menu_ext = config->readListEntry("Extensions");
    if (!menu_ext.isEmpty())
    {
        for (QStringList::ConstIterator it=menu_ext.begin(); it!=menu_ext.end(); ++it)
        {
            MenuInfo info(*it);
            KPanelMenu *menu = info.load();
            if (menu)
            {
                insertItem(SmallIconSet(info.icon()), info.name(), menu);
                subMenus.append(menu);
                need_separator = true;
            }
        }
    }

    if (need_separator)
        insertSeparator();

    // insert client menus, if any
    if (clients.count() > 0) {
        QIntDictIterator<KickerClientMenu> it(clients);
        while (it){
            if (it.current()->text.at(0) != '.')
                insertItem(
                    it.current()->icon,
                    it.current()->text,
                    it.current(),
                    it.currentKey()
                    );
            ++it;
        }
        insertSeparator();
    }

    // run command
    insertItem(SmallIconSet("run"), i18n("Run Command..."), this, SLOT( slotRunCommand() ) );
    insertSeparator();

    // insert panel menu
    PanelOpMenu *panelOpMenu = new PanelOpMenu( _panel, this );
    insertItem(SmallIconSet("panel"), i18n("Configure Panel"), panelOpMenu);
    subMenus.append(panelOpMenu);

    // lock and logout
    insertItem(SmallIconSet("lock"), i18n("Lock Screen"), this, SLOT(slotLock()));

    insertItem(SmallIconSet("exit"), i18n("Logout"), this, SLOT(slotLogout()));

    if (KGlobalSettings::insertTearOffHandle())
      insertTearOffHandle();

    setInitialized(true);
}

int PanelKMenu::insertClientMenu(KickerClientMenu *p)
{
    int id = client_id;
    clients.insert(id, p);
    slotClear();
    return id;
}

void PanelKMenu::removeClientMenu(int id)
{
    clients.remove(id);
    removeItem(id);
    slotClear();
}

extern int kicker_screen_number;

void PanelKMenu::slotLock()
{
    QCString appname( "kdesktop" );
    if ( kicker_screen_number )
        appname.sprintf("kdesktop-screen-%d", kicker_screen_number);
    kapp->dcopClient()->send(appname, "KScreensaverIface", "lock()", "");
}

void PanelKMenu::slotLogout()
{
    QApplication::syncX();
    kapp->requestShutDown();
}

void PanelKMenu::slotRunCommand()
{
    QByteArray data;
    QCString appname( "kdesktop" );
    if ( kicker_screen_number )
        appname.sprintf("kdesktop-screen-%d", kicker_screen_number);

    kapp->dcopClient()->send( appname, "KDesktopIface",
                              "popupExecuteCommand()", data );
}

void PanelKMenu::setMinimumSize(const QSize & s)
{
    KPanelMenu::setMinimumSize(s.width() + sidePixmap.width(), s.height());
}

void PanelKMenu::setMaximumSize(const QSize & s)
{
    KPanelMenu::setMaximumSize(s.width() + sidePixmap.width(), s.height());
}

void PanelKMenu::setMinimumSize(int w, int h)
{
    KPanelMenu::setMinimumSize(w + sidePixmap.width(), h);
}

void PanelKMenu::setMaximumSize(int w, int h)
{
  KPanelMenu::setMaximumSize(w + sidePixmap.width(), h);
}

QRect PanelKMenu::sideImageRect()
{
    return QStyle::visualRect( QRect( frameWidth(), frameWidth(), sidePixmap.width(),
                                      height() - 2*frameWidth() ), this );
}

void PanelKMenu::resizeEvent(QResizeEvent * e)
{
//    kdDebug(1210) << "PanelKMenu::resizeEvent():" << endl;
//    kdDebug(1210) << geometry().width() << ", " << geometry().height() << endl;

    PanelServiceMenu::resizeEvent(e);

    setFrameRect( QStyle::visualRect( QRect( sidePixmap.width(), 0,
                                      width() - sidePixmap.width(), height() ), this ) );
}

QSize PanelKMenu::sizeHint() const
{
    QSize s = PanelServiceMenu::sizeHint();
//    kdDebug(1210) << "PanelKMenu::sizeHint()" << endl;
//    kdDebug(1210) << s.width() << ", " << s.height() << endl;
    return s;
}

void PanelKMenu::paintEvent(QPaintEvent * e)
{
    if (sidePixmap.isNull()) {
        PanelServiceMenu::paintEvent(e);
        return;
    }

    QPainter p(this);

    style().drawPrimitive( QStyle::PE_PanelPopup, &p,
                           QRect( 0, 0, width(), height() ),
                           colorGroup(), QStyle::Style_Default,
                           QStyleOption( frameWidth(), 0 ) );

    QRect r = sideImageRect();
    r.setBottom( r.bottom() - sidePixmap.height() );
    p.drawTiledPixmap( r, sideTilePixmap );

    r = sideImageRect();
    r.setTop( r.bottom() - sidePixmap.height() );
    p.drawPixmap( r, sidePixmap );

    drawContents( &p );
}

QMouseEvent PanelKMenu::translateMouseEvent( QMouseEvent* e )
{
    QRect side = sideImageRect();

    if ( !side.contains( e->pos() ) )
        return *e;

    QPoint newpos( e->pos() );
    QApplication::reverseLayout() ?
        newpos.setX( newpos.x() - side.width() ) :
        newpos.setX( newpos.x() + side.width() );
    QPoint newglobal( e->globalPos() );
    QApplication::reverseLayout() ?
        newglobal.setX( newpos.x() - side.width() ) :
        newglobal.setX( newpos.x() + side.width() );

    return QMouseEvent( e->type(), newpos, newglobal, e->button(), e->state() );
}

void PanelKMenu::mousePressEvent(QMouseEvent * e)
{
    QMouseEvent newEvent = translateMouseEvent(e);
    PanelServiceMenu::mousePressEvent( &newEvent );
}

void PanelKMenu::mouseReleaseEvent(QMouseEvent *e)
{
    QMouseEvent newEvent = translateMouseEvent(e);
    PanelServiceMenu::mouseReleaseEvent( &newEvent );
}

void PanelKMenu::mouseMoveEvent(QMouseEvent *e)
{
    QMouseEvent newEvent = translateMouseEvent(e);
    PanelServiceMenu::mouseMoveEvent( &newEvent );
}
