/*
 * Copyright (C) 2008 Instituto Nokia de Tecnologia. All rights reserved.
 *
 * This file is part of QZion.
 *
 * QZion is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * QZion is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with QZion.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "qziontextblock_p.h"

QGraphicsQZionTextBlockItem::QGraphicsQZionTextBlockItem(QGraphicsItem *parent)
    : QAbstractGraphicsShapeItem(parent), _text(""), _scale(1.0)
{
    setFlag(QGraphicsItem::ItemClipsToShape, true);

    QPalette palette;
    palette.setBrush(QPalette::Window, QBrush(QColor(255, 255, 255, 0)));
    _page.setPalette(palette);
    _page.mainFrame()->setHtml(_text);
    _page.mainFrame()->setScrollBarPolicy(Qt::Horizontal, Qt::ScrollBarAlwaysOff);
    _page.mainFrame()->setScrollBarPolicy(Qt::Vertical, Qt::ScrollBarAlwaysOff);
}


QRectF QGraphicsQZionTextBlockItem::boundingRect() const
{
    return QRectF(0, 0, _size.width(), _size.height());
}


void QGraphicsQZionTextBlockItem::paint(QPainter *painter,
                                   const QStyleOptionGraphicsItem *option,
                                   QWidget *widget)
{
    Q_UNUSED(option);
    Q_UNUSED(widget);

    // tests with zooming on webkit showed these flags
    // provide the best results (good image scaling and
    // no loss of details, specially underlined text)
    painter->setRenderHints(QPainter::SmoothPixmapTransform |
                            QPainter::Antialiasing);

    painter->scale(_scale, _scale);
    _page.mainFrame()->render(painter);
}

QSize QGraphicsQZionTextBlockItem::size() const
{
    return _size;
}

void QGraphicsQZionTextBlockItem::setSize(const QSize &size)
{
    if (_size == size)
        return;

    prepareGeometryChange();

    _size = size;

    if (preferredWidth) {
        update();
        return;
    }

    _page.setViewportSize(QSize(size.width(), 1));
    _page.setViewportSize(_page.mainFrame()->contentsSize());
    update();
}

double QGraphicsQZionTextBlockItem::scale()
{
    return _scale;
}

void QGraphicsQZionTextBlockItem::setScale(double factor)
{
    _scale = factor;
}

QString QGraphicsQZionTextBlockItem::text() const
{
    return _text;
}


void QGraphicsQZionTextBlockItem::setText(const QString &text)
{
    if (_text != text) {
        _text = text;
        _page.mainFrame()->setHtml(text);
    }
}
