/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: minisymbiansurf.cpp,v 1.21.2.4 2005/02/11 17:01:44 gwright Exp $
 * 
 * Portions Copyright (c) 1995-2004 RealNetworks, Inc. All Rights Reserved.
 * 
 * The contents of this file, and the files included with this file,
 * are subject to the current version of the RealNetworks Public
 * Source License (the "RPSL") available at
 * http://www.helixcommunity.org/content/rpsl unless you have licensed
 * the file under the current version of the RealNetworks Community
 * Source License (the "RCSL") available at
 * http://www.helixcommunity.org/content/rcsl, in which case the RCSL
 * will apply. You may also obtain the license terms directly from
 * RealNetworks.  You may not use this file except in compliance with
 * the RPSL or, if you have a valid RCSL with RealNetworks applicable
 * to this file, the RCSL.  Please see the applicable RPSL or RCSL for
 * the rights, obligations and limitations governing use of the
 * contents of the file.
 * 
 * Alternatively, the contents of this file may be used under the
 * terms of the GNU General Public License Version 2 or later (the
 * "GPL") in which case the provisions of the GPL are applicable
 * instead of those above. If you wish to allow use of your version of
 * this file only under the terms of the GPL, and not to allow others
 * to use your version of this file under the terms of either the RPSL
 * or RCSL, indicate your decision by deleting the provisions above
 * and replace them with the notice and other provisions required by
 * the GPL. If you do not delete the provisions above, a recipient may
 * use your version of this file under the terms of any one of the
 * RPSL, the RCSL or the GPL.
 * 
 * This file is part of the Helix DNA Technology. RealNetworks is the
 * developer of the Original Code and owns the copyrights in the
 * portions it created.
 * 
 * This file, and the files included with this file, is distributed
 * and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
 * KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
 * ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
 * ENJOYMENT OR NON-INFRINGEMENT.
 * 
 * Technology Compatibility Kit Test Suite(s) Location:
 *    http://www.helixcommunity.org/content/tck
 * 
 * Contributor(s):
 * 
 * ***** END LICENSE BLOCK ***** */

#include "minisite.h"
#include "hxvsurf.h"
#include "coloracc.h"
#include "hxtick.h"
#include "hxprefs.h"
#include "hxprefutil.h"

#include "minisurf.h"
#include "minisymbiansurf.h"
#include "minisymbiansite.h"
#include "minifmt.h"
#include "nostatic/colorlib.h"

#include <e32std.h>  //for User::InfoPrint()
#include <eikenv.h> 
#include <eikdef.h> 
#include <gdi.h> 
#include <fbs.h> 

CMiniSymbianSurface::CMiniSymbianSurface(IUnknown* pContext, CMiniBaseSite* pSite)
    :  CMiniBaseSurface(pContext, pSite),
       m_nCompositionPitch(0),
       m_pGC(NULL),
       m_pBitMap(NULL),
       m_pLandscapeBitMap(NULL),
       m_DisplayMode(EColor4K),
       m_pBS(NULL),
       m_ulLastResetTime(0),
       m_bAutoRotate(FALSE)
{
    memset(&m_surfaceSize, 0, sizeof(m_surfaceSize) );
    memset(&m_ColorData, 0, sizeof(m_ColorData) );

}

CMiniSymbianSurface::~CMiniSymbianSurface()
{
    m_nCompositionPitch = 0;
    memset(&m_surfaceSize, 0, sizeof( m_surfaceSize ) );
    HX_DELETE(m_pBitMap);
    HX_DELETE(m_pLandscapeBitMap);
    if( m_pBS )
        m_pBS->Disconnect();
    HX_DELETE(m_pBS); 
}

color_data_t* CMiniSymbianSurface::GetColorData()
{
    return &m_ColorData;
}


HX_RESULT CMiniSymbianSurface::_CreateDestBuffer( int cidIn,
                                                  int nWidth,
                                                  int nHeight,
                                                  int& nCount)
{
    
    HX_ASSERT( m_pSite );

    m_surfaceSize.cx = nWidth;
    m_surfaceSize.cy = nHeight;

    //Get our GC, and Region.
    m_DisplayMode = EColor4K; //hardcoded for emulator right now.

    HX_RESULT retVal = HXR_OK;
    if( m_pImageHelper )
    {
        HXBitmapInfo bmiTemp;
        m_pImageHelper->MakeBitmap( &bmiTemp,
                                    sizeof(bmiTemp),
                                    CID_RGB444,
                                    m_surfaceSize.cx,
                                    m_surfaceSize.cy,
                                    NULL,
                                    0);

        m_nCompositionPitch = m_pImageHelper->GetBitmapPitch(&bmiTemp); 
        HX_ASSERT( m_pImageHelper->GetBitmapColor(&bmiTemp) == CID_RGB444 ); 
    }
    else
    {
        retVal = HXR_OUTOFMEMORY;
    }

    //Create our bitmap.
    if( !m_pBS )
    {
        m_pBS = new RFbsSession();
        if(!m_pBS)
        {
            retVal = HXR_OUTOFMEMORY;
        }
        else
        {
            m_pBS->Connect();
        }
    }

    IHXPreferences* pPreferences = NULL;
    if (HXR_OK == m_pContext->QueryInterface(IID_IHXPreferences, (void**)&pPreferences))
    {
        ReadPrefBOOL(pPreferences, "AutoRotate",  m_bAutoRotate);
        HX_RELEASE(pPreferences);
    }

    HX_ASSERT(m_pBS);
    if( retVal == HXR_OK )
    {
        HX_ASSERT(!m_pBitMap);
        HX_DELETE(m_pBitMap);
        HX_DELETE(m_pLandscapeBitMap);
        
        m_pBitMap = new CFbsBitmap();
        HX_ASSERT(m_pBitMap);

        if( m_bAutoRotate )
        {
            m_pLandscapeBitMap = new CFbsBitmap();
            HX_ASSERT(m_pLandscapeBitMap);
        }
        
        if(!m_pBitMap || (m_bAutoRotate && !m_pLandscapeBitMap))
        {
            retVal = HXR_OUTOFMEMORY;
        }
        else
        {
            TInt err = m_pBitMap->Create(TSize(m_surfaceSize.cx,m_surfaceSize.cy), m_DisplayMode);
            HX_ASSERT( err == KErrNone );
            if( err != KErrNone )
            {
                retVal = HXR_OUTOFMEMORY;
            }
            else
            {
                if( m_bAutoRotate )
                {
                    err = m_pLandscapeBitMap->Create(
                        TSize(m_surfaceSize.cy,m_surfaceSize.cx), m_DisplayMode);
                    HX_ASSERT( err == KErrNone );
                    if( err != KErrNone )
                    {
                        retVal = HXR_OUTOFMEMORY;
                    }
                }
            }
        }
    }

    HX_ASSERT(retVal==HXR_OK);
    if( FAILED(retVal) )
    {
        if( m_pBS )
        {
            m_pBS->Disconnect();
        }
        HX_DELETE(m_pBS);
        HX_DELETE(m_pBitMap);
        HX_DELETE(m_pLandscapeBitMap);
    }

    return retVal;
}

HX_RESULT CMiniSymbianSurface::_LockDestBuffer( UCHAR** ppDestPtr,
                                                LONG32* pnDestPitch,
                                                int& cid,
                                                REF(HXxSize) srcSize,
                                                int nIndex)
{
    HX_RESULT res = HXR_OK;

    HX_ASSERT(m_pBitMap != 0);
    *ppDestPtr   = (UCHAR*)m_pBitMap->DataAddress();
    *pnDestPitch = m_nCompositionPitch;
    cid          = CID_RGB444;

    return res;
}

         
HX_RESULT CMiniSymbianSurface::_TransferToDestBuffer( UCHAR*   pSrcBuffer,
                                                      HXBitmapInfoHeader* pBitmapInfo,
                                                      HXxRect* prSrcRect,
                                                      HXxRect* prDstRect,
                                                      UCHAR*   pDstBuffer,
                                                      LONG32   nDstPitch)
{
    HX_RESULT res = HXR_OK;

    res =  CMiniBaseSurface::_TransferToDestBuffer( pSrcBuffer,
                                                    pBitmapInfo,
                                                    prSrcRect,
                                                    prDstRect,
                                                    pDstBuffer,
                                                    nDstPitch);
    HX_ASSERT(res == HXR_OK);
    
    return res;
}

         
HX_RESULT CMiniSymbianSurface::_UnlockDestBuffer(UCHAR* pSurfPtr, int nIndex)
{
    //Nothing to do here for symbian.....
    return HXR_OK;
}

         
HX_RESULT CMiniSymbianSurface::_RenderDestBuffer( HXxRect* prSrcRect,
                                                  HXxRect* prDestRect,
                                                  int nIndex)
{
    HXxWindow*  pHXWin  = m_pSite->GetWindow();
    HX_RESULT   res     = HXR_OK;
    HXxPoint    point;
    RRegion*    clipReg = NULL;
    CDirectScreenAccess* pDirectScreen = pHXWin->iDSA;
    RWindow*    pWin    = (RWindow*)pHXWin->window;
    CFbsBitmap* pBitMap = m_pBitMap;

#if defined(HELIX_FEATURE_SMIL_SITE)
    TPoint     topleft = pWin->Position();
#endif

    HX_ASSERT(m_pSite);

#if defined(HELIX_FEATURE_SMIL_SITE)    
    point = *(m_pSite->GetOrigin());
#else
    m_pSite->GetPosition(point);
#endif    
    
    CFbsScreenDevice*& pSD = pDirectScreen->ScreenDevice();
    if( pSD )
    {
        m_pGC     = pDirectScreen->Gc();
        clipReg   = pDirectScreen->DrawingRegion();
        if( clipReg )
        {
            
#if defined(HELIX_FEATURE_SMIL_SITE)
            //Generate a TRegion from our site's region and only blt to the
            //intersection of the two.
            RRegion trTmp;
            HXREGION* reg = m_pSite->GetRegion();
            if( !HXEmptyRegion(reg))
            {
                //Add each rectangle...
                for(int i =0; i< reg->numRects; i++)
                {
                    TRect rect( reg->rects[i].x1+topleft.iX,
                                reg->rects[i].y1+topleft.iY,
                                reg->rects[i].x2+topleft.iX,
                                reg->rects[i].y2+topleft.iY
                                );
                    trTmp.AddRect(rect);
                }
                trTmp.Intersect(*clipReg);
            }
            clipReg = &trTmp;
#endif    

            if( m_bAutoRotate )
            {
                TSize windowSize = pWin->Size();

                //compute aspect ratio of our display window for both
                //landscape and portrait modes.
                int portraitAR  = windowSize.iWidth/windowSize.iHeight;
                int landscapeAR = windowSize.iHeight/windowSize.iWidth;

                //Now compute our current bitmap size.
                int bitmapAR    = m_surfaceSize.cx/m_surfaceSize.cy;

                if( 1<=bitmapAR && 1<=landscapeAR )
                {
//XXXgfw Keep this code in place until we find out the new
//       way doesn't take more CPU.                    
//                     //Rotate our bitmap into landscape mode.
//                     TBuf8<1024> aBuf;
//                     for(int i=0 ; i<m_surfaceSize.cx ; i++ )
//                     {
//                         m_pBitMap->GetVerticalScanLine( aBuf, i, m_DisplayMode );
//                         m_pLandscapeBitMap->SetScanLine( aBuf, m_surfaceSize.cx-i-1 );
//                     }
                    TBitmapUtil bitmapUtil(m_pBitMap);
                    TBitmapUtil landscapeUtil(m_pLandscapeBitMap);
                    TInt        nX = 0;
                    TInt        nY = 0;

                    bitmapUtil.Begin(TPoint(0,m_surfaceSize.cy)); 
                    landscapeUtil.Begin(TPoint(0,0),bitmapUtil); 

                    for (nY=0 ; nY<m_surfaceSize.cy ; nY++)
                    {
                        bitmapUtil.SetPos( TPoint(0,m_surfaceSize.cy-nY-1) );
                        landscapeUtil.SetPos( TPoint(nY,0) );
                        for (nX=0; nX<m_surfaceSize.cx ; nX++) 
                        {
                            landscapeUtil.SetPixel( bitmapUtil );
                            bitmapUtil.IncXPos();
                            landscapeUtil.IncYPos();
                        }
                    }

                    bitmapUtil.End();
                    landscapeUtil.End();

                    //Assign this bitmap to be blt'ed
                    pBitMap = m_pLandscapeBitMap;

                    //Do some quick centering of the image.
                    point.y = (windowSize.iHeight-m_surfaceSize.cx)/2;
                    point.x = (windowSize.iWidth-m_surfaceSize.cy)/2;
                
                }
            }
            
            m_pGC->SetClippingRegion(clipReg); 
            m_pGC->BitBlt(TPoint(point.x, point.y), pBitMap );

            //Force an update. This is required for WINS but it may
            //not be needed on all hardware. It *is* needed for Nokia
            //3650.
            pSD->Update();

#if defined(HELIX_FEATURE_SMIL_SITE)
            trTmp.Close();
#endif            
        }
    }
    
    return res;
}


void CMiniSymbianSurface::_KeepScreenAlive()
{
    ULONG32 ulNow = HX_GET_TICKCOUNT();

    //While we are BLT'ing video frames make sure the screen doesn't
    //dim on us. Do this every 10 seconds for now.
    //XXXGfw need to query the timeout and base the calls on that #.
    if( ulNow-m_ulLastResetTime > 10*1000)
    {
        User::ResetInactivityTime();
        m_ulLastResetTime = ulNow;
    }
}

HX_RESULT CMiniSymbianSurface::_DestroyDestBuffer(int cid, int nCount)
{
    HX_DELETE(m_pBitMap);
    m_nCompositionPitch   = 0;
    return HXR_OK;
}

int CMiniSymbianSurface::GetDstCID(int nIndex)
{
    //XXXgfw need more intelligent detection of screen depth.
    return CID_RGB444;
}


