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

Copyright (c) 2004 Zack Rusin <zrusin@kde.org>
                   Sami Kyostil <skyostil@kempele.fi>
                   Aaron J. Seigo <aseigo@kde.org>

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 <qapplication.h>
#include <qpainter.h>
#include <qsimplerichtext.h>
#include <qtimer.h>

#include <kdialog.h>

#include "kickertip.h"

static const int DEFAULT_FRAMES = 30;

KickerTip* KickerTip::m_self = 0;
int KickerTip::m_tippingEnabled = 1;

KickerTip* KickerTip::the()
{
    if (!m_self)
    {
        m_self = new KickerTip(0);
    }

    return m_self;
}

KickerTip::KickerTip(QWidget * parent)
    : QWidget(parent, "animtt",WX11BypassWM),
      m_richText(0),
      m_dissolveSize(0),
      m_dissolveDelta(-1),
      m_dirty(false),
      m_tippingFor(0)
{
    setFocusPolicy(NoFocus);
    setBackgroundMode(NoBackground);
    resize(0, 0);
    hide();
    connect(&m_timer, SIGNAL(timeout()), SLOT(hide()));
    connect(&m_frameTimer, SIGNAL(timeout()), SLOT(internalUpdate()));
}

void KickerTip::display(const QString& title,
                        const QString& subtext,
                        const QPixmap& icon,
                        MaskEffect mEff,
                        int durationMs)
{
    if (!tippingEnabled())
    {
        return;
    }

    delete m_richText;
    m_richText = new QSimpleRichText("<qt><nobr><h3>" + title + "</h3><p>" +
                                     subtext + "</p></qt>",
                                     font());
    m_icon = icon;
    m_maskEffect = isVisible() ? Plain : mEff;
    m_dissolveSize = 24;
    m_dissolveDelta = -1;

    displayInternal();

    m_frameTimer.start(1000 / DEFAULT_FRAMES);

    // close the message window after given mS
    if (durationMs > 0)
    {
        m_timer.start(durationMs, true);
    }
    else
    {
        m_timer.stop();
    }
}

void KickerTip::paintEvent(QPaintEvent * e)
{
    if (m_dirty)
    {
        displayInternal();
        m_dirty = false;
    }

    QPainter p(this);
    p.drawPixmap(e->rect().topLeft(), m_pixmap, e->rect());
}

void KickerTip::mousePressEvent(QMouseEvent * /*e*/)
{
    m_timer.stop();
    m_frameTimer.stop();
    hide();
}

void KickerTip::plainMask()
{
    QPainter maskPainter(&m_mask);

    m_mask.fill(Qt::black);

    maskPainter.setBrush(Qt::white);
    maskPainter.setPen(Qt::white);
    maskPainter.drawRoundRect(m_mask.rect(), 1600 / m_mask.rect().width(),
                              1600 / m_mask.rect().height());
    setMask(m_mask);
    m_frameTimer.stop();
}

void KickerTip::dissolveMask()
{
    QPainter maskPainter(&m_mask);

    m_mask.fill(Qt::black);

    maskPainter.setBrush(Qt::white);
    maskPainter.setPen(Qt::white);
    maskPainter.drawRoundRect(m_mask.rect(), 1600 / m_mask.rect().width(),
                              1600 / m_mask.rect().height());

    m_dissolveSize += m_dissolveDelta;

    if (m_dissolveSize > 0)
    {
        maskPainter.setRasterOp(Qt::EraseROP);

        int x, y, s;
        const int size = 16;

        for (y = 0; y < height() + size; y += size)
        {
            x = width();
            s = m_dissolveSize * x / 128;
            for (; x > -size; x -= size, s -= 2)
            {
                if (s < 0)
                {
                    s = 0;
                }
                maskPainter.drawEllipse(x - s / 2, y - s / 2, s, s);
            }
        }
    }
    else if (m_dissolveSize < 0)
    {
        m_frameTimer.stop();
        m_dissolveDelta = 1;
    }

    setMask(m_mask);
}

void KickerTip::displayInternal()
{
    if (!m_richText)
    {
        return;
    }

    // determine text rectangle
    QRect textRect(0, 0, m_richText->width(), m_richText->height());
    textRect.moveBy(-textRect.left(), -textRect.top());
    textRect.addCoords(0, 0, 2, 2);

    int textX = 2 + 3 * m_icon.width() / 2;
    int width = textX + textRect.width() + KDialog::marginHint();
    int height = QMAX(3 * m_icon.height() / 2 , textRect.height());
    int textY = (height - textRect.height()) / 2;

    resize(width, height);

    // resize pixmap, mask and widget
    m_mask.resize(width, height);
    m_pixmap.resize(width, height);
    resize(width, height);

    // create and set transparency mask
    switch(m_maskEffect)
    {
        case Plain:
            plainMask();
            break;

        case Dissolve:
            dissolveMask();
            break;
    }

    // draw background
    QPainter bufferPainter(&m_pixmap);
    bufferPainter.setPen(Qt::black);
    bufferPainter.setBrush(backgroundColor());
    bufferPainter.drawRoundRect(0, 0, width, height,
                                1600 / width, 1600 / height);

    // draw icon if present
    if (!m_icon.isNull())
    {
        int yOffset = m_icon.height() / 4;
        bufferPainter.drawPixmap(this->height() / 2 - m_icon.width() / 2,
                                 height - m_icon.height() / 2 -
                                 m_icon.height() / 2 - yOffset,
                                 m_icon, 0, 0,
                                 m_icon.width(), m_icon.height());
    }

    // draw text shadow
    QColorGroup cg = colorGroup();
    cg.setColor(QColorGroup::Text, cg.background().dark(115));
    int shadowOffset = QApplication::reverseLayout() ? -1 : 1;
    m_richText->draw(&bufferPainter, 5 + textX + shadowOffset, textY + 1, QRect(), cg);

    // draw text
    cg = colorGroup();
    m_richText->draw(&bufferPainter, 5 + textX, textY, rect(), cg);
}

void KickerTip::internalUpdate()
{
    m_dirty = true;
    update();
}

void KickerTip::tipFor(const QWidget* w)
{
    m_tippingFor = w;
}

void KickerTip::untipFor(const QWidget* w)
{
    if (isTippingFor(w))
    {
        tipFor(0);
        m_timer.stop();
        hide();
    }
}

bool KickerTip::isTippingFor(const QWidget* w) const
{
    return m_tippingFor == w;
}

void KickerTip::enableTipping(bool tip)
{
    if (tip)
    {
        m_tippingEnabled++;
    }
    else
    {
        m_tippingEnabled--;
    }

    if (m_tippingEnabled < 1 && m_self)
    {
        m_self->m_tippingFor = 0;
        m_self->hide();
    }
}

bool KickerTip::tippingEnabled()
{
    return m_tippingEnabled > 0;
}

void KickerTip::hide()
{
    m_tippingFor = 0;
    QWidget::hide();
}

#include <kickertip.moc>

