//$Id: colorlistbox.cpp,v 1.2 1997/12/01 05:49:48 parallax Exp $

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

ColorListBox::ColorListBox (QWidget *parent,  const char *name)
        : QListBox(parent, name)
{
    verticalScrollBar(); // so that the vert scroll bar gets setPalette() events
}

void ColorListBox::mousePressEvent(QMouseEvent *ev)
{
    if (ev->button() == RightButton)
    {
        if (count() != 0)
        {
            if (currentItem() == -1)
                setCurrentItem(0);
            emit Popup();
        }
    }
}

void ColorListBox::DrawBackground( QPainter *painter,int row )
{
    int x = 0;
    int y;
    if (!rowYPos(row, &y))
    {
        debug("row is not visible.");
        return;
    }
    int w = cellWidth();
    int h = cellHeight(row);
    
    if (bgPixmap.isNull())
    {
        painter->eraseRect( x, y, w, h );
        return;
    }
    
    QPixmap *buffer = new QPixmap(w, h);
    QPainter *p = new QPainter();
    p->begin(buffer);
    
    int pw = bgPixmap.width();
    int ph = bgPixmap.height();
    int ox = xOffset();
    int oy = yOffset();
    int xOrigin = x/pw*pw - ox%pw;
    int yOrigin = y/ph*ph - oy%ph;
    p->setClipRect(0,0,w, h);
    p->setClipping( TRUE);

    for ( int yp = yOrigin; yp < y + h; yp += ph )
    {
        for ( int xp = xOrigin; xp < x + w; xp += pw )
        {
            p->drawPixmap( xp, yp-y, bgPixmap );
        }
    }
    p->end();
    painter->drawPixmap(0,0, *buffer);
    delete buffer;
    delete p;
}

void ColorListBox::paintCell(QPainter *p, int row, int col)
{
    // first draw the background
    DrawBackground(p, row);
    QListBox::paintCell(p, row, col);

}

void ColorListBox::paintEvent(QPaintEvent *e)
{
    if (!bgPixmap.isNull())
    {
        QPainter p;
        p.begin(this);
        p.setClipRect(e->rect());
        QRect r = viewRect();
        int pw = bgPixmap.width();
        int ph = bgPixmap.height();
        for ( int yp = r.y(); yp < r.y() + r.height(); yp += ph )
        {
        for ( int xp = r.x(); xp < r.x() + r.width(); xp += pw )
        {
            p.drawPixmap( xp, yp, bgPixmap );
        }
        }
        p.end();
    }
        QListBox::paintEvent(e);
}
#include "colorlistbox.moc"
