/**
Completes a pass of this render stage.
*/
void CTestRenderStage::End()
	{
	CFbsBitGc* gc =  iBackBuffer->GetBitGcCurrent();
	gc->SetPenSize(TSize(2,2));
	gc->SetPenColor(KRgbRed);
	gc->DrawLine(TPoint(50,0),TPoint(0,50));
	gc->SetPenColor(KRgbGreen);
	gc->DrawLine(TPoint(60,0),TPoint(0,60));
	
	if (Next())
		{
		gc = Next()->Begin();
		const TRegion* region = iScreenRedraw->AnimationRegion();
		if(region && !region->IsEmpty() && !region->CheckError())
			{
			if (iBackBuffer->Observer())
				iBackBuffer->Observer()->BeforeUpdate(*iBackBuffer,*region);
			
			gc->SetDrawMode(CGraphicsContext::EDrawModeWriteAlpha);
			gc->SetClippingRegion(region);
			gc->BitBlt(-iScreenConfig->ScaledOrigin(),iBackBuffer->GetBitmap());
			gc->SetDrawMode(CGraphicsContext::EDrawModePEN);
			gc->CancelClipping();
			
			if (iBackBuffer->Observer())
				iBackBuffer->Observer()->AfterUpdate(*iBackBuffer,*region);
			}
		Next()->End();
		}
	}
/**
Copy a bitmap into another bitmap (generally in a different displaymode)
tiles destination bitmap with source
*/
void CTe_graphicsperformanceSuiteStepBase::CopyBitmapL(CFbsBitmap* aDst, CFbsBitmap* aSrc)
	{
	TSize srcSize = aSrc->SizeInPixels();
	TSize dstSize = aDst->SizeInPixels();
	CFbsBitmapDevice* dev = CFbsBitmapDevice::NewL(aDst);
	CleanupStack::PushL(dev);
	CFbsBitGc* gc = NULL;
	if ( 0 == dev->CreateContext(gc) )
		{
		CleanupStack::PushL(gc);
		TPoint point;
		gc->SetBrushColor(TRANSPARENT_BLACK);
		gc->SetBrushStyle(CGraphicsContext::ENullBrush);
		gc->SetDrawMode(CGraphicsContext::EDrawModeWriteAlpha);
		gc->Clear();
		gc->SetDrawMode(CGraphicsContext::EDrawModePEN);
		for(point.iY=0; point.iY<dstSize.iHeight; point.iY+=srcSize.iHeight)
			{
			for(point.iX=0; point.iX<dstSize.iWidth; point.iX+=srcSize.iWidth)
				{
				gc->BitBlt(point, aSrc);
				}
			}
		CleanupStack::PopAndDestroy(gc);
		}
	CleanupStack::PopAndDestroy(dev);
	}
/**
Bitblt test

@param aSrcMode is the source display mode
@param aDstMode is the destination display mode
@param aSession is the windows server session
@param aWindow is a reference to the window
@param aGc is the graphics context of the window
@param aNumIterations is the number of iterations to run the test
*/		
void CAlphaBlendTest::DoBitBltAlphaBitmapTestL(TDisplayMode aSrcMode,TDisplayMode aDstMode, RWsSession& aSession, RWindow& aWindow, CWindowGc* aGc, TInt aNumIterations)
	{	
	const TSize bitmapSize = aWindow.Size();
	
	CFbsBitmap* bitmapTarget = CreateSoftwareBitmapLC(bitmapSize, aDstMode);
	CFbsBitmapDevice* bitmapDevice = CFbsBitmapDevice::NewL(bitmapTarget);
	CleanupStack::PushL(bitmapDevice);
	CFbsBitGc* bitmapGc = NULL;	
	User::LeaveIfError(bitmapDevice->CreateContext(bitmapGc));	
	CleanupStack::PushL(bitmapGc);
	
	CFbsBitmap* source = CreateSoftwareBitmapLC(bitmapSize, aSrcMode);
	CFbsBitmap* sourceAlpha = CreateSoftwareBitmapLC(bitmapSize, EGray256);	// match size to src
	VerticalGradientAlphaL(sourceAlpha, TRgb(0x01010101), TRgb(0xfefefefe));
	VerticalGradientAlphaL(source, TRgb(0x00000000), TRgb(0xffffffff));

	TPoint point(0,0);
	
	bitmapGc->SetBrushStyle(CGraphicsContext::ENullBrush);
	bitmapGc->SetBrushColor(TRANSPARENT_BLACK);

	bitmapGc->SetDrawMode(CGraphicsContext::EDrawModeWriteAlpha);
	bitmapGc->Clear();
	bitmapGc->SetDrawMode(CGraphicsContext::EDrawModePEN);
	bitmapGc->BitBlt(point, source);

	aGc->Activate(aWindow);
	aGc->BitBlt(point, bitmapTarget);
	aGc->Deactivate();
	aSession.Flush();

	iProfiler->InitResults();		
	for(TInt i=0; i<aNumIterations; i++)
	{
		bitmapGc->SetDrawMode(CGraphicsContext::EDrawModeWriteAlpha);
		bitmapGc->Clear();
		bitmapGc->SetDrawMode(CGraphicsContext::EDrawModePEN);
		bitmapGc->BitBlt(point, source);
		iProfiler->MarkResultSetL();
	}
	
	iProfiler->ResultsAnalysis(_L("DoBitBltAlphaBitmapTestL"), 0, aSrcMode, aDstMode, aNumIterations);
	
	// copy up to screen for sanity check
	aGc->Activate(aWindow);
	aGc->BitBlt(TPoint(), bitmapTarget);
	aGc->Deactivate();
	CleanupStack::PopAndDestroy(5, bitmapTarget); //sourceAlpha, source, bitmapGc, bitmapDevice, bitmapTarget
	}
/**
Draws a stretched bitmap with or without a mask.

@param aUseMask set to ETrue to use a alpha mask. Normally used for 16MU display modes that do not store the alpha.
@param aSrcMode is the source display mode
@param aDstMode is the destination display mode
@param aSession is the windows server session
@param aWindow is a reference to the window
@param aGc is the graphics context of the window
@param aNumIterations is the number of iterations to run the test
*/
void CAlphaBlendTest::DoDrawBitmapL(TBool aUseMask, TDisplayMode aSrcMode, TDisplayMode aDstMode, RWsSession& aSession, RWindow& aWindow, CWindowGc* aGc, TInt aNumIterations)
	{		
	const TSize bitmapSize = aWindow.Size();
	
	// Construct target bitmap.
	CFbsBitmap* bitmapTarget = CreateSoftwareBitmapLC(bitmapSize, aDstMode);
	CFbsBitmapDevice* bitmapDevice = CFbsBitmapDevice::NewL(bitmapTarget);
	CleanupStack::PushL(bitmapDevice);
	
	// Construct GC.
	CFbsBitGc* bitmapGc = NULL;
	User::LeaveIfError(bitmapDevice->CreateContext(bitmapGc));
	CleanupStack::PushL(bitmapGc);
	
	// Construct source bitmap.	
	TSize smallerSize(bitmapSize.iWidth/2,  bitmapSize.iHeight/2);
	CFbsBitmap* source = CreateSoftwareBitmapLC(smallerSize, aSrcMode);
	VerticalGradientAlphaL(source, TRgb(0x00000000), TRgb(0xffffffff));	
	CFbsBitmap* sourceAlpha = CreateSoftwareBitmapLC(smallerSize, EGray256);	// match size to src
	VerticalGradientAlphaL(sourceAlpha, TRgb(0x01010101), TRgb(0xfefefefe));
		
	bitmapGc->SetBrushStyle(CGraphicsContext::ENullBrush);
	bitmapGc->SetBrushColor(TRANSPARENT_BLACK);
	bitmapGc->Clear();
	bitmapGc->SetDrawMode(CGraphicsContext::EDrawModePEN);
	aGc->Activate(aWindow);
	TPoint point(0,0);
	bitmapGc->BitBlt(point, bitmapTarget);
	aGc->Deactivate();
	aSession.Flush();

	TBuf <20> testName;
	if (!aUseMask)
		{
		testName=_L("DrawBitmap");
		iProfiler->InitResults();
		for(int i=0; i<aNumIterations; i++)
			{
			bitmapGc->DrawBitmap(TRect(point, bitmapSize), source);
			iProfiler->MarkResultSetL();
			}
		}
	else
		{
		testName=_L("DrawBitmapMasked");
		iProfiler->InitResults();
		for(int i=0; i<aNumIterations; i++)
			{
			bitmapGc->DrawBitmapMasked(TRect(point, bitmapSize), source,TRect(point, smallerSize), sourceAlpha, EFalse);
			iProfiler->MarkResultSetL();
			}
		}
	INFO_PRINTF4(_L("%S(Stretched) with src = %S, dst = %S"), &testName, &ColorModeName(aSrcMode), &ColorModeName(aDstMode));
	iProfiler->ResultsAnalysis(testName, 0, aSrcMode, aDstMode, aNumIterations);
	// copy up to screen for sanity check
	BitBlt(aSession, aWindow, aGc, *bitmapTarget);
	CleanupStack::PopAndDestroy(5, bitmapTarget);
	}
// ============================================================================
// CIconConverter::DoProcessMaskL()
// process the bitmap mask
//
// @since 3.1
// ============================================================================
void CIconConverter::DoProcessMaskL()
    {
    // we use white to mean transparent at this stage, simply for efficiency
    // since all the canvases we will copy in to begin as white

    if ( iOriginalBitmapMask->Handle() == 0 )
        {
        // Create a mask that shows the whole bitmap as an icon
        // (all black)
        User::LeaveIfError( iOriginalBitmapMask->Create(
            iOriginalBitmap->SizeInPixels(), EGray2 ) );
        CFbsBitmapDevice* device =
            CFbsBitmapDevice::NewL( iOriginalBitmapMask );
        CleanupStack::PushL( device );

        CFbsBitGc* gc;
        User::LeaveIfError( device->CreateContext( gc ) );
        gc->SetBrushStyle( CGraphicsContext::ESolidBrush );
        gc->SetDrawMode( CGraphicsContext::EDrawModePEN );
        gc->SetBrushColor( KRgbBlack );
        // Create a big black image
        gc->Clear();
        delete gc;
        CleanupStack::PopAndDestroy( device );
        }
    else
        {
        // Invert the mask obtained from the PNG
        CFbsBitmapDevice* device =
            CFbsBitmapDevice::NewL( iOriginalBitmapMask );
        CleanupStack::PushL(device);
        CFbsBitGc* gc;
        User::LeaveIfError( device->CreateContext( gc ) );
        gc->SetDrawMode( CGraphicsContext::EDrawModeNOTSCREEN );
        gc->Clear();
        delete gc;
        CleanupStack::PopAndDestroy( device );
        }

    // Scale the icon to the sizes required
    iCurrentSizeIndex = 0;
    DoIconScalingL();
    }
/**
Auxilary function called to Copy the screen to bitmap (mbm) file.
@param aHashIndex contains hashID. Bitmap is created with the aHashIndex as name
*/
EXPORT_C void CTHashReferenceImages::CopyScreenToBitmapL(const TDesC& aHashIndex)
	{
	CFbsBitmap *bitmap = new(ELeave)CFbsBitmap();
	CleanupStack::PushL(bitmap);
	User::LeaveIfError(bitmap->Create(iBitmapDevice->SizeInPixels(), iBitmapDevice->DisplayMode()));
	TRect rect = TRect(iBitmapDevice->SizeInPixels());
	CFbsBitmapDevice *device=CFbsBitmapDevice::NewL(bitmap);
	CleanupStack::PushL(device);
	CFbsBitGc *gc;
	User::LeaveIfError(device->CreateContext(gc));
	gc->SetDrawMode(CGraphicsContext::EDrawModeWriteAlpha);
	gc->BitBlt(TPoint(), iBitmap, rect);
	TFileName mbmFile;
	mbmFile.Format(iPath->Des(), &aHashIndex);
	bitmap->Save(mbmFile);
	delete gc;
	CleanupStack::PopAndDestroy(2);
	}
// ============================================================================
// CIconConverter::DoIconStoreL()
// Store icon and mask files
//
// @since 3.1
// ============================================================================
void CIconConverter::DoIconStoreL()
    {
    // Store the icon and its mask in temporary files until we are ready
    // to create the final icon

    // Icon is stored at index n, mask at index n+1
    TInt iconIndex = iCurrentSizeIndex * 2;
    TFileName iconFile = *iTempPath;
    GetTempIconName( iconIndex++, iconFile );

    TFileName maskFile = *iTempPath;
    GetTempIconName( iconIndex, maskFile );

    // invert the masks before saving

    CFbsBitmapDevice* device = CFbsBitmapDevice::NewL( iTempBitmapMask );
    CleanupStack::PushL( device );

    CFbsBitGc* gc;
    User::LeaveIfError( device->CreateContext( gc ) );
    gc->SetDrawMode( CGraphicsContext::EDrawModeNOTSCREEN );
    gc->Clear();

    delete gc;
    CleanupStack::PopAndDestroy( device );

    // save the bitmaps
    User::LeaveIfError( iTempBitmap->Save( iconFile ) );
    User::LeaveIfError( iTempBitmapMask->Save( maskFile ) );

    if ( ++iCurrentSizeIndex < iIconSizes->Count() )
        {
        // do the next icon size
        DoIconScalingL();
        }
    else
        {
        DoCreateFinalIconL();
        }

    }
// ---------------------------------------------------------------------------
// CMMACameraWindow::DrawViewFinderError()
// Draws the error message to specified area.
// Used in cases when viewfinder is unable to start.
// ---------------------------------------------------------------------------
//
void CMMACameraWindow::DrawViewFinderErrorL(
    const TInt /*aError*/,
    const TRect& aDrawRect)
{

    ASSERT(iDirectAccess);
    TInt dcError = KErrNone;
    if (!iDirectAccess->IsActive())
    {
        TRAP(dcError, iDirectAccess->StartL());
    }

    TRect drawRect(aDrawRect);

    if (dcError == KErrNone)
    {
        drawRect.Intersection(iClientRect);
        drawRect.Move(-iWindow->AbsPosition());

        CFbsBitGc* directGc = iDirectAccess->Gc();
        directGc->SetClippingRect(drawRect);
        directGc->SetBrushColor(TRgb(128,128,128));
        directGc->SetPenColor(TRgb(128,0,0));
        directGc->SetBrushStyle(CGraphicsContext::ESolidBrush);
        directGc->SetPenStyle(CGraphicsContext::ESolidPen);
        directGc->SetDrawMode(CGraphicsContext::EDrawModeWriteAlpha);
        directGc->DrawRect(drawRect);

        if (!iErrorIconBitmap || !iErrorIconMaskBitmap)
        {
            if (iErrorIconBitmap)
            {
                delete iErrorIconBitmap;
                iErrorIconBitmap = NULL;
            }

            if (iErrorIconMaskBitmap)
            {
                delete iErrorIconMaskBitmap;
                iErrorIconMaskBitmap = NULL;
            }
            /*
                        AknsUtils::CreateIconL(
                            AknsUtils::SkinInstance(),
                            KAknsIIDQgnIndiCam4Camera,
                            iErrorIconBitmap,
                            iErrorIconMaskBitmap,
                            KCameraAppBitmapFile,
                            EMbmCameraappQgn_indi_cam4_camera,
                            EMbmCameraappQgn_indi_cam4_camera_mask
                        );
                        */
        }

        //TRect iconRect
        drawRect.iTl.iX += KErrorIconMargin;
        drawRect.iTl.iY += KErrorIconMargin;
        drawRect.iBr.iX -= KErrorIconMargin;
        drawRect.iBr.iY -= KErrorIconMargin;

        if (iErrorIconBitmap->SizeInPixels() != drawRect.Size())
        {
            AknIconUtils::SetSize(iErrorIconBitmap, drawRect.Size());
            AknIconUtils::SetSize(iErrorIconMaskBitmap, drawRect.Size());
        }

        directGc->BitBltMasked(
            drawRect.iTl, iErrorIconBitmap,
            TRect(iErrorIconBitmap->SizeInPixels()),
            iErrorIconMaskBitmap, EFalse);

        iDirectAccess->ScreenDevice()->Update();
    }

}
TBool CHuiRasterizedTextMesh::RasterizePictographLineL(const TDesC& aTextLine, CFont* aFont, SRasterizedLine & aLineOut)
    {
    if(iUsingPreRasterizedMesh)
        {
        return EFalse;
        }

    // Retrieve the used text style.
    THuiTextStyle* textStyle = CHuiStatic::Env().TextStyleManager().TextStyle(iTextStyleId);
    
    // Calculate line extents and assign it to texture size.
    TSize textureSize = textStyle->LineExtentsL(aTextLine);
	    
    if(textureSize.iWidth == 0 || !iPictographInterface || !iPictographInterface->Interface()->ContainsPictographs(aTextLine))
        {
        // This is an empty string or it does not contain pictographs. We will not rasterize it.
        // Just add a gap.
        aLineOut.iTexture = NULL;
        aLineOut.iGap = textureSize.iHeight;
        return !IsMaxLineCountReached(); 
        }

    // store the actual size to be assigned as the textures logical size
    TSize actualsize(textureSize);

    if (aLineOut.iTexture == NULL)
        {
    // Create a texture for storing the pictographs into.
        aLineOut.iTexture = CHuiTexture::NewL();
        HUI_DEBUG1(_L("CHuiRasterizedTextMesh::RasterizePictographLineL() - Registering self (0x%x) as a texture content observer."), this);        
        // Register one content observer for the first texture that
        // is able to restore all lines in a single run
        if (iLines.Count()==1)
            {
            aLineOut.iTexture->iContentObservers.AppendL(*this);
            }
        aLineOut.iGap = 0;
        }

    // set a name for the texture
    // @todo is this needed, what names to use
    aLineOut.iTexture->SetImageFileNameL(_L("Pictographs"));

    TSize maxTextureSize = aLineOut.iTexture->MaxTextureSize();
    textureSize.iWidth = Min(textureSize.iWidth, maxTextureSize.iWidth);
    textureSize.iHeight = Min(textureSize.iHeight, maxTextureSize.iHeight);

    if((textureSize.iWidth == 0) || (textureSize.iHeight == 0))
        {
        // Cannot draw into this tiny texture, so leave.
        HUI_DEBUG2(_L("CHuiRasterizedTextMesh::RasterizePictographLineL() - texture size was too small to draw into (%i, %i)."), textureSize.iWidth, textureSize.iHeight);
        User::Leave(KErrAbort);
        }

    User::LeaveIfError( iPictographBitmap->Resize(textureSize) );

    CFbsBitmapDevice* device = CFbsBitmapDevice::NewL(iPictographBitmap);
    CleanupStack::PushL(device);

    CFbsBitGc* gc = 0;
    User::LeaveIfError( device->CreateContext(gc) );
    CleanupStack::PushL(gc);

    // Prepare the bitmap for drawing...set drawmode because of EColor16MA mode...
    gc->SetDrawMode(CGraphicsContext::EDrawModeWriteAlpha); 

    TRgb color = KRgbWhite;
    color.SetAlpha(0x00);
    gc->SetBrushColor(color);
    gc->Clear();
    gc->UseFont(aFont);  
    
	// Draw pictorgraphs
    iPictographInterface->Interface()->DrawPictographsInText(
            *gc,
            *aFont,
            aTextLine, TPoint(0, aFont->FontMaxAscent()));

    CleanupStack::PopAndDestroy(gc);
    CleanupStack::PopAndDestroy(device);

    aLineOut.iTexture->UploadL(*iPictographBitmap, NULL, EHuiTextureUploadFlagRetainResolution);
    aLineOut.iTexture->SetSize(actualsize);
    return !IsMaxLineCountReached();
    }