/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: gifvsrc.cpp,v 1.2.24.1 2004/07/09 01:54:22 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 "giffdll.ver"

#include "hxcom.h"
#include "hxtypes.h"
#include "hxcomm.h"
#include "ihxpckts.h"
#include "hxformt.h"
#include "hxplugn.h"
#include "hxvsrc.h"  /*IHXFileViewSource*/
#include "ihxfgbuf.h"
#include "chxfgbuf.h"
#include "growingq.h" /*CHXFragmentedBuffer*/
#include "hxassert.h"
#include "baseobj.h"

#include "gifimage.h"
#include "gifcodec.h"
#include "gifvsrc.h"
#include "vsrcinfo.h"
#include "timerep.h"

const UINT32 INITIAL_QUEUESIZE = 1000;

CGIFViewSource::CGIFViewSource(IUnknown* pContext, 
				     IUnknown* pContainer)
    :	m_lRefCount(0)
    ,	m_pContext(NULL)
    ,	m_pCommonClassFactory(NULL)
    ,	m_pFileObject(NULL)
    ,	m_pViewSourceResponse(NULL)
    ,	m_type(HTML_SOURCE)
    ,	m_pContainer(NULL)
    ,	m_ulFileSize(0)
    ,	m_pFileBuffer(NULL)
    ,	m_bIsGIF89a(FALSE)
    ,	m_state(kStateConstructed)
    ,	m_pViewSourceOptions(NULL)
{
    // XXX we AddRef to ourselves because we are created in
    // a QI call...
    AddRef();

    HX_RELEASE(m_pContext);
    m_pContext = pContext;
    HX_ASSERT(m_pContext != NULL);
    m_pContext->AddRef();

    HX_RELEASE(m_pContainer);
    m_pContainer = pContainer;
    HX_ASSERT(m_pContainer != NULL);
    m_pContainer->AddRef();
};
CGIFViewSource::~CGIFViewSource()
{
    Close();
}
/* *** IUnknown methods *** */

/************************************************************************
 *  Method:
 *	IUnknown::QueryInterface
 *  Purpose:
 *	Implement this to export the interfaces supported by your 
 *	object.
 */
STDMETHODIMP CGIFViewSource::QueryInterface(REFIID riid, void** ppvObj)
{
    if (IsEqualIID(riid, IID_IHXFileViewSource))
    {
	AddRef();
	*ppvObj = (IHXFileViewSource*)this;
	return HXR_OK;
    }
    else if (m_pContainer != NULL)
    {
        // deligate to our container
        return m_pContainer->QueryInterface(riid, ppvObj);
    }
    else if (IsEqualIID(riid, IID_IUnknown))
    {
        AddRef();
        *ppvObj = m_pContainer;
        return HXR_OK;
    }
    *ppvObj = NULL;
    return HXR_NOINTERFACE;
}

/************************************************************************
 *  Method:
 *	IUnknown::AddRef
 *  Purpose:
 *	Everyone usually implements this the same... feel free to use
 *	this implementation.
 */
STDMETHODIMP_(ULONG32) CGIFViewSource::AddRef()
{
    return InterlockedIncrement(&m_lRefCount);
}

/************************************************************************
 *  Method:
 *	IUnknown::Release
 *  Purpose:
 *	Everyone usually implements this the same... feel free to use
 *	this implementation.
 */
STDMETHODIMP_(ULONG32) CGIFViewSource::Release()
{
    if (InterlockedDecrement(&m_lRefCount) > 0)
    {
        return m_lRefCount;
    }

    delete this;
    return 0;
}

/************************************************************************
 *	Method:
 *	    IHXFileViewSource::Close()
 *	Purpose:
 *	    Close down...
 */
STDMETHODIMP 
CGIFViewSource::Close()
{
    HX_RELEASE(m_pContext);
    HX_RELEASE(m_pCommonClassFactory);
    HX_RELEASE(m_pContainer);
    HX_RELEASE(m_pFileBuffer);
    HX_RELEASE(m_pViewSourceOptions);
    if ( m_pFileObject != NULL )
    {
	m_pFileObject->Close();
	HX_RELEASE(m_pFileObject);
    }
    m_state = kStateConstructed;
    
    if ( m_pViewSourceResponse != NULL )
    {
	m_pViewSourceResponse->CloseDone(HXR_OK);
	HX_RELEASE(m_pViewSourceResponse);
    }
    return HXR_OK;
}

/************************************************************************
 *	Method:
 *	    IHXFileViewSource::InitViewSource
 *	Purpose:
 *	    Called by the user to init before a viewsource.
 */

STDMETHODIMP
CGIFViewSource::InitViewSource(IHXFileObject* pFileObject,
	IHXFileViewSourceResponse* pResp, SOURCE_TYPE sourceType,
	IHXValues* pOptions)
{
    if ( m_state != kStateConstructed )
    {
	return HXR_UNEXPECTED;
    }

    HX_ASSERT(pFileObject != NULL);
    HX_ASSERT(pResp != NULL);
    if ( sourceType == HTML_SOURCE )
    {
	m_type = HTML_SOURCE;
    }
    else if ( sourceType == RAW_SOURCE )
    {
	HX_ASSERT(FALSE);
	m_type = RAW_SOURCE;
	return HXR_NOTIMPL;
    }
    else
    {
	HX_ASSERT(FALSE);
	return HXR_UNEXPECTED;
    }

    HX_RELEASE(m_pViewSourceOptions);
    m_pViewSourceOptions = pOptions;
    if ( m_pViewSourceOptions )
    {
	m_pViewSourceOptions->AddRef();
    }

    HX_RELEASE(m_pCommonClassFactory);
    HX_RESULT ret = m_pContext->QueryInterface(IID_IHXCommonClassFactory, 
	(void**)&m_pCommonClassFactory);
    if ( SUCCEEDED(ret) )
    {
	HX_RELEASE(m_pFileObject);
	m_pFileObject = pFileObject;
	m_pFileObject->AddRef();
	HX_RELEASE(m_pViewSourceResponse);
	m_pViewSourceResponse = pResp;
	m_pViewSourceResponse->AddRef();

	m_state = kStateInitFilePending;
	ret = m_pFileObject->Init(HX_FILE_READ | HX_FILE_BINARY, this);
    }
    else
    {
	pResp->InitDone(HXR_FAIL);
    }
    return ret;
}

/************************************************************************
 *	Method:
 *	    IHXFileViewSource::GetSource
 *	Purpose:
 *	    Called to get source html source.  Return the source
 *	through m_pViewSourceResoponse
 */
STDMETHODIMP
CGIFViewSource::GetSource()
{
    if ( m_state != kStateReady )
    {
	return HXR_UNEXPECTED;
    }

    HX_ASSERT(m_pFileObject != NULL);
    IHXFileStat* pFileStat = NULL;
    HX_RESULT ret = m_pFileObject->QueryInterface(IID_IHXFileStat, 
	(void**)&pFileStat);
    if ( SUCCEEDED(ret) )
    {
	m_state = kStateStatPending;
	ret = pFileStat->Stat(this);
    }
    else
    {
	ret = m_pViewSourceResponse->SourceReady(ret, NULL);
    }
    HX_RELEASE(pFileStat);
    return ret;
}

/************************************************************************
 *  Method:
 *	IHXStatResponse::StatDone
 */
STDMETHODIMP 
CGIFViewSource::StatDone(HX_RESULT status,  UINT32 ulSize,
    UINT32 ulCreationTime, UINT32 ulAccessTime, UINT32 ulModificationTime,
    UINT32 ulMode)
{
    if ( m_state != kStateStatPending )
    {
	return HXR_UNEXPECTED;
    }
    HX_RESULT ret = HXR_OK;

    if ( SUCCEEDED(status) )
    {
	HX_ASSERT(m_pViewSourceResponse != NULL);
	HX_ASSERT(m_pFileObject != NULL);
	m_ulFileSize = ulSize;
	m_ulModTime = ulModificationTime;
        // Now we read we only need the first 13 bytes -
	m_state = kStateReadPending;
        ret = m_pFileObject->Read(13);
    }
    else
    {
	m_state = kStateReady;
 	ret = m_pViewSourceResponse->SourceReady(status, NULL);
    }
    return ret;
}


/************************************************************************
 *  Method:
 *    IHXFileResponse::InitDone
 *  Purpose:
 *    Notification interface provided by users of the IHXFileObject
 *    interface. This method is called by the IHXFileObject when the
 *    initialization of the file is complete.
 */
STDMETHODIMP
CGIFViewSource::InitDone( HX_RESULT status )
{
    if ( m_state != kStateInitFilePending )
    {
	return HXR_UNEXPECTED;
    }
    HX_ASSERT(m_pViewSourceResponse != NULL);
    m_state = kStateReady;
    return m_pViewSourceResponse->InitDone(status);
}

/************************************************************************
 *  Method:
 *	IHXFileResponse::ReadDone
 *  Purpose:
 *	Notification interface provided by users of the IHXFileObject
 *	interface. This method is called by the IHXFileObject when the
 *	last read from the file is complete and a buffer is available.
 */
STDMETHODIMP
CGIFViewSource::ReadDone(HX_RESULT status, 
				       IHXBuffer* pBuffer)
{
    if ( m_state != kStateReadPending )
    {
	return HXR_UNEXPECTED;
    }

    HX_RESULT result = HXR_OK;
    HX_ASSERT(m_pViewSourceResponse != NULL);
    
    m_state = kStateReady;
    if ( SUCCEEDED(status) )
    {
        // Have we read all we were supposed to?
        if (pBuffer->GetSize() == 13)
        {
	    HX_RELEASE(m_pFileBuffer);
	    m_pFileBuffer = pBuffer;
	    m_pFileBuffer->AddRef();

	    IHXBuffer* pReturnBuffer = NULL;
	    result = CreateInfoBuffer(pReturnBuffer);
	    if ( SUCCEEDED(result) )
	    {
		result = m_pViewSourceResponse->SourceReady(HXR_OK, 
		    pReturnBuffer);
	    }
	    else
	    {
		//  don't like the File format 
		result = m_pViewSourceResponse->SourceReady(result, 
		    NULL);
	    }
	    HX_RELEASE(pReturnBuffer);
        }
        else
        {
	    result = m_pViewSourceResponse->SourceReady(HXR_FAIL,
		NULL);
        }
    }
    else
    {
	result = m_pViewSourceResponse->SourceReady(status, 
    	    NULL);
    }
    return result;
}

/************************************************************************
 *  Method:
 *	IHXFileResponse::WriteDone
 *  Purpose:
 *	Notification interface provided by users of the IHXFileObject
 *	interface. This method is called by the IHXFileObject when the
 *	last write to the file is complete.
 */
STDMETHODIMP
CGIFViewSource::WriteDone(HX_RESULT status)
{
    // We don't ever write, so we don't expect to get this...
    return HXR_UNEXPECTED;
}

/************************************************************************
 *  Method:
 *	IHXFileResponse::SeekDone
 *  Purpose:
 *	Notification interface provided by users of the IHXFileObject
 *	interface. This method is called by the IHXFileObject when the
 *	last seek in the file is complete.
 */
STDMETHODIMP
CGIFViewSource::SeekDone(HX_RESULT status)
{
    return HXR_UNEXPECTED;
}

/************************************************************************
 *  Method:
 *	IHXFileResponse::CloseDone
 *  Purpose:
 *	Notification interface provided by users of the IHXFileObject
 *	interface. This method is called by the IHXFileObject when the
 *	close of the file is complete.
 */
STDMETHODIMP
CGIFViewSource::CloseDone(HX_RESULT status)
{
    return HXR_OK;
}

/************************************************************************
 *  Method:
 *	CGIFViewSource::CreateInfoBuffer
 */
STDMETHODIMP 
CGIFViewSource::CreateInfoBuffer(REF(IHXBuffer*) pBuffer)
{
    char buf[128]; /* Flawfinder: ignore */

    CGIFCodec::LogicalScreenDescriptor lsd;
    HX_RESULT ret = ParseGif(lsd);
    if ( FAILED(ret) )
    {
	return ret;
    }

    CBigByteGrowingQueue queue(INITIAL_QUEUESIZE);
    queue.EnQueue(z_pOpen);
     
    sprintf(buf, z_pImage_ss, z_pGIFGif, z_pGIFGif); /* Flawfinder: ignore */
    queue.EnQueue(buf);
    queue.EnQueue(z_pImageType);
    if ( m_bIsGIF89a )
    {
	queue.EnQueue("GIF 89a Image");
    }
    else
    {
	queue.EnQueue("GIF 87a Image");
    }
    queue.EnQueue(z_pEndLine);
    
    queue.EnQueue(z_pFileName);
    const char* pFileName;
    m_pFileObject->GetFilename(pFileName);
    queue.EnQueue(pFileName);
    queue.EnQueue(z_pEndLine);
    
    QueueModificationTime(&queue, m_ulModTime);
    QueueFileSize(&queue, m_ulFileSize);
    
    sprintf(buf, z_pImageDimen_ii, lsd.m_ulLogicalScreenWidth, /* Flawfinder: ignore */
	lsd.m_ulLogicalScreenHeight);
    queue.EnQueue(buf);
    queue.EnQueue(z_pEndLine);

    sprintf(buf, z_pColorTableBits_i, lsd.m_ulColorTableBits); /* Flawfinder: ignore */
    queue.EnQueue(buf);
    queue.EnQueue(z_pEndLine);
    
    IHXBuffer* pRam = NULL;
    IHXBuffer* pCD = NULL;
    if (m_pViewSourceOptions &&
	SUCCEEDED(m_pViewSourceOptions->GetPropertyCString("RamGenURL",
	pRam)) && 
	SUCCEEDED(m_pViewSourceOptions->GetPropertyCString("CurrentPath",
	pCD)) )
    {
	queue.EnQueue(z_pRamLink);
	queue.EnQueue("<a href =\"");
	queue.EnQueue((const char*)pRam->GetBuffer());
	const char* p = (const char*)pCD->GetBuffer();
	if ( *p == '/' )
	{
	    p++;
	}
	queue.EnQueue(p);
	queue.EnQueue("/");
	const char* pFileName;
	m_pFileObject->GetFilename(pFileName);
	queue.EnQueue(pFileName);
	queue.EnQueue("\">");
	queue.EnQueue((const char*)pRam->GetBuffer());
	queue.EnQueue(p);
	queue.EnQueue("/");
	queue.EnQueue(pFileName);
	queue.EnQueue("</a>");
	queue.EnQueue(z_pEndLine);
    }
    HX_RELEASE(pRam);
    HX_RELEASE(pCD);

    queue.EnQueue((void*)z_pClose, strlen(z_pClose));
    HX_RELEASE(pBuffer);
    m_pCommonClassFactory->CreateInstance(IID_IHXBuffer, (void**)&pBuffer);
    if ( !pBuffer )
    {
	return HXR_OUTOFMEMORY;
    }
    if ( FAILED(pBuffer->SetSize(queue.GetQueuedItemCount())) )
    {
	HX_RELEASE(pBuffer);
	return HXR_OUTOFMEMORY;
    }
    unsigned char* chr = pBuffer->GetBuffer();
    queue.DeQueue(chr, queue.GetQueuedItemCount());
    return HXR_OK;
}

/************************************************************************
 *  Method:
 *	CGIFViewSource::ParseGif
 */
STDMETHODIMP
CGIFViewSource::ParseGif(REF(CGIFCodec::LogicalScreenDescriptor) lsd)
{
    HX_RESULT retVal = HXR_OK;

    if ( m_pFileBuffer )
    {
        // Get the buffer (this causes the initial gather)
        BYTE* pBuf = m_pFileBuffer->GetBuffer();
        if (pBuf)
        {
	    UINT32 ulBufSize = m_pFileBuffer->GetSize();
	    if ( ulBufSize < 13 )
	    {
		return HXR_FAIL;
	    }

	    BYTE  *pBufLimit = pBuf + ulBufSize;
	    /* Check the signature */
	    if (pBuf[0] != 'G' || pBuf[1] != 'I' || pBuf[2] != 'F')
	    {
		return HXR_FAIL;
	    }
	    pBuf += 3;

	    /* Check the version */
	    if (pBuf[0] == '8' && pBuf[1] == '9' && pBuf[2] == 'a')
	    {
		m_bIsGIF89a = TRUE;
	    }
	    else if (pBuf[0] == '8' && pBuf[1] == '7' && pBuf[2] == 'a')
	    {
		m_bIsGIF89a = FALSE;
	    }
	    else
	    {
		return HXR_FAIL;
	    }
	    pBuf += 3;

	    /* Get the logical screen descriptor */
	    CGIFCodec::ParseLogicalScreenDescriptor(pBuf, lsd);
        }
        else
        {
            retVal = HXR_FAIL;
        }
    }
    else
    {
        retVal = HXR_UNEXPECTED;
    }
    return retVal;
}
