/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: brushrnd.cpp,v 1.5.2.1 2004/07/09 01:57:52 hubbe 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
#include "hxtypes.h"
#include "hxwintyp.h"
#include "hxcom.h"
#include "hxcomm.h"
#include "ihxpckts.h"
#include "hxplugn.h"
#include "hxrendr.h"
#include "hxvsurf.h"
#include "hxhyper.h"
#include "hxwin.h"
#include "hxver.h"
#include "hxasm.h"
#include "hxprefs.h"
#include "hxmon.h"
#include "hxupgrd.h"
#include "hxcore.h"
#include "hxerror.h"
// pnmisc
#include "baseobj.h"
#include "hxparse.h"
// pxcomlib
#include "pxtransp.h"
// baserend
#include "baserend.h"
#include "vbasernd.h"
// brushrnd
#include "brushrnd.h"
#include "brushrnd.ver"
// pndebug
#include "errdbg.h"
#include "hxheap.h"
// runtime
#include "hlxclib/string.h"
#ifdef _DEBUG
#undef HX_THIS_FILE		
static const char HX_THIS_FILE[] = __FILE__;
#endif

const char* const CBrushRenderer::m_pszName        = "Brush";
const char* const CBrushRenderer::m_pszDescription = "RealNetworks Brush Renderer Plugin";
const char* const CBrushRenderer::m_ppszMimeType[] = {"application/vnd.rn-brushstream", NULL};

CBrushRenderer::CBrushRenderer() : CRNVisualBaseRenderer()
{
    m_ulColor              = 0x00000000;
    m_pHeader              = NULL;
    m_ulChromaKey          = 0x00000000;
    m_ulChromaKeyTolerance = 0x00000000;
    m_ulChromaKeyOpacity   = 0;
    m_ulLastColor          = 0;
    m_pucBuffer            = NULL;
    m_bFirstDraw           = TRUE;
    m_bChromaKeySpecified  = FALSE;
    m_bNullBrush           = FALSE;
};

CBrushRenderer::~CBrushRenderer()
{
    HX_DELETE(m_pHeader);
    HX_VECTOR_DELETE(m_pucBuffer);
};

STDMETHODIMP CBrushRenderer::QueryInterface(REFIID riid, void** ppvObj)
{
    // If we ever have any new interfaces to add which
    // are specific to the brush renderer, then we'll need
    // to add them here. Until then we simply proxy the
    // visual base renderer.
    return CRNVisualBaseRenderer::QueryInterface(riid, ppvObj);
}

STDMETHODIMP_(UINT32) CBrushRenderer::AddRef()
{
    return CRNVisualBaseRenderer::AddRef();
}

STDMETHODIMP_(UINT32) CBrushRenderer::Release()
{
    return CRNVisualBaseRenderer::Release();
}

STDMETHODIMP CBrushRenderer::OnHeader(IHXValues* pHeader)
{
    HX_RESULT retVal = HXR_FAIL;

    if (pHeader)
    {
        // Check presentation stream and content versions
        retVal = CheckStreamVersions(pHeader);
        if (SUCCEEDED(retVal))
        {
            // Allocate a bitmap info header
            HX_DELETE(m_pHeader);
            m_pHeader = new HXBitmapInfoHeader;
            if (m_pHeader)
            {
                // Set up the bitmap info header
                m_pHeader->biSize          = 40;
                m_pHeader->biWidth         = 1;
                m_pHeader->biHeight        = 1;
                m_pHeader->biPlanes        = 1;
                m_pHeader->biBitCount      = 32;
                m_pHeader->biCompression   = HX_RGB;
                m_pHeader->biSizeImage     = 0;
                m_pHeader->biXPelsPerMeter = 0;
                m_pHeader->biYPelsPerMeter = 0;
                m_pHeader->biClrUsed       = 0;
                m_pHeader->biClrImportant  = 0;
                m_pHeader->rcolor          = 0;
                m_pHeader->gcolor          = 0;
                m_pHeader->bcolor          = 0;
                // See if we are a null brush
                UINT32 ulTmp = 0;
                HX_RESULT rv = pHeader->GetPropertyULONG32("NullBrush", ulTmp);
                if (SUCCEEDED(rv) && ulTmp)
                {
                    m_bNullBrush = TRUE;
                }
                // Get the opaque data from the stream header
                IHXBuffer* pBuffer = NULL;
                pHeader->GetPropertyBuffer("OpaqueData", pBuffer);
                if (pBuffer)
                {
                    // XXXMEH - TODO - make more robust parsing. Since
                    // we are creating this "file" in the SMIL renderer,
                    // then we can afford to do simple parsing.
                    const char* pszStr = (const char*) pBuffer->GetBuffer();
                    char*       pTmp   = new char [strlen(pszStr) + 1];
                    if (pTmp)
                    {
                        // Copy the string
                        strcpy(pTmp, pszStr); /* Flawfinder: ignore */
                        // Look for " separators
                        const char* pSep   = "\"";
                        char*       pToken = strtok(pTmp, pSep);
                        BOOL        bNext  = FALSE;
                        while (pToken)
                        {
                            if (bNext)
                            {
                                UINT32    ulColor = 0;
                                HX_RESULT rv      = HXParseColorUINT32(pToken, ulColor);
                                if (SUCCEEDED(rv))
                                {
                                    m_ulColor = ulColor;
                                    // Initialize some persistent properties
                                    CRNBaseRenderer::SetPropertyULONG32("color",             m_ulColor);
                                    CRNBaseRenderer::SetPropertyULONG32("mediaOpacity",      255);
                                    CRNBaseRenderer::SetPropertyULONG32("backgroundOpacity", 255);
                                }
                                break;
                            }
                            if (strstr(pToken, "color"))
                            {
                                bNext = TRUE;
                            }
                            pToken = strtok(NULL, pSep);
                        }
                    }
                    HX_VECTOR_DELETE(pTmp);
                }
                HX_RELEASE(pBuffer);
            }
            else
            {
                retVal = HXR_OUTOFMEMORY;
            }
        }
        else
        {
            AddMimeToUpgradeCollection(m_ppszMimeType[0]);
        }
    }

    return retVal;
}


STDMETHODIMP CBrushRenderer::OnPacketNoOffset(IHXPacket* pPacket)
{
    HX_RESULT retVal = HXR_OK;

    return retVal;
}

STDMETHODIMP CBrushRenderer::OnTimeSyncOffset(UINT32 ulTime)
{
    // We should force a redraw ONLY on
    // the first time sync
    if (m_bFirstDraw && !m_bNullBrush)
    {
        // Redraw our data by damaging the entire area of our data
        HXxSize size;
        m_pSite->GetSize(size);
        HXxRect cRect = {0, 0, size.cx, size.cy};
        m_pSite->DamageRect(cRect);
        m_pSite->ForceRedraw();
        // Clear the first draw flag
        m_bFirstDraw = FALSE;
    }

    return HXR_OK;
}

STDMETHODIMP CBrushRenderer::GetDisplayType(REF(HX_DISPLAY_TYPE) rulFlags,
                                            REF(IHXBuffer*)      pBuffer)
{
    if (m_bNullBrush)
    {
        rulFlags = HX_DISPLAY_NONE;
    }
    else
    {
        rulFlags = GetDisplayFlags();
    }

    return HXR_OK;
}

STDMETHODIMP CBrushRenderer::GetWindowSize(REF(HXxSize) rSize)
{
    rSize.cx = 1;
    rSize.cy = 1;

    return HXR_OK;
}

STDMETHODIMP CBrushRenderer::IsMouseOverActiveLink(INT16 x, INT16 y, REF(BOOL) rbActive, REF(IHXBuffer*) rpLink)
{
    HX_RESULT retVal = HXR_OK;

    rbActive = FALSE;

    return retVal;
}

STDMETHODIMP CBrushRenderer::RMASurfaceUpdate(IHXVideoSurface* pSurface)
{
    HX_RESULT retVal = HXR_FAIL;

    if (pSurface && m_pHeader && !m_bNullBrush)
    {
        retVal = SetupBuffer();
        if (SUCCEEDED(retVal))
        {
            // Set up the src and dst rect
            HXxRect rSrcRect = {0, 0, m_pHeader->biWidth, m_pHeader->biHeight};
            HXxRect rDstRect = rSrcRect;
            // Blit to the video surface
            retVal = pSurface->Blt(m_pucBuffer,
                                   m_pHeader,
                                   rDstRect,
                                   rSrcRect);
        }
    }

    return retVal;
}

STDMETHODIMP CBrushRenderer::HandleClick(INT16 x, INT16 y)
{
    return HXR_OK;
}

STDMETHODIMP CBrushRenderer::SetPropertyULONG32(const char* pName, ULONG32 ulVal)
{
    HX_RESULT retVal = HXR_OK;

    if (pName)
    {
        // Clear the flag
        BOOL bChromaKeyUpdate = FALSE;
        // Switch based on property name
        if (!strcmp(pName, "color"))
        {
            // Preserve the current alpha from the
            // color and set the color from ulVal
            m_ulColor = (m_ulColor & 0xFF000000) |
                        (ulVal     & 0x00FFFFFF);
        }
        else if (!strcmp(pName, "mediaOpacity") ||
                 !strcmp(pName, "backgroundOpacity"))
        {
            // Cap the opacity
            if (ulVal > 255) ulVal = 255;
            // Update the color
            m_ulColor = (m_ulColor             & 0x00FFFFFF) |
                        (((255 - ulVal) << 24) & 0xFF000000);
        }
        else if (!strcmp(pName, "chromaKey"))
        {
            // Save the value
            m_ulChromaKey         = ulVal;
            m_bChromaKeySpecified = TRUE;
            // We do need to update the color
            bChromaKeyUpdate = TRUE;

        }
        else if (!strcmp(pName, "chromaKeyTolerance"))
        {
            // Save the value
            m_ulChromaKeyTolerance = ulVal & 0x00FFFFFF;
            // If we have a chroma key already specified, then update
            if (m_bChromaKeySpecified)
            {
                bChromaKeyUpdate = TRUE;
            }
        }
        else if (!strcmp(pName, "chromaKeyOpacity"))
        {
            // Cap the value
            if (ulVal > 255) ulVal = 255;
            // Save the value
            m_ulChromaKeyOpacity = ulVal;
            // If we have a chroma key already specified, then update
            if (m_bChromaKeySpecified)
            {
                bChromaKeyUpdate = TRUE;
            }
        }
        // If we need to update the color because of
        // chroma key changes, then do it now
        if (bChromaKeyUpdate &&
            DoesChromaKeyMatch(m_ulColor, m_ulChromaKey, m_ulChromaKeyTolerance))
        {
            // Update the color
            m_ulColor = (m_ulColor & 0x00FFFFFF) |
                        (((255 - m_ulChromaKeyOpacity) << 24) & 0xFF000000);
        }
        // Now pass this on to our base class
        retVal = CRNBaseRenderer::SetPropertyULONG32(pName, ulVal);
    }
    else
    {
        retVal = HXR_FAIL;
    }

    return retVal;
}

HX_RESULT STDAPICALLTYPE CBrushRenderer::HXCreateInstance(IUnknown** ppIUnknown)
{
    HX_RESULT retVal = HXR_FAIL;

    if (ppIUnknown)
    {
        // Create the object
        CBrushRenderer* pObj = new CBrushRenderer();
        if (pObj)
        {
            // QI for IUnknown
            retVal = pObj->QueryInterface(IID_IUnknown, (void**) ppIUnknown);
        }
    }

    return retVal;
}

HX_RESULT STDAPICALLTYPE CBrushRenderer::CanUnload2()
{
    return ((CHXBaseCountingObject::ObjectsActive() > 0) ? HXR_FAIL : HXR_OK );
}

HX_RESULT CBrushRenderer::RMASurfaceUpdate2(IHXSubRectVideoSurface* pSurface,
                                            HXxRect*                 pExtents,
                                            HXxBoxRegion*              pDirtyRegion)
{
    HX_RESULT retVal = HXR_FAIL;

    if (pSurface && m_pHeader && !m_bNullBrush)
    {
        retVal = SetupBuffer();
        if (SUCCEEDED(retVal))
        {
            retVal = pSurface->BltSubRects(m_pucBuffer,
                                           m_pHeader,
                                           pDirtyRegion,
                                           pDirtyRegion,
                                           1.0,1.0 );
        }
    }

    return retVal;
}

void CBrushRenderer::_AttachSite()
{
    if (m_pSite)
    {
        // Subscribe to the sub rect messages, HX_SURFACE_UPDATE2.
        IHXSubRectSite* pSubRectSite = NULL;
        m_pSite->QueryInterface(IID_IHXSubRectSite, (void**) &pSubRectSite);
        if (pSubRectSite)
        {
            // If so, since IHXSubRectSite inheirits from IHXSite, lets
            // just swap the pointers and sign up for the service.
            HX_RELEASE(m_pSite);
            m_pSite = pSubRectSite;
            pSubRectSite->SendSubRectMessages(TRUE);
        }
    }
}

HX_RESULT CBrushRenderer::SetupBuffer()
{
    HX_RESULT retVal = HXR_FAIL;

    if (m_pSite && m_pHeader)
    {
        // Get the site's current size
        HXxSize cSize = {0, 0};
        m_pSite->GetSize(cSize);
        // Make sure the site has non-zero dimensions
        if (cSize.cx > 0 && cSize.cy > 0)
        {
            // Do we need to allocate a buffer?
            BOOL bAllocated = FALSE;
            if (!m_pucBuffer                    ||
                m_pHeader->biWidth  != cSize.cx ||
                m_pHeader->biHeight != cSize.cy)
            {
                UINT32 ulNumBytes = (UINT32) cSize.cx * cSize.cy * 4;
                HX_VECTOR_DELETE(m_pucBuffer);
                m_pucBuffer = new BYTE [ulNumBytes];
                if (m_pucBuffer)
                {
                    m_pHeader->biWidth     = cSize.cx;
                    m_pHeader->biHeight    = cSize.cy;
                    m_pHeader->biSizeImage = ulNumBytes;
                    bAllocated             = TRUE;
                }
            }
            if (m_pucBuffer)
            {
                // Do we need to fill in the color?
                if (bAllocated || m_ulLastColor != m_ulColor)
                {
                    // Fill in the buffer
                    UINT32  ulNumPix = (UINT32) cSize.cx * cSize.cy;
                    UINT32* pPix     = (UINT32*) m_pucBuffer;
                    while (ulNumPix--)
                    {
                        *pPix++ = m_ulColor;
                    }
                    // Save this color
                    m_ulLastColor = m_ulColor;
                    // Set the bitmap info header compression
                    m_pHeader->biCompression = (m_ulColor & 0xFF000000 ? HX_ARGB : HX_RGB);
                }
                // Clear the return value
                retVal = HXR_OK;
            }
        }
    }

    return retVal;
}

STDMETHODIMP CBrushRenderer::GetName(REF(const char*) rpszName)
{
    rpszName = (const char*) m_pszName;
    return HXR_OK;
}

STDMETHODIMP CBrushRenderer::GetDescription(REF(const char*) rpszDescription)
{
    rpszDescription = (const char*) m_pszDescription;
    return HXR_OK;
}

STDMETHODIMP CBrushRenderer::GetMimeTypes(REF(const char**) rppszMimeType)
{
    rppszMimeType = (const char**) m_ppszMimeType;
    return HXR_OK;
}

STDMETHODIMP_(UINT32) CBrushRenderer::GetPluginVersion()
{
    return TARVER_ULONG32_VERSION;
}

STDMETHODIMP_(UINT32) CBrushRenderer::GetInitialGranularity()
{
    return 200;
}

