/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: winsurf.cpp,v 1.3.34.2 2004/07/26 10:28:31 pankajgupta 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 "hxtypes.h"
#include <math.h>
#include "ddraw.h"
#include "hxcom.h"
#include "hxwintyp.h"
#include "hxvsurf.h"
#include "hxslist.h"

#include "winsurf.h"
#include "winsite.h"
#include "colormap.h"
#include "hxprefs.h"
#include "hxtick.h"
#include "hxheap.h"
#include "hxevent.h"

// these are defined in basesurf.cpp and should probably be moved to a .h file
#define HX_OVER_KEYDEST    1
#define HX_OVER_HIDE       2
#define HX_OVER_SHOW       4
#define OVERLAY_NOT_VISIBLE 0

#ifdef _DEBUG
#undef HX_THIS_FILE
static const char HX_THIS_FILE[] = __FILE__;

#include "winthrd.h"
#endif


CWinSurface::CWinSurface(IUnknown* pContext, CHXBaseSite* pSite) :
    CBaseSurface(pContext,pSite)
 ,  m_nBitsPerPixel(0)
 ,  m_nHozRes(0)
 ,  m_nVertRes(0)
 ,  m_nLastBltMode(HX_NO_BLT)
{
    // initialize data so we don't have invalid ptrs floating around.
    memset(&m_surface,0,sizeof(m_surface));
}

CWinSurface::~CWinSurface()
{
}

void CWinSurface::_ReleaseSurface(CBaseRootSurface* pSurface)
{
    WINDRAW* pWindraw = ((CWinBaseRootSurface*)pSurface)->GetWinDraw();
    WinDraw2_ReleaseSurface(pWindraw, &m_surface);

    m_nLastBltMode = HX_NO_BLT;
}

void CWinSurface::_ReleaseSurface(CWinBaseRootSurface* pSurface)
{
    WINDRAW* pWindraw = pSurface->GetWinDraw();
    WinDraw2_ReleaseSurface(pWindraw, &m_surface);

    m_nLastBltMode = HX_NO_BLT;
}

void CWinSurface::_DrawBlack(void* pWindow)
{
}

void CWinSurface::_CreateBuffer()
{
    CWinBaseRootSurface* pSurface = (CWinBaseRootSurface*)m_pSite->GetRootSurface();
    pSurface->OpenWindraw();
    WINDRAW* pWindraw = pSurface->GetWinDraw();

    BMI bmi;
    memset(&bmi, 0, sizeof(BMI));
    WinDraw2_GetDisplayFormat(pWindraw, &bmi);
    int cid = GetBitmapColor((LPBITMAPINFO)&bmi);

    memset(&bmi, 0, sizeof(BMI));
    MakeBitmap((LPBITMAPINFO)&bmi, sizeof(BMI), cid, m_pOptimizedFormat->biWidth, m_pOptimizedFormat->biHeight, NULL, NULL);
    memset(&m_surface, 0, sizeof(WINDRAWSURFACE));

    if (NOERROR == WinDraw2_CreateSurface(pWindraw, &m_surface, &bmi, pSurface->GetSurfaceType(), 0, 0))
    {
        m_surfaceSize.cx = m_pOptimizedFormat->biWidth;
        m_surfaceSize.cy = m_pOptimizedFormat->biHeight;
        m_nSurfaceCID = cid;
        m_nBltMode = HX_BLT_YUV_STRETCH;

        if (!m_nBitsPerPixel ||
            !m_nHozRes ||
            !m_nVertRes)
        {
            // Store the display mode we were created in.
            m_pSite->_GetDeviceCaps(NULL, m_nBitsPerPixel, m_nHozRes, m_nVertRes);
        }
    }
}

HX_RESULT CWinSurface::_GetCaps(UINT32 *pfSurfaceCaps)
{
    CWinBaseRootSurface* pSurface = (CWinBaseRootSurface*)m_pSite->GetRootSurface();
    pSurface->OpenWindraw();
    WINDRAW* pWindraw = pSurface->GetWinDraw();

    //    UINT32 fSurfaceCaps;
    UINT32 garbagea, garbageb;

    if (NOERROR != Windraw_GetCaps(pWindraw, pfSurfaceCaps, &garbagea, &garbageb))
    {
        return HXR_FAIL;
    }
    else
    {
        return HXR_OK;
    }
}

HX_RESULT CWinSurface::_CreateOverlay(BOOL bOverlay, int cid, int x, int y)
{
    //Get our windraw object from the root surface
    CWinBaseRootSurface* pSurface = (CWinBaseRootSurface*)m_pSite->GetRootSurface();

    HX_ASSERT( pSurface );
    if( !pSurface )
        return HXR_FAIL;

    pSurface->OpenWindraw();
    WINDRAW* pWindraw = pSurface->GetWinDraw();
    BMI bmi;
    memset(&bmi, 0, sizeof(BMI));
    MakeBitmap((LPBITMAPINFO)&bmi, sizeof(BMI), cid, x, y, NULL, NULL);
    memset(&m_surface, 0, sizeof(WINDRAWSURFACE));

    int fFlags = 0;

    if (bOverlay)
    {
        fFlags = WINDRAWSURFACE_DIRECTDRAW | WINDRAWSURFACE_OVERLAY | WINDRAWSURFACE_VIDEOMEMORY;
    }
    else
    {
        fFlags = WINDRAWSURFACE_DIRECTDRAW | WINDRAWSURFACE_DEFAULTMEMORY;
    }

    int numBuffers = (m_bFlipOverlay && bOverlay) ? m_nBackBufferCount+1 : 1;
    for (; numBuffers; numBuffers--)
    {
        if (NOERROR == WinDraw2_CreateSurface(pWindraw, &m_surface, &bmi, fFlags, numBuffers-1, 0))
        {
            m_nDDSurfaceSize = bmi.bmiHeader.biSizeImage;
            m_surfaceSize.cx = x;
            m_surfaceSize.cy = y;
            m_nSurfaceCID = cid;
            m_nBackBufferCount = numBuffers-1;

            if (bOverlay)
            {
                m_nBltMode = HX_OVERLAY_BLT;
            }
            else
            {
                m_nBltMode = HX_BLT_YUV_STRETCH;
            }
            UpdateDestRect();

            if (!m_nBitsPerPixel ||
                !m_nHozRes ||
                !m_nVertRes)
            {
                // Store the display mode we were created in.
                m_pSite->_GetDeviceCaps(NULL, m_nBitsPerPixel, m_nHozRes, m_nVertRes);
            }

            return HXR_OK;
        }
    }

    return HXR_FAIL;
}

HX_RESULT CWinSurface::_BltToPrimary(REF(HXxRect) rDestRect, REF(HXxRect) rSrcRect)
{
#ifdef _CHECK_PERFORMANCE
    static LARGE_INTEGER QueryPerformanceCounterResult = {0,0};
    static LARGE_INTEGER QueryPerformanceFrequencyResult = {0,0};

    QueryPerformanceFrequency(&QueryPerformanceFrequencyResult);

    double frequency = ((double)QueryPerformanceFrequencyResult.LowPart + 4294967296.0*QueryPerformanceFrequencyResult.HighPart);
    QueryPerformanceCounter(&QueryPerformanceCounterResult);

    double startTime = ((double)QueryPerformanceCounterResult.LowPart + 4294967296.0*QueryPerformanceCounterResult.HighPart)/frequency;
#endif

    if ((m_surfaceSize.cx==0  && m_surfaceSize.cy == 0)  || HX_BLT_YUV_STRETCH != m_nBltMode )
    {
        return HXR_FAIL;
    }

    CWinBaseRootSurface* pSurface = (CWinBaseRootSurface*)m_pSite->GetRootSurface();
    WINDRAW* pWindraw = pSurface->GetWinDraw();

    HX_RESULT retVal = HXR_FAIL;

    if (NOERROR == WinDrawSurface_Blt(pWindraw, &m_surface, (RECT*)&rDestRect, (RECT*)&rSrcRect))
    {
        retVal = HXR_OK;
    }

#ifdef _CHECK_PERFORMANCE
    QueryPerformanceCounter(&QueryPerformanceCounterResult);
    double endTime = ((double)QueryPerformanceCounterResult.LowPart + 4294967296.0*QueryPerformanceCounterResult.HighPart)/frequency;

    static UINT32 z_nNumTimes = 0;
    static double z_fTotalTime;
    static double z_fAverageTime;

    z_nNumTimes++;
    z_fTotalTime += endTime - startTime;
    z_fAverageTime = z_fTotalTime / (double) z_nNumTimes;

    if (! (z_nNumTimes % 25))
    {
        FILE* f1 = ::fopen("c:\\performance.txt", "a+"); /* Flawfinder: ignore */
        ::fprintf(f1, "WINDRAW2 - BltToPrimary: %d blts. Total CPU time: %f, CPU/Blt: %f -- Blt/s Second Max: %f\n", z_nNumTimes, z_fTotalTime, z_fAverageTime, 1.0/z_fAverageTime);
        fclose(f1);
    }
#endif
    return retVal;
}

HX_RESULT CWinSurface::_LockInternalSurface(UCHAR** ppSurfPtr, LONG* pnSurfPitch, REF(HXxSize) srcSize)
{
    HX_RESULT ret = HXR_OK;
    IDirectDrawSurface *pBackBuffer = NULL;

    CWinBaseRootSurface* pSurface = (CWinBaseRootSurface*)m_pSite->GetRootSurface();
    WINDRAW* pWindraw = pSurface->GetWinDraw();

    //See comments in _UnlockInternalSurface below.....
    if( m_bVideoSurface2 && m_surface.dd.lpDDBackBuffer )
    {
        pBackBuffer = m_surface.dd.lpDDBackBuffer;
        m_surface.dd.lpDDBackBuffer = NULL;
    }

    if (NOERROR == WinDrawSurface_Lock(pWindraw, &m_surface, 0, (void**) ppSurfPtr, pnSurfPitch))
        ret =  HXR_OK;
    else
        ret = HXR_FAIL;

    if (pBackBuffer)
        m_surface.dd.lpDDBackBuffer = pBackBuffer;

    return ret;
}

// Note that the pSurfPtr is not used... but other implementations will
// probbaly use it.
HX_RESULT CWinSurface::_UnlockInternalSurface(UCHAR* pSurfPtr)
{
    CWinBaseRootSurface* pSurface = (CWinBaseRootSurface*)m_pSite->GetRootSurface();
    WINDRAW* pWindraw = pSurface->GetWinDraw();

    if (m_pSite->HasFocusRect())
    {
        pSurface->DrawFocusRect(//&m_surface,
            m_nSurfaceCID,
            &m_surfaceSize,
            pSurfPtr,
            m_pSite);
    }


    IDirectDrawSurface *pBackBuffer = NULL;

    //This is a VS1 only call. If we are calling this and we are in
    //VS2 mode then it means we are sharing the overlay.
    //VS1 only uses the front buffer and so we need to hide the back
    //buffer from VS1 to keep the flip from happening.
    //PR70865, Fixes the 'shaking' bug.
    if( m_bVideoSurface2 && m_surface.dd.lpDDBackBuffer )
    {
        //XXXgfw This assumes that VS1 *NEVER* uses a flipping chain.
        pBackBuffer = m_surface.dd.lpDDBackBuffer;
        m_surface.dd.lpDDBackBuffer = NULL;
    }

    WinDrawSurface_Unlock(pWindraw, &m_surface, 0);

    if (pBackBuffer)
        m_surface.dd.lpDDBackBuffer = pBackBuffer;

    return HXR_OK;
}

void CWinSurface::_SetupDCObjects(HXxDC hxxDC, void** phOldBrush, void** phOldPen)
{
    HDC hdc = (HDC) hxxDC;

    LOGBRUSH brush;

    brush.lbStyle = BS_SOLID;
    brush.lbColor = GetOverlayColor();
    brush.lbHatch = 0;

    HBRUSH  hBrush      = (HBRUSH)CreateBrushIndirect(&brush);
    HPEN    hPen        = (HPEN)CreatePen(PS_SOLID, 1, GetOverlayColor());
    *phOldBrush         = (void*)SelectObject(hdc, hBrush);
    *phOldPen           = (void*)SelectObject(hdc, hPen);
}

void CWinSurface::_FillRectangle(HXxDC hxxDC, UINT32 left, UINT32 top, UINT32 right, UINT32 bottom)
{
    HDC hdc = (HDC)hxxDC;
    LOGBRUSH brush;

    brush.lbStyle = BS_SOLID;
//  Do NOT use _InsureColorMatch() here.  This color must be RGB(8,8,8) format and _InsureColorMatch()
//  will return a different format if display isn't in 24 or 32-bit mode.
    brush.lbColor = GetOverlayColor();
    brush.lbHatch = 0;

    HBRUSH  hBrush      = (HBRUSH)CreateBrushIndirect(&brush);
    HPEN    hPen        = (HPEN)CreatePen(PS_SOLID, 1, brush.lbColor);
    HBRUSH  hOldBrush   = (HBRUSH)SelectObject(hdc, hBrush);
    HPEN    hOldPen     = (HPEN)SelectObject(hdc, hPen);

    Rectangle(hdc, left, top, right, bottom);

    SelectObject(hdc, hOldBrush);
    SelectObject(hdc, hOldPen);
    DeleteObject(hBrush);
    DeleteObject(hPen);
}

void CWinSurface::_RestoreDCObjects(HXxDC hxxDC, void* hOldBrush, void* hOldPen)
{
    HBRUSH hBrush = (HBRUSH)SelectObject((HDC) hxxDC, (HBRUSH) hOldBrush);
    HPEN hPen = (HPEN)SelectObject((HDC) hxxDC, (HPEN) hOldPen);
    DeleteObject(hBrush);
    DeleteObject(hPen);
}

void CWinSurface::_GetCompositionSurfaceHXxDC(HXxDC *hdc)
{
    CWinBaseRootSurface* pSurface = (CWinBaseRootSurface*)m_pSite->GetRootSurface();
    WINDRAWSURFACE* pDrawSurface = pSurface->GetCompositionSurface();
    WINDRAW*    pWindraw = pSurface->GetWinDraw();

    WinDrawSurface_GetDC(pWindraw, pDrawSurface, (HDC*)hdc);
    // XXXAH Huh? Fix this up!
}

void CWinSurface::_ReleaseCompositionSurfaceHXxDC(HXxDC hdc)
{
    CWinBaseRootSurface* pSurface = (CWinBaseRootSurface*)m_pSite->GetRootSurface();

    WINDRAWSURFACE* pDrawSurface = pSurface->GetCompositionSurface();
    WINDRAW*    pWindraw = pSurface->GetWinDraw();

    WinDrawSurface_ReleaseDC(pWindraw, pDrawSurface, (HDC)hdc);

}

INT32 CWinSurface::_InsureColorMatch(INT32 InColor)
{
    CWinBaseRootSurface* pSurface = (CWinBaseRootSurface*)m_pSite->GetRootSurface();
    WINDRAW*    pWindraw = pSurface->GetWinDraw();
    return Windraw_ColorMatch(pWindraw, InColor);
}

void CWinSurface::_SetColorKey(INT32 nColorSpaceLowValue, INT32 nColorSpaceHighValue)
{
    CWinBaseRootSurface* pSurface = (CWinBaseRootSurface*)m_pSite->GetRootSurface();
    WINDRAW*    pWindraw = pSurface->GetWinDraw();
    HRESULT hr = WinDraw2_SetColorKey(pWindraw, m_convertedOverlayColor, m_convertedOverlayColor);
}

void CWinSurface::_UpdateOverlay(HXxRect* dest, HXxRect* src, INT32 inFlags)
{
    CWinBaseRootSurface* pSurface = (CWinBaseRootSurface*)m_pSite->GetRootSurface();
    WINDRAW*    pWindraw = pSurface->GetWinDraw();

    // convert flags.
    INT32 flags = 0;

    if (inFlags & HX_OVER_KEYDEST)
    {
        flags |= DDOVER_KEYDEST;
    }

    if (inFlags & HX_OVER_HIDE)
    {
        flags |= DDOVER_HIDE;
    }

    if (inFlags & HX_OVER_SHOW)
    {
        flags |= DDOVER_SHOW;
    }

    HRESULT hr = WinDraw2_UpdateOverlay(pWindraw, &m_surface, (RECT*)dest, (RECT*)src, flags);
    // We can only have one visible overlay and someone else has it :(
    // Drop to offscreen mode.
    if (DDERR_OUTOFCAPS == hr)
    {
        m_nBltMode = HX_BASIC_BLT;
        m_bMultipleOverlay = !m_bLostHWAcceleration;//TRUE;
    }
    // If we lost/restored our surfaces, the video will be garbage so force
    // a redraw.
    else if (DDERR_SURFACELOST == hr)
        m_nLastBltMode = HX_NO_BLT;
}

BOOL CWinSurface::_IsSurfaceVisible()
{
    CWinBaseRootSurface* pSurface = (CWinBaseRootSurface*)m_pSite->GetRootSurface();
    if (!pSurface)
        return FALSE;

    WINDRAW* pWindraw = pSurface->GetWinDraw();

    return WinDraw2_IsSurfaceVisible(pWindraw, &m_surface);
}

void CWinSurface::_ReleaseSurface()
{
    CWinBaseRootSurface* pSurface = (CWinBaseRootSurface*)m_pSite->GetRootSurface();
    if (pSurface)
    {
        WINDRAW* pWindraw = pSurface->GetWinDraw();
        if (pWindraw)
        {
            WinDraw2_ReleaseSurface(pWindraw, &m_surface);
        }
    }

    m_nLastBltMode = HX_NO_BLT;
}

HXxDC CWinSurface::_GetDC(HXxWindow* pWindow)
{
    HWND hwnd = (HWND) pWindow->window;
    return     (HXxDC) GetDC(hwnd);
}

void CWinSurface::_ReleaseDC(HXxWindow* pWindow, HXxDC hdc)
{
    HWND hwnd = (HWND) pWindow->window;
    ReleaseDC(hwnd, (HDC)hdc);
}

void CWinSurface::_GetWindowDeviceCords(HXxRect* rect)
{
    HXxWindow* pWin = m_pSite->GetWindow();
    if( pWin )
    {
        HWND hwnd = (HWND) pWin->window;
        GetWindowRect(hwnd,(RECT*)rect);
    }
}

HX_RESULT CWinSurface::RelinquishOverlay()
{
    return CBaseSurface::RelinquishOverlay();
}

HX_RESULT CWinSurface::AcquireOverlay()
{
    return CBaseSurface::AcquireOverlay();
}

void CWinSurface::_ColorWindows()
{
    int index = m_pSite->m_pTopLevelSite->m_nWindowColor++;

    if (m_pSite && m_pSite->GetWindow())
    {
        HWND hwnd = (HWND) (m_pSite->GetWindow())->window;
        HDC hdc = GetDC(hwnd);

        LOGBRUSH logBrush;
        logBrush.lbStyle = BS_SOLID;
        UCHAR red   =  (index) * 16;
        UCHAR green =  (index+5) * 16;
        UCHAR blue  =  (index+10) * 16;
        logBrush.lbColor = (red << 16) | (green <<8) | blue;
        logBrush.lbHatch = 0;
        HBRUSH brush = CreateBrushIndirect(&logBrush);
        HBRUSH oldBrush = (HBRUSH) SelectObject(hdc, brush);

        Rectangle(hdc, 0,0, 1000, 1000);

        SelectObject(hdc, oldBrush);
        DeleteObject(brush);
        ReleaseDC(hwnd, hdc);

        RECT rect;
        ::GetWindowRect(hwnd, &rect);
        FILE* f = fopen("c:\\color.txt", "a+"); /* Flawfinder: ignore */
        fprintf(f, "%p HWND %p %p (%d, %d, %d, %d)\n", this, hwnd, logBrush.lbColor, rect.left, rect.top, rect.right, rect.bottom);
        HRGN r = CreateRectRgn(0,0,0,0);
        GetWindowRgn( hwnd, r);
        DWORD dwCount = GetRegionData( r, 0, 0);
        char* p = (char* ) calloc(dwCount, 1);
        LPRGNDATA pdata = (LPRGNDATA)p;
        DWORD ret = GetRegionData( r, dwCount, pdata);
        fprintf(f, "\tCount: %d Size: %d\n", pdata->rdh.nCount, dwCount);
        RECT* pr = (RECT*)pdata->Buffer;
        for(int i = 0; i< pdata->rdh.nCount; i++)
            fprintf(f, "\t\t(%d, %d, %d, %d)\n", pr[i]);
        DeleteObject(r);
        free(p);
        fclose(f);
    }
}

BOOL  CWinSurface::UsingOverlay()
{
    if (m_surface.fMode & WINDRAWSURFACE_OVERLAY)
    {
        return TRUE;
    }

    if (m_pLinkedOverlay)
    {
        return m_pLinkedOverlay->UsingOverlay();
    }

    return FALSE;
}
