/****************************************************************************
**
** Copyright (C) 2000-$THISYEAR$ $TROLLTECH$. All rights reserved.
**
** This file is part of the $MODULE$ of the Qtopia Toolkit.
**
** $TROLLTECH_DUAL_LICENSE$
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
****************************************************************************/

#define private public
#include "qscreen_qws.h"
#undef private

#include "brcm1103screen.h"
#include <QRect>
#include <QRegion>
#include <QWSServer>

#include <QDebug>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>


Brcm1103Screen::Brcm1103Screen(int displayId)
: QLinuxFbScreen(displayId)
{
    fbd = ::open( "/dev/fb0", O_RDWR );
    if ( fbd < 0 ) {
        qWarning() << "Brcm1103Screen: Cannot open frame buffer device /dev/fb0";
        return;
    }
}

Brcm1103Screen::~Brcm1103Screen()
{
}


extern bool alphaPaintingEnabled;


void Brcm1103Screen::blit(const QImage &inImg, const QPoint &topLeft, const QRegion &region)
{
    if ( alphaPaintingEnabled ) {
	QImage img = inImg.convertToFormat(QImage::Format_ARGB32);
	QImage dst = inImg.convertToFormat(QImage::Format_RGB16);
	for (int y = 0; y < dst.height(); y++) {
		for (int x = 0; x < dst.width(); x++) {
			uint pixel = img.pixel(x, y);
			if ( pixel == 0xFFFFFF00 )
		            dst.setPixel(x, y, 0xFF000008);
		}
	}
        QScreen::blit(dst, topLeft, region);
    } else {
        QScreen::blit(inImg, topLeft, region);
    }

/*
    const QRect bounds = region.boundingRect();
    dirtyRows.top = bounds.y();
    dirtyRows.bottom = dirtyRows.top + bounds.height()-1;
    if ( ::ioctl( fbd, LCDFB_IOCTL_UPDATE_LCD, &dirtyRows ) != 0 ) {
        qWarning() << "Brcm1103Screen::exposeRegion: LCDFB_IOCTL_UPDATE_LCD failed";
    }
*/
}

 
void Brcm1103Screen::exposeRegion(QRegion r, int changing)
{
    r &= region();
    if (r.isEmpty())
        return;
    if (changing && qwsServer->clientWindows().at(changing)->state() == QWSWindow::Lowering)
        changing = 0;
    const QRect bounds = r.boundingRect();
    QRegion blendRegion;
    QImage blendBuffer;
    compose(0, r, blendRegion, blendBuffer, changing);
    if (!blendBuffer.isNull())
        blit(blendBuffer, blendRegion.boundingRect().topLeft(), blendRegion);

    const QRect bnds = bounds;
    //const QRect bnds = blendRegion.boundingRect();
    dirtyRows.top = bnds.y();
    dirtyRows.bottom = dirtyRows.top + bnds.height()-1;
    if ( ::ioctl( fbd, LCDFB_IOCTL_UPDATE_LCD, &dirtyRows ) != 0 ) {
        qWarning() << "Brcm1103Screen::exposeRegion: LCDFB_IOCTL_UPDATE_LCD failed";
    }
}

