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

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 <qcursor.h>
#include <qmovie.h>
#include <qpainter.h>
#include <qpopupmenu.h>
#include <qstyle.h>
#include <qtooltip.h>

#include <kapplication.h>
#include <kconfig.h>
#include <kcursor.h>
#include <kdialog.h>
#include <kglobal.h>
#include <kglobalsettings.h>
#include <kiconloader.h>
#include <kicontheme.h>
#include <kipc.h>
#include <kstandarddirs.h>
#include <klocale.h>

#include "global.h"

#include "kickerSettings.h"
#include "kickertip.h"
#include "panelbutton.h"
#include "panelbutton.moc"

PanelButton::PanelButton( QWidget* parent, const char* name )
    : QButton(parent, name),
      m_valid(true),
      m_isLeftMouseButtonDown(false),
      m_drawArrow(false),
      m_highlight(false),
      m_animated(false),
      m_changeCursorOverItem(true),
      m_hasAcceptedDrag(false),
      m_hasAnimation(true),
      m_movie(0L),
      m_arrowDirection(KPanelExtension::Bottom),
      m_popupDirection(KPanelApplet::Up),
      m_orientation(Horizontal),
      m_size((KIcon::StdSizes)-1)
{
    KGlobal::locale()->insertCatalogue("libkicker");
    calculateIconSize();
    setAcceptDrops(true);

    updateSettings(KApplication::SETTINGS_MOUSE);

    kapp->addKipcEventMask(KIPC::SettingsChanged | KIPC::IconChanged);

    connect(kapp, SIGNAL(settingsChanged(int)), SLOT(updateSettings(int)));
    connect(kapp, SIGNAL(iconChanged(int)), SLOT(updateIcon(int)));
}

void PanelButton::configure()
{
    if (!KickerSettings::showMouseOverEffects() &&
        KickerSettings::showToolTips())
    {
        QToolTip::add(this, m_tip);
    }
    else
    {
        QToolTip::remove(this);
    }

    QString name = tileName();
    if( name.isEmpty() )
        return;

    KConfigGroup config( KGlobal::config(), "buttons" );
    if( !config.readBoolEntry( "EnableTileBackground", false ) ) {
        setTile( QString::null );
        return;
    }

    KConfigGroup tilesGroup( KGlobal::config(), "button_tiles" );
    if( !tilesGroup.readBoolEntry( "Enable" + name + "Tiles", true ) ) {
            setTile( QString::null );
        return;
    }

    QString tile = tilesGroup.readEntry( name + "Tile" );
    QColor color = QColor();

    if (tile == "Colorize")
    {
        color = tilesGroup.readColorEntry( name + "TileColor" );
        tile = QString::null;
    }

    setTile( tile, color );
}

void PanelButton::setTile(const QString& tile, const QColor& color)
{
    if (tile == m_tile && m_tileColor == color)
    {
        return;
    }

    m_tile = tile;
    m_tileColor = color;
    loadTiles();
    update();
}

void PanelButton::setDrawArrow(bool drawArrow)
{
    if (m_drawArrow == drawArrow)
    {
        return;
    }

    m_drawArrow = drawArrow;
    update();
}

void PanelButton::setIcon(const QString& icon)
{
    if (icon == m_iconName)
    {
        return;
    }

    m_iconName = icon;
    loadIcons();
    update();
    emit iconChanged();
}

QImage PanelButton::loadTile(const QString& tile,
                             const QSize& size,
                             const QString& state)
{
    QString name = tile;

    if (size.height() < 42)
    {
        name += "_tiny_";
    }
    else if (size.height() < 54)
    {
        name += "_normal_";
    }
    else
    {
        name += "_large_";
    }

    name += state + ".png";

    QImage tileImg(KGlobal::dirs()->findResource("tiles", name));

    // scale if size does not match exactly
    if (!tileImg.isNull() && tileImg.size() != size)
    {
        tileImg = tileImg.smoothScale(size);
    }

    return tileImg;
}

void PanelButton::setPopupDirection(KPanelApplet::Direction d)
{
    m_popupDirection = d;
    setArrowDirection(KickerLib::directionToPopupPosition(d));
}

void PanelButton::movieUpdate(const QRect& /*rect*/)
{
    if (m_animated)
    {
        emit iconChanged();
        update(); // update all since rect seems to be set incorrect
    // update(rect);
    }
}

void PanelButton::movieStatus(int status)
{
    if (status < 0 && m_animated)
    {
        // Error playing the MNG -> forget about it and do normal iconeffect
        m_movie->disconnectUpdate(this, SLOT(movieUpdate(const QRect&)));
        m_movie->disconnectStatus(this, SLOT(movieStatus(int)));
        delete m_movie;
        m_movie = 0;
        m_animated = false ;
        m_hasAnimation = false;
        emit iconChanged();
        update();
    }
    /*
    else if (status == QMovie::EndOfMovie)
    {
    // We could trigger on end of movie here, we don't because we wish to
    // view the last frame of the movie for the rest of the mouse-over .
    }
    */
}

void PanelButton::updateIcon(int group)
{
    if (group != KIcon::Panel)
    {
        return;
    }

    loadIcons();
    update();
}

void PanelButton::updateSettings(int category)
{
    if (category != KApplication::SETTINGS_MOUSE)
    {
        return;
    }

    m_changeCursorOverItem = KGlobalSettings::changeCursorOverIcon();

    if (m_changeCursorOverItem)
    {
        setCursor(KCursor::handCursor());
    }
    else
    {
        unsetCursor();
    }
}

void PanelButton::showMouseOver()
{
    if (!KickerTip::the()->isTippingFor(this))
    {
        return;
    }

    if (!rect().contains(mapFromGlobal(QCursor::pos())))
    {
        KickerTip::the()->untipFor(this);
        return;
    }

    KickerTip::the()->display(title(), tip(), zoomIcon());

    QPoint p = KickerLib::popupPosition(popupDirection(),
                                        KickerTip::the(),
                                        this);
    KickerTip::the()->move(p);
    KickerTip::the()->show();
}

void PanelButton::setTip(const QString& tip)
{
    m_tip = tip;
    if (!KickerSettings::showMouseOverEffects() &&
        KickerSettings::showToolTips())
    {
        QToolTip::add(this, m_tip);
    }
}

void PanelButton::hideMouseOver()
{
    KickerTip::the()->untipFor(this);
}

// return the dimension that the button wants to be for a given panel dimension (panelDim)
int PanelButton::preferredDimension(int panelDim) const
{
    // determine the upper limit on the size.  Normally, this is panelDim,
    // but if conserveSpace() is true, we restrict size to comfortably fit the icon
    if (KickerSettings::conserveSpace())
    {
        int newSize = preferredIconSize(panelDim);
        if (newSize > 0)
        {
            return QMIN(panelDim, newSize + KDialog::spacingHint()*2);
        }
    }

    return panelDim;
}

const QPixmap& PanelButton::labelIcon() const
{
    if (m_animated)
    {
        return m_movie->framePixmap();
    }

    return m_highlight ? m_iconh : m_icon;
}

void PanelButton::triggerDrag()
{
    setDown(false);

    if (KickerTip::tippingEnabled())
    {
        KickerTip::the()->untipFor(this);
        kapp->processEvents();
        kapp->syncX();
    }

    startDrag();
}

void PanelButton::startDrag()
{
    emit dragme(m_icon);
}

void PanelButton::enterEvent(QEvent* e)
{
    if (!m_highlight)
    {
        m_highlight = true;
        repaint(false);
    }

    if (!KickerSettings::showMouseOverEffects())
    {
        QButton::enterEvent(e);
        return;
    }


    if (m_hasAnimation)
    {
        QMovie movie = KGlobal::iconLoader()->loadMovie(m_iconName,
                                                        KIcon::Panel,
                                                        m_size);
        if (movie.isNull())
        {
            m_hasAnimation = false;
        }
        else
        {
            delete m_movie;
            m_movie = new QMovie(movie);
            m_movie->connectUpdate(this, SLOT(movieUpdate(const QRect&)));
            m_movie->connectStatus(this, SLOT(movieStatus(int)));
            m_animated = true;
        }
    }

    if (!KickerTip::tippingEnabled())
    {
        QButton::enterEvent(e);
        return;
    }

    if (!mouseGrabber() &&
        !qApp->activePopupWidget() &&
        !KickerTip::the()->isTippingFor(this))
    {
        KickerTip::the()->tipFor(this);

        if (KickerTip::the()->isVisible())
        {
            showMouseOver();
        }
        else
        {
            // delay if it isn't shown to avoid false starts
            // e.g. when the user quickly zooms their mouse over
            // a button then out of kicker
            QTimer::singleShot(250, this, SLOT(showMouseOver()));
        }

        return;
    }

    QButton::enterEvent(e);
}

void PanelButton::leaveEvent(QEvent* e)
{
    if (m_animated)
    {
        //  Should always disconnect before deletion,
        // because QMovie uses explicit sharing
        m_movie->disconnectUpdate(this, SLOT(movieUpdate(const QRect&)));
        m_movie->disconnectStatus(this, SLOT(movieStatus(int)));
        delete m_movie;
        m_movie = 0L;
        m_animated = false;
        repaint(false);
    }

    if (KickerTip::tippingEnabled() &&
        KickerTip::the()->isTippingFor(this) &&
        KickerTip::the()->isVisible())
    {
        QTimer::singleShot(200, this, SLOT(hideMouseOver()));
    }

    if (m_highlight)
    {
        m_highlight = false;
        repaint(false);
    }

    QButton::leaveEvent(e);
}

void PanelButton::dragEnterEvent(QDragEnterEvent* e)
{
    if (e->isAccepted())
    {
        m_hasAcceptedDrag = true;
    }

    update();
    QButton::dragEnterEvent( e );
}

void PanelButton::dragLeaveEvent(QDragLeaveEvent* e)
{
    m_hasAcceptedDrag = false;
    update();
    QButton::dragLeaveEvent( e );
}

void PanelButton::dropEvent(QDropEvent* e)
{
    m_hasAcceptedDrag = false;
    update();
    QButton::dropEvent( e );
}

void PanelButton::mouseMoveEvent(QMouseEvent *e)
{
    if (!m_isLeftMouseButtonDown || (e->state() & LeftButton) == 0)
    {
        return;
    }

    QPoint p(e->pos() - m_lastLeftMouseButtonPress);
    if (p.manhattanLength() <= 16)
    {
        // KGlobalSettings::dndEventDelay() is not enough!
        return;
    }

    m_isLeftMouseButtonDown = false;
    triggerDrag();
}

void PanelButton::mousePressEvent(QMouseEvent *e)
{
    if (e->button() == LeftButton)
    {
        m_lastLeftMouseButtonPress = e->pos();
        m_isLeftMouseButtonDown = true;
    }
    QButton::mousePressEvent(e);
}

void PanelButton::mouseReleaseEvent(QMouseEvent *e)
{
    if (e->button() == LeftButton)
    {
        m_isLeftMouseButtonDown = false;
    }
    QButton::mouseReleaseEvent(e);
}

void PanelButton::resizeEvent(QResizeEvent*)
{
    loadTiles();

    if (calculateIconSize())
    {
        loadIcons();
    }
}

void PanelButton::drawButton(QPainter *p)
{
    // Draw the background. This is always needed, even when using tiles,
    // because they don't have to cover the entire button.
    if (m_tileColor.isValid())
    {
        p->fillRect(rect(), m_tileColor);
        style().drawPrimitive(QStyle::PE_Panel, p, rect(), colorGroup());
    }

    const QPixmap& tile = (isDown() || isOn()) ? m_down : m_up;
    if (!tile.isNull())
    {
        // Draw the tile.
        p->drawPixmap(0, 0, tile);
    }
    else if (isDown() || isOn())
    {
        // Draw shapes to indicate the down state.
        style().drawPrimitive(QStyle::PE_Panel, p, rect(), colorGroup(), QStyle::Style_Sunken);
    }

    drawButtonLabel(p);

    if (hasFocus() || m_hasAcceptedDrag)
    {
        int x1, y1, x2, y2;
        rect().coords(&x1, &y1, &x2, &y2);
        QRect r(x1+2, y1+2, x2-x1-3, y2-y1-3);
        style().drawPrimitive(QStyle::PE_FocusRect, p, r, colorGroup(),
        QStyle::Style_Default, colorGroup().button());
    }
}

void PanelButton::drawButtonLabel(QPainter *p)
{
    if (isDown() || isOn())
    {
        p->translate(2,2);
    }

    const QPixmap& icon = labelIcon();
    if (!icon.isNull())
    {
        int x = (width()  - icon.width() )/2;
        int y = (height() - icon.height())/2;
        p->drawPixmap(x, y, icon);
    }

    if (m_drawArrow)
    {
        QStyle::PrimitiveElement e = QStyle::PE_ArrowUp;
        QRect r(0, 0, 8, 8);

        switch (m_arrowDirection)
        {
            case KPanelExtension::Top:
                e = QStyle::PE_ArrowUp;
                break;
            case KPanelExtension::Bottom:
                e = QStyle::PE_ArrowDown;
                r.moveBy(0, height() - 8);
                break;
            case KPanelExtension::Right:
                e = QStyle::PE_ArrowRight;
                r.moveBy(width() - 8 , 0);
                break;
            case KPanelExtension::Left:
                e = QStyle::PE_ArrowLeft;
                break;
            case KPanelExtension::Floating:
                if (orientation() == Horizontal)
                {
                    e = QStyle::PE_ArrowDown;
                }
                else if (QApplication::reverseLayout())
                {
                    e = QStyle::PE_ArrowLeft;
                }
                else
                {
                    e = QStyle::PE_ArrowRight;
                }
                break;
        }

        int flags = QStyle::Style_Enabled;
        if (isDown() || isOn())
        {
            flags |= QStyle::Style_Down;
        }
        style().drawPrimitive(e, p, r, colorGroup(), flags);
    }

    if (isDown() || isOn())
    {
        p->translate(-2,-2);
    }
}

// return the icon size that would be used if the panel were proposed_size
// if proposed_size==-1, use the current panel size instead
int PanelButton::preferredIconSize(int proposed_size) const
{
    // (re)calculates the icon sizes and report true if they have changed.
    // Get sizes from icontheme. We assume they are sorted.
    KIconTheme *ith = KGlobal::iconLoader()->theme();

    if (!ith)
    {
        return -1; // unknown icon size
    }

    QValueList<int> sizes = ith->querySizes(KIcon::Panel);

    int sz = ith->defaultSize(KIcon::Panel);

    if (proposed_size < 0)
    {
        proposed_size = (orientation() == Horizontal) ? height() : width();
    }

    // determine the upper limit on the size.  Normally, this is panelSize,
    // but if conserve space is requested, the max button size is used instead.
    int upperLimit = proposed_size;
    if (proposed_size > KickerLib::maxButtonDim() &&
        KickerSettings::conserveSpace())
    {
        upperLimit = KickerLib::maxButtonDim();
    }

    //kdDebug()<<endl<<endl<<flush;
    QValueListConstIterator<int> i = sizes.constBegin();
    while (i != sizes.constEnd())// &&
    {
        if (   (*i) + (2 * KickerLib::iconMargin()) > upperLimit)
        {
            break;
        }
        sz = *i++;   // get the largest size under the limit
    }

    //kdDebug()<<"Using icon sizes: "<<sz<<"  "<<zoom_sz<<endl<<flush;
    return sz;
}

void PanelButton::setArrowDirection(KPanelExtension::Position dir)
{
    if (m_arrowDirection != dir)
    {
        m_arrowDirection = dir;
        update();
    }
}

void PanelButton::loadTiles()
{
    if (m_tileColor.isValid())
    {
        setBackgroundOrigin(WidgetOrigin);
        m_up = m_down = QPixmap();
    }
    else if (m_tile.isNull())
    {
        setBackgroundOrigin(AncestorOrigin);
        m_up = m_down = QPixmap();
    }
    else
    {
        setBackgroundOrigin(WidgetOrigin);
        // If only the tiles were named a bit smarter we wouldn't have
        // to pass the up or down argument.
        m_up   = QPixmap(loadTile(m_tile, size(), "up"));
        m_down = QPixmap(loadTile(m_tile, size(), "down"));
    }
}

void PanelButton::loadIcons()
{
    KIconLoader * ldr = KGlobal::iconLoader();
    QString nm = m_iconName;
    m_hasAnimation = true;

    m_icon = ldr->loadIcon(nm, KIcon::Panel, m_size,
                           KIcon::DefaultState, 0L, true);

    if (m_icon.isNull())
    {
        nm = defaultIcon();
        m_icon = ldr->loadIcon(nm, KIcon::Panel,
                               m_size, KIcon::DefaultState);
    }

    m_iconh = ldr->loadIcon(nm, KIcon::Panel, m_size,
                            KIcon::ActiveState, 0L, true);
    m_iconz = ldr->loadIcon(nm, KIcon::Panel, KIcon::SizeHuge,
                            KIcon::DefaultState, 0L, true );
}

// (re)calculates the icon sizes and report true if they have changed.
//      (false if we don't know, because theme couldn't be loaded?)
bool PanelButton::calculateIconSize()
{
    int size = preferredIconSize();

    if (size < 0)
    {
        // size unknown
        return false;
    }

    if (m_size != size)
    {
        // Size has changed, update
        m_size = size;
        return true;
    }

    return false;
}

//
// PanelPopupButton class
//

PanelPopupButton::PanelPopupButton(QWidget *parent, const char *name)
  : PanelButton(parent, name)
{
    m_pressedDuringPopup = false;
    m_popup = 0;
    setDrawArrow(true);
    connect(this, SIGNAL(pressed()), SLOT(slotExecMenu()));
}

void PanelPopupButton::setPopup(QPopupMenu *popup)
{
    if (m_popup)
    {
        m_popup->removeEventFilter(this);
    }

    m_popup = popup;

    if (popup)
    {
        m_popup->installEventFilter(this);
    }
}

QPopupMenu *PanelPopupButton::popup() const
{
    return m_popup;
}

bool PanelPopupButton::eventFilter(QObject *, QEvent *e)
{
    if (e->type() == QEvent::MouseMove)
    {
        QMouseEvent *me = static_cast<QMouseEvent *>(e);
        if (rect().contains(mapFromGlobal(me->globalPos())) &&
            ((me->state() & ControlButton) != 0 ||
             (me->state() & ShiftButton) != 0))
        {
            PanelButton::mouseMoveEvent(me);
            return true;
        }
    }
    else if (e->type() == QEvent::MouseButtonPress ||
             e->type() == QEvent::MouseButtonDblClick)
    {
        QMouseEvent *me = static_cast<QMouseEvent *>(e);
        if (rect().contains(mapFromGlobal(me->globalPos())))
        {
            m_pressedDuringPopup = true;
            return true;
        }
    }
    else if (e->type() == QEvent::MouseButtonRelease)
    {
        QMouseEvent *me = static_cast<QMouseEvent *>(e);
        if (rect().contains(mapFromGlobal(me->globalPos())))
        {
            if (m_pressedDuringPopup && m_popup)
            {
                m_popup->hide();
            }
            return true;
        }
    }
    return false;
}

void PanelPopupButton::slotExecMenu()
{
    if (KickerTip::tippingEnabled())
    {
        KickerTip::the()->untipFor(this);
    }

    if (m_popup != 0)
    {
        m_pressedDuringPopup = false;
        KickerTip::enableTipping(false);
        kapp->syncX();
        kapp->processEvents();
        initPopup();
        m_popup->adjustSize();
        m_popup->exec(KickerLib::popupPosition(popupDirection(), m_popup, this));
        setDown(false);
        KickerTip::enableTipping(true);
    }
}

void PanelPopupButton::triggerDrag()
{
    if (m_popup)
    {
        m_popup->hide();
    }

    PanelButton::triggerDrag();
}

