#include "bitmapwidget.h"
#include <qpainter.h>

KPBitmapWidget::KPBitmapWidget(QWidget *parent, const char *name)
    : QWidget(parent, name)
{
    cellExtent = 1;
    resize(0, 0);
    cBmp = NULL;
}

void KPBitmapWidget::reset()
{
    resize(0, 0);
    cBmp = NULL;
    cellExtent = 1;
    emit scaleChanged("100%");
    emit zoomInEnabled(false);
    emit zoomOutEnabled(false);
}

void KPBitmapWidget::increaseScale()
{
    cellExtent*=2;
    if(cellExtent == 4)
        emit zoomInEnabled(false);
    else
        emit zoomInEnabled(true);
    emit zoomOutEnabled(true);

    QString str;
    str.sprintf("%d%%", (int)(cellExtent*100));
    emit scaleChanged(str);
    if(cBmp)
        resize(cBmp->width()*cellExtent, cBmp->height()*cellExtent);
}

void KPBitmapWidget::decreaseScale()
{
    cellExtent*=0.5;
    if(cellExtent == 0.25)
        emit zoomOutEnabled(false);
    else
        emit zoomOutEnabled(true);
    emit zoomInEnabled(true);

    QString str;
    str.sprintf("%d%%", (int)(cellExtent*100));
    emit scaleChanged(str);
    if(cBmp)
        resize(cBmp->width()*cellExtent, cBmp->height()*cellExtent);
}

void KPBitmapWidget::setBitmap(QBitmap *bitmap)
{
    cBmp = bitmap;
    if(cBmp){
        resize(cBmp->width()*cellExtent, cBmp->height()*cellExtent);
        cellExtent != 0.25 ? emit zoomInEnabled(true) : emit zoomInEnabled(false);
        cellExtent != 4 ? emit zoomOutEnabled(true) : emit zoomOutEnabled(false);
        repaint(false);
    }
    else
        resize(0, 0);
}

QBitmap* KPBitmapWidget::bitmap()
{
    return(cBmp);
}

void KPBitmapWidget::paintEvent(QPaintEvent *ev)
{
    QPainter p(this);
    if(!cBmp){
        p.fillRect(ev->rect(), QBrush(Qt::white, SolidPattern));
        return;
    }
    p.setBackgroundColor(Qt::white);
    p.setPen(Qt::black);
    p.scale(cellExtent, cellExtent);
    QRect r = p.xFormDev(ev->rect());
    // no idea why I have to do this but if I don't the area doesn't get
    // entirely filled :P Using ev->rect() for the pixmap coords doesn't work
    // either, although that is not scaled...
    if(r.x() > 0)
        r.setX(r.x()-1);
    if(r.y() > 0)
        r.setY(r.y()-1);
    r.setWidth(r.width()+2);
    r.setHeight(r.height()+2);
    p.drawPixmap(r.topLeft(), *cBmp, r);
}

#include "bitmapwidget.moc"



