#include "scrolltoplevel.h"
#include "ifapp.h"
#include <qpainter.h>

KIFScrollTopLevel::KIFScrollTopLevel(KIFImage *image, QWidget *parent,
                                     const char *name)
    : QScrollView(parent, name)
{
    setFocusPolicy(StrongFocus);

    connect(kifapp(), SIGNAL(hideAllWindows()), this,
            SLOT(slotHideAll()));
    connect(kifapp(), SIGNAL(showAllWindows()), this,
            SLOT(slotShowAll()));

    imageBuffer = image;
    connect(imageBuffer, SIGNAL(updated()), this, SLOT(slotUpdateFromImage()));
    connect(imageBuffer, SIGNAL(invalidFile()), this, SLOT(slotInvalidFile()));
    // speed hack for pixmapped palettes
    QPalette pal(palette());
    QBrush brush(pal.active().base());
    pal.setBrush(QColorGroup::Base, brush);
    pal.setBrush(QColorGroup::Background, brush);
    setPalette(pal);
    viewport()->setBackgroundMode(NoBackground);
}

void KIFScrollTopLevel::slotUpdateFromImage()
{
    qWarning("In slotUpdateFromImage");
    pix.convertFromImage(*imageBuffer->image());
    resizeContents(pix.width(), pix.height());
    viewport()->repaint(false);
}

void KIFScrollTopLevel::slotInvalidFile()
{
    ;
}

void KIFScrollTopLevel::drawContents(QPainter *p, int x, int y, int w, int h)
{
    if(x+w > pix.width() || y+h > pix.height()){
        // we use NoBackground, so calculate bg rects to repaint

        QRect r(x, y, w, h);
        QRect pixRect(0, 0, pix.width(), pix.height());
        QRect drawRect = pixRect.intersect(r);
        if(pix.mask())
            p->fillRect(r, Qt::white);
        p->drawPixmap(r.topLeft(), pix, r);
        if(drawRect.right() < r.right()){
            p->fillRect(drawRect.right()+1, y, w-drawRect.width(), h,
                        Qt::darkGray);
        }
        if(drawRect.bottom() < r.bottom()){
            p->fillRect(x, drawRect.bottom()+1, w, h-drawRect.height(),
                        Qt::darkGray);

        }
    }
    else
        p->drawPixmap(x, y, pix, x, y, w, h);
}

void KIFScrollTopLevel::closeEvent(QCloseEvent *ev)
{
    pix.resize(0, 0);
    resizeContents(0, 0);
    ev->accept();
    emit finished();
}

void KIFScrollTopLevel::slotHideAll()
{
    visible = isVisible();
    if(visible)
        hide();
}

void KIFScrollTopLevel::slotShowAll()
{
    if(visible)
        show();
}

void KIFScrollTopLevel::keyPressEvent(QKeyEvent *ev)
{
    int key = ev->key();
    if(key == Key_Left)
        emit(prevList());
    else if(key == Key_Right || key == Key_Space)
        emit(nextList());
    else if(key == Key_Up)
        emit(prevImage());
    else if(key == Key_Down)
        emit(nextImage());
    else if(key == Key_Escape || key == Key_Enter || key == Key_Return)
        close();
}






#include "scrolltoplevel.moc"
