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

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 <sys/types.h>
#include <unistd.h>

#include <qpainter.h>
#include <qstyle.h>
#include <qfile.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 <kmessagebox.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 "client_mnu.h"
#include "popupmenutitle.h"
#include "container_base.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" ) );
}

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();
      setMinimumSize( sizeHint() );
    }
}

void PanelKMenu::configChanged()
{
    PanelServiceMenu::configChanged();
    deinitialize();
}

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
/* This item should be at the top of the menu...
#include <kuser.h>
    insertItem(SmallIconSet("kuser"), KUser().loginName(), this, SLOT( slotEditUserContact() ) );
*/
    PanelServiceMenu::initialize();

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

    if (config->readBoolEntry("ShowMenuTitles", true))
    {
        int id;
        id = insertItem(new PopupMenuTitle(i18n("All Applications"), font()), -1 /* id */, 0);
        setItemEnabled( id, false );
        id = insertItem(new PopupMenuTitle(i18n("Actions"), font()), -1 /* id */, -1);
        setItemEnabled( id, false );
    }

    // create recent menu section
    createRecentMenuItems();

    bool need_separator = false;

    // insert bookmarks
    if(config->readBoolEntry("UseBookmarks", true) && kapp->authorizeKAction("bookmarks"))
    {
        // 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;
        delete bookmarkMenu; // can't reuse old one, the popup has been deleted
        bookmarkMenu = new KBookmarkMenu( KonqBookmarkManager::self(), bookmarkOwner, bookmarkParent, actionCollection, true, false );

        insertItem( SmallIconSet("bookmark"), i18n( "Bookmarks" ), bookmarkParent );
        subMenus.append(bookmarkParent);
        need_separator = true;
    }

    // insert quickbrowser
    if(config->readBoolEntry("UseBrowser", true))
    {
        PanelQuickBrowser *browserMnu = new PanelQuickBrowser(this);
        browserMnu->initialize();
        insertItem(SmallIconSet("kdisknav"), i18n("Quick Browser"), BaseContainer::reduceMenu(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);
            if (!info.isValid())
               continue;

            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
    if (kapp->authorize("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);

    QStringList dmopt =
        QStringList::split( QChar( ',' ),
                            QString::fromLatin1( ::getenv( "XDM_MANAGED" ) ) );
    if ( dmopt.findIndex( "rsvd" ) < 0 )
        xdmFifoName = QString::null;
    else {
        xdmFifoName = dmopt.first();
	if (kapp->authorize("start_new_session")){
	        insertItem(SmallIconSet("fork"), i18n("Start New Session..."), this, SLOT(slotNewSession()));
	}
    }

    /*
      If  the user configured ksmserver to
    */
    KConfig ksmserver("ksmserverrc", false, false);
    ksmserver.setGroup("General");
    if ( ksmserver.readEntry( "loginMode" ) == "restoreSavedSession"  )
        insertItem(SmallIconSet("filesave"), i18n("Save Session"), this, SLOT(slotSaveSession()));

    if (kapp->authorize("lock_screen"))
        insertItem(SmallIconSet("lock"), i18n("Lock Session"), this, SLOT(slotLock()));

    if (kapp->authorize("logout"))
      insertItem(SmallIconSet("exit"), i18n("Logout..."), this, SLOT(slotLogout()));

#if 0
    // WABA: tear off handles don't work together with dynamically updated
    // menus. We can't update the menu while torn off, and we don't know
    // when it is torn off.
    if (KGlobalSettings::insertTearOffHandle())
      insertTearOffHandle();
#endif

    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()
{
    kapp->requestShutDown();
}

void PanelKMenu::slotNewSession()
{
    KDialogBase *dialog= new KDialogBase("",
                       KDialogBase::Yes | KDialogBase::No,
                       KDialogBase::Yes, KDialogBase::No,
                       kapp->desktop()->screen(kapp->desktop()->screenNumber(this)),
                       "warningYesNo", true, true,
                       KGuiItem(i18n("&Start New Session"), "fork"), KStdGuiItem::cancel() );
    dialog->setPlainCaption(i18n("Warning - New Session"));

    bool checkboxResult = kapp->authorize("lock_screen");
    const QString text = i18n("<p>You have chosen to open another desktop session.<br>"
               "The current session will be hidden "
               "and a new login screen will be displayed.<br>"
               "An F-key is assigned to each session; "
               "F%1 is usually assigned to the first session, "
               "F%2 to the second session and so on. "
               "You can switch between sessions by pressing "
               "CTRL, ALT and the appropriate F-key at the same time.</p>")
                           .arg(7).arg(8);

    int result = KMessageBox::createKMessageBox(dialog, QMessageBox::Warning,
                       text, QStringList(),
                       checkboxResult ? i18n("&Lock current session") : QString::null,
                       &checkboxResult, 0);

    if (result==KDialogBase::No)
        return;

    if (checkboxResult)
        slotLock();

    QFile fifo(xdmFifoName);
    if (fifo.open(IO_WriteOnly | IO_Raw)) {
        fifo.writeBlock( "reserve\n", 8 );
        fifo.close();
    }
}

void PanelKMenu::slotSaveSession()
{
    QByteArray data;
    kapp->dcopClient()->send( "ksmserver", "default",
                              "saveCurrentSession()", data );
}

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

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

void PanelKMenu::slotEditUserContact()
{
}

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

//Workaround Qt3.3.x sizing bug, by ensuring we're always wide enough.
void PanelKMenu::resize(int width, int height)
{
    width = kMax(width, maximumSize().width());
    PanelServiceMenu::resize(width, height);
}

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);
    p.setClipRegion(e->region());

    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() );
    if ( r.intersects( e->rect() ) )
    {
        p.drawTiledPixmap( r, sideTilePixmap );
    }

    r = sideImageRect();
    r.setTop( r.bottom() - sidePixmap.height() );
    if ( r.intersects( e->rect() ) )
    {
        QRect drawRect = r.intersect( e->rect() );
        QRect pixRect = drawRect;
        pixRect.moveBy( -r.left(), -r.top() );
        p.drawPixmap( drawRect.topLeft(), sidePixmap, pixRect );
    }

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