<commit_before>/*************************************************************************
 *
 *  $RCSfile: xmlnexpi.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: vg $ $Date: 2003-06-04 12:36:37 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifdef PCH
#include "filt_pch.hxx"
#endif

#pragma hdrstop

// INCLUDE ---------------------------------------------------------------
#include <rtl/ustrbuf.hxx>

#include "xmlnexpi.hxx"
#include "xmlimprt.hxx"
#include "xmlcelli.hxx"
#include "docuno.hxx"
#include "global.hxx"
//#include "document.hxx"
#ifndef _SC_XMLCONVERTER_HXX
#include "XMLConverter.hxx"
#endif

#include <xmloff/xmltkmap.hxx>
#include <xmloff/nmspmap.hxx>
#include <com/sun/star/sheet/XSpreadsheetDocument.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/sheet/XNamedRanges.hpp>
#include <com/sun/star/sheet/NamedRangeFlag.hpp>
#ifndef _COM_SUN_STAR_SHEET_XNAMEDRANGE_HPP_
#include <com/sun/star/sheet/XNamedRange.hpp>
#endif

#define SC_NAMEDRANGES "NamedRanges"
#define SC_REPEAT_COLUMN "repeat-column"
#define SC_REPEAT_ROW "repeat-row"
#define SC_FILTER "filter"
#define SC_PRINT_RANGE "print-range"

using namespace com::sun::star;

//------------------------------------------------------------------

ScXMLNamedExpressionsContext::ScXMLNamedExpressionsContext( ScXMLImport& rImport,
                                      USHORT nPrfx,
                                      const ::rtl::OUString& rLName,
                                      const ::com::sun::star::uno::Reference<
                                      ::com::sun::star::xml::sax::XAttributeList>& xAttrList) :
    SvXMLImportContext( rImport, nPrfx, rLName )
{
/*  sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
    for( sal_Int16 i=0; i < nAttrCount; i++ )
    {
        rtl::OUString sAttrName = xAttrList->getNameByIndex( i );
        rtl::OUString aLocalName;
        USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName(
                                            sAttrName, &aLocalName );
        rtl::OUString sValue = xAttrList->getValueByIndex( i );

        const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetNamedRangeAttrTokenMap();

        switch( rAttrTokenMap.Get( nPrefix, aLocalName ) )
        {
        }
    }*/
    rImport.LockSolarMutex();
}

ScXMLNamedExpressionsContext::~ScXMLNamedExpressionsContext()
{
    GetScImport().UnlockSolarMutex();
}

SvXMLImportContext *ScXMLNamedExpressionsContext::CreateChildContext( USHORT nPrefix,
                                            const ::rtl::OUString& rLName,
                                            const ::com::sun::star::uno::Reference<
                                          ::com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
    SvXMLImportContext *pContext = 0;

    const SvXMLTokenMap& rTokenMap = GetScImport().GetNamedExpressionsElemTokenMap();
    switch( rTokenMap.Get( nPrefix, rLName ) )
    {
    case XML_TOK_NAMED_EXPRESSIONS_NAMED_RANGE:
        pContext = new ScXMLNamedRangeContext( GetScImport(), nPrefix,
                                                      rLName, xAttrList//,
                                                      //this
                                                      );
        break;
    case XML_TOK_NAMED_EXPRESSIONS_NAMED_EXPRESSION:
        pContext = new ScXMLNamedExpressionContext( GetScImport(), nPrefix,
                                                      rLName, xAttrList//,
                                                      //this
                                                      );
        break;
    }

    if( !pContext )
        pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName );

    return pContext;
}

sal_Int32 ScXMLNamedExpressionsContext::GetRangeType(const rtl::OUString sRangeType) const
{
    sal_Int32 nRangeType = 0;
    rtl::OUStringBuffer sBuffer;
    sal_Int16 i = 0;
    while (i <= sRangeType.getLength())
    {
        if ((sRangeType[i] == ' ') || (i == sRangeType.getLength()))
        {
            rtl::OUString sTemp = sBuffer.makeStringAndClear();
            if (sTemp.compareToAscii(SC_REPEAT_COLUMN) == 0)
                nRangeType |= sheet::NamedRangeFlag::COLUMN_HEADER;
            else if (sTemp.compareToAscii(SC_REPEAT_ROW) == 0)
                nRangeType |= sheet::NamedRangeFlag::ROW_HEADER;
            else if (sTemp.compareToAscii(SC_FILTER) == 0)
                 nRangeType |= sheet::NamedRangeFlag::FILTER_CRITERIA;
            else if (sTemp.compareToAscii(SC_PRINT_RANGE) == 0)
                 nRangeType |= sheet::NamedRangeFlag::PRINT_AREA;
        }
        else if (i < sRangeType.getLength())
            sBuffer.append(sRangeType[i]);
        i++;
    }
    return nRangeType;
}

void ScXMLNamedExpressionsContext::EndElement()
{
    if (GetScImport().GetModel().is())
    {
        uno::Reference <beans::XPropertySet> xPropertySet (GetScImport().GetModel(), uno::UNO_QUERY);
        if (xPropertySet.is())
        {
            uno::Any aNamedRanges = xPropertySet->getPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_NAMEDRANGES)));
            uno::Reference <sheet::XNamedRanges> xNamedRanges;
            if (aNamedRanges >>= xNamedRanges)
            {
                ScMyNamedExpressions* pNamedExpressions = GetScImport().GetNamedExpressions();
                ScMyNamedExpressions::iterator aItr = pNamedExpressions->begin();
                ScMyNamedExpressions::const_iterator aEndItr = pNamedExpressions->end();
                table::CellAddress aCellAddress;
                rtl::OUString sTempContent(RTL_CONSTASCII_USTRINGPARAM("0"));
                while (aItr != aEndItr)
                {
                    sal_Int32 nOffset(0);
                    if (ScXMLConverter::GetAddressFromString(
                        aCellAddress, (*aItr)->sBaseCellAddress, GetScImport().GetDocument(), nOffset ))
                    {
                        try
                        {
                            xNamedRanges->addNewByName((*aItr)->sName, sTempContent, aCellAddress, GetRangeType((*aItr)->sRangeType));
                        }
                        catch( uno::RuntimeException& r )
                        {
                            DBG_ERROR("here are some Named Ranges with the same name");
                            uno::Reference < container::XIndexAccess > xIndex(xNamedRanges, uno::UNO_QUERY);
                            if (xIndex.is())
                            {
                                sal_Int32 nMax(xIndex->getCount());
                                sal_Bool bInserted(sal_False);
                                sal_Int32 nCount(1);
                                rtl::OUStringBuffer sName((*aItr)->sName);
                                sName.append(sal_Unicode('_'));
                                while (!bInserted && nCount <= nMax)
                                {
                                    rtl::OUStringBuffer sTemp(sName);
                                    sTemp.append(rtl::OUString::valueOf(nCount));
                                    try
                                    {
                                        xNamedRanges->addNewByName(sTemp.makeStringAndClear(), sTempContent, aCellAddress, GetRangeType((*aItr)->sRangeType));
                                        bInserted = sal_True;
                                    }
                                    catch( uno::RuntimeException& rE )
                                    {
                                        ++nCount;
                                    }
                                }
                            }
                        }
                    }
                    aItr++;
                }
                aItr = pNamedExpressions->begin();
                while (aItr != aEndItr)
                {
                    sal_Int32 nOffset(0);
                    if (ScXMLConverter::GetAddressFromString(
                        aCellAddress, (*aItr)->sBaseCellAddress, GetScImport().GetDocument(), nOffset ))
                    {
                        sTempContent = (*aItr)->sContent;
                        ScXMLConverter::ParseFormula(sTempContent, (*aItr)->bIsExpression);
                        uno::Any aNamedRange = xNamedRanges->getByName((*aItr)->sName);
                        uno::Reference <sheet::XNamedRange> xNamedRange;
                        if (aNamedRange >>= xNamedRange)
                            xNamedRange->setContent(sTempContent);
                    }
                    delete *aItr;
                    aItr = pNamedExpressions->erase(aItr);
                }
            }
        }
    }
}

ScXMLNamedRangeContext::ScXMLNamedRangeContext( ScXMLImport& rImport,
                                      USHORT nPrfx,
                                      const ::rtl::OUString& rLName,
                                      const ::com::sun::star::uno::Reference<
                                      ::com::sun::star::xml::sax::XAttributeList>& xAttrList) :
    SvXMLImportContext( rImport, nPrfx, rLName )
{
    ScMyNamedExpression* pNamedExpression = new ScMyNamedExpression;
    sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
    const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetNamedRangeAttrTokenMap();
    for( sal_Int16 i=0; i < nAttrCount; i++ )
    {
        rtl::OUString sAttrName = xAttrList->getNameByIndex( i );
        rtl::OUString aLocalName;
        USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName(
                                            sAttrName, &aLocalName );
        rtl::OUString sValue = xAttrList->getValueByIndex( i );

        switch( rAttrTokenMap.Get( nPrefix, aLocalName ) )
        {
            case XML_TOK_NAMED_RANGE_ATTR_NAME :
            {
                pNamedExpression->sName = sValue;
            }
            break;
            case XML_TOK_NAMED_RANGE_ATTR_CELL_RANGE_ADDRESS :
            {
                pNamedExpression->sContent = sValue;
            }
            break;
            case XML_TOK_NAMED_RANGE_ATTR_BASE_CELL_ADDRESS :
            {
                pNamedExpression->sBaseCellAddress = sValue;
            }
            break;
            case XML_TOK_NAMED_RANGE_ATTR_RANGE_USABLE_AS :
            {
                pNamedExpression->sRangeType = sValue;
            }
            break;
        }
    }
    pNamedExpression->bIsExpression = sal_False;
    GetScImport().AddNamedExpression(pNamedExpression);
}

ScXMLNamedRangeContext::~ScXMLNamedRangeContext()
{
}

SvXMLImportContext *ScXMLNamedRangeContext::CreateChildContext( USHORT nPrefix,
                                            const ::rtl::OUString& rLName,
                                            const ::com::sun::star::uno::Reference<
                                          ::com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
    SvXMLImportContext *pContext = 0;

/*  const SvXMLTokenMap& rTokenMap = GetScImport().GetTableElemTokenMap();
    switch( rTokenMap.Get( nPrefix, rLName ) )
    {
    }*/

    if( !pContext )
        pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName );

    return pContext;
}

void ScXMLNamedRangeContext::EndElement()
{
}

ScXMLNamedExpressionContext::ScXMLNamedExpressionContext( ScXMLImport& rImport,
                                      USHORT nPrfx,
                                      const ::rtl::OUString& rLName,
                                      const ::com::sun::star::uno::Reference<
                                      ::com::sun::star::xml::sax::XAttributeList>& xAttrList) :
    SvXMLImportContext( rImport, nPrfx, rLName )
{
    ScMyNamedExpression* pNamedExpression = new ScMyNamedExpression;
    sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
    const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetNamedExpressionAttrTokenMap();
    for( sal_Int16 i=0; i < nAttrCount; i++ )
    {
        rtl::OUString sAttrName = xAttrList->getNameByIndex( i );
        rtl::OUString aLocalName;
        USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName(
                                            sAttrName, &aLocalName );
        rtl::OUString sValue = xAttrList->getValueByIndex( i );

        switch( rAttrTokenMap.Get( nPrefix, aLocalName ) )
        {
            case XML_TOK_NAMED_EXPRESSION_ATTR_NAME :
            {
                pNamedExpression->sName = sValue;
            }
            break;
            case XML_TOK_NAMED_EXPRESSION_ATTR_EXPRESSION :
            {
                pNamedExpression->sContent = sValue;
            }
            break;
            case XML_TOK_NAMED_EXPRESSION_ATTR_BASE_CELL_ADDRESS :
            {
                pNamedExpression->sBaseCellAddress = sValue;
            }
            break;
        }
    }
    pNamedExpression->bIsExpression = sal_True;
    GetScImport().AddNamedExpression(pNamedExpression);
}

ScXMLNamedExpressionContext::~ScXMLNamedExpressionContext()
{
}

SvXMLImportContext *ScXMLNamedExpressionContext::CreateChildContext( USHORT nPrefix,
                                            const ::rtl::OUString& rLName,
                                            const ::com::sun::star::uno::Reference<
                                          ::com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
    SvXMLImportContext *pContext = 0;

/*  const SvXMLTokenMap& rTokenMap = GetScImport().GetTableElemTokenMap();
    switch( rTokenMap.Get( nPrefix, rLName ) )
    {
    }*/

    if( !pContext )
        pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName );

    return pContext;
}

void ScXMLNamedExpressionContext::EndElement()
{
}

<commit_msg>INTEGRATION: CWS geordi2q01 (1.11.74); FILE MERGED 2003/08/18 14:01:35 hr 1.11.74.1: #111861#: join changes from CWS sab006<commit_after>/*************************************************************************
 *
 *  $RCSfile: xmlnexpi.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: hjs $ $Date: 2003-08-18 14:44:12 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifdef PCH
#include "filt_pch.hxx"
#endif

#pragma hdrstop

// INCLUDE ---------------------------------------------------------------
#include <rtl/ustrbuf.hxx>

#include "xmlnexpi.hxx"
#include "xmlimprt.hxx"
#include "xmlcelli.hxx"
#include "docuno.hxx"
#include "global.hxx"
#ifndef _SC_XMLCONVERTER_HXX
#include "XMLConverter.hxx"
#endif

#include <xmloff/xmltkmap.hxx>
#include <xmloff/nmspmap.hxx>

using namespace com::sun::star;

//------------------------------------------------------------------

ScXMLNamedExpressionsContext::ScXMLNamedExpressionsContext( ScXMLImport& rImport,
                                      USHORT nPrfx,
                                      const ::rtl::OUString& rLName,
                                      const ::com::sun::star::uno::Reference<
                                      ::com::sun::star::xml::sax::XAttributeList>& xAttrList) :
    SvXMLImportContext( rImport, nPrfx, rLName )
{
/*  sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
    for( sal_Int16 i=0; i < nAttrCount; i++ )
    {
        rtl::OUString sAttrName = xAttrList->getNameByIndex( i );
        rtl::OUString aLocalName;
        USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName(
                                            sAttrName, &aLocalName );
        rtl::OUString sValue = xAttrList->getValueByIndex( i );

        const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetNamedRangeAttrTokenMap();

        switch( rAttrTokenMap.Get( nPrefix, aLocalName ) )
        {
        }
    }*/
    rImport.LockSolarMutex();
}

ScXMLNamedExpressionsContext::~ScXMLNamedExpressionsContext()
{
    GetScImport().UnlockSolarMutex();
}

SvXMLImportContext *ScXMLNamedExpressionsContext::CreateChildContext( USHORT nPrefix,
                                            const ::rtl::OUString& rLName,
                                            const ::com::sun::star::uno::Reference<
                                          ::com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
    SvXMLImportContext *pContext = 0;

    const SvXMLTokenMap& rTokenMap = GetScImport().GetNamedExpressionsElemTokenMap();
    switch( rTokenMap.Get( nPrefix, rLName ) )
    {
    case XML_TOK_NAMED_EXPRESSIONS_NAMED_RANGE:
        pContext = new ScXMLNamedRangeContext( GetScImport(), nPrefix,
                                                      rLName, xAttrList//,
                                                      //this
                                                      );
        break;
    case XML_TOK_NAMED_EXPRESSIONS_NAMED_EXPRESSION:
        pContext = new ScXMLNamedExpressionContext( GetScImport(), nPrefix,
                                                      rLName, xAttrList//,
                                                      //this
                                                      );
        break;
    }

    if( !pContext )
        pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName );

    return pContext;
}

void ScXMLNamedExpressionsContext::EndElement()
{
    // happends in ScXMLImport::EndDocument()
    // because it has to be set after the Database Ranges
}

ScXMLNamedRangeContext::ScXMLNamedRangeContext( ScXMLImport& rImport,
                                      USHORT nPrfx,
                                      const ::rtl::OUString& rLName,
                                      const ::com::sun::star::uno::Reference<
                                      ::com::sun::star::xml::sax::XAttributeList>& xAttrList) :
    SvXMLImportContext( rImport, nPrfx, rLName )
{
    ScMyNamedExpression* pNamedExpression = new ScMyNamedExpression;
    sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
    const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetNamedRangeAttrTokenMap();
    for( sal_Int16 i=0; i < nAttrCount; i++ )
    {
        rtl::OUString sAttrName = xAttrList->getNameByIndex( i );
        rtl::OUString aLocalName;
        USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName(
                                            sAttrName, &aLocalName );
        rtl::OUString sValue = xAttrList->getValueByIndex( i );

        switch( rAttrTokenMap.Get( nPrefix, aLocalName ) )
        {
            case XML_TOK_NAMED_RANGE_ATTR_NAME :
            {
                pNamedExpression->sName = sValue;
            }
            break;
            case XML_TOK_NAMED_RANGE_ATTR_CELL_RANGE_ADDRESS :
            {
                pNamedExpression->sContent = sValue;
            }
            break;
            case XML_TOK_NAMED_RANGE_ATTR_BASE_CELL_ADDRESS :
            {
                pNamedExpression->sBaseCellAddress = sValue;
            }
            break;
            case XML_TOK_NAMED_RANGE_ATTR_RANGE_USABLE_AS :
            {
                pNamedExpression->sRangeType = sValue;
            }
            break;
        }
    }
    pNamedExpression->bIsExpression = sal_False;
    GetScImport().AddNamedExpression(pNamedExpression);
}

ScXMLNamedRangeContext::~ScXMLNamedRangeContext()
{
}

SvXMLImportContext *ScXMLNamedRangeContext::CreateChildContext( USHORT nPrefix,
                                            const ::rtl::OUString& rLName,
                                            const ::com::sun::star::uno::Reference<
                                          ::com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
    SvXMLImportContext *pContext = 0;

/*  const SvXMLTokenMap& rTokenMap = GetScImport().GetTableElemTokenMap();
    switch( rTokenMap.Get( nPrefix, rLName ) )
    {
    }*/

    if( !pContext )
        pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName );

    return pContext;
}

void ScXMLNamedRangeContext::EndElement()
{
}

ScXMLNamedExpressionContext::ScXMLNamedExpressionContext( ScXMLImport& rImport,
                                      USHORT nPrfx,
                                      const ::rtl::OUString& rLName,
                                      const ::com::sun::star::uno::Reference<
                                      ::com::sun::star::xml::sax::XAttributeList>& xAttrList) :
    SvXMLImportContext( rImport, nPrfx, rLName )
{
    ScMyNamedExpression* pNamedExpression = new ScMyNamedExpression;
    sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
    const SvXMLTokenMap& rAttrTokenMap = GetScImport().GetNamedExpressionAttrTokenMap();
    for( sal_Int16 i=0; i < nAttrCount; i++ )
    {
        rtl::OUString sAttrName = xAttrList->getNameByIndex( i );
        rtl::OUString aLocalName;
        USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName(
                                            sAttrName, &aLocalName );
        rtl::OUString sValue = xAttrList->getValueByIndex( i );

        switch( rAttrTokenMap.Get( nPrefix, aLocalName ) )
        {
            case XML_TOK_NAMED_EXPRESSION_ATTR_NAME :
            {
                pNamedExpression->sName = sValue;
            }
            break;
            case XML_TOK_NAMED_EXPRESSION_ATTR_EXPRESSION :
            {
                pNamedExpression->sContent = sValue;
            }
            break;
            case XML_TOK_NAMED_EXPRESSION_ATTR_BASE_CELL_ADDRESS :
            {
                pNamedExpression->sBaseCellAddress = sValue;
            }
            break;
        }
    }
    pNamedExpression->bIsExpression = sal_True;
    GetScImport().AddNamedExpression(pNamedExpression);
}

ScXMLNamedExpressionContext::~ScXMLNamedExpressionContext()
{
}

SvXMLImportContext *ScXMLNamedExpressionContext::CreateChildContext( USHORT nPrefix,
                                            const ::rtl::OUString& rLName,
                                            const ::com::sun::star::uno::Reference<
                                          ::com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
    SvXMLImportContext *pContext = 0;

/*  const SvXMLTokenMap& rTokenMap = GetScImport().GetTableElemTokenMap();
    switch( rTokenMap.Get( nPrefix, rLName ) )
    {
    }*/

    if( !pContext )
        pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName );

    return pContext;
}

void ScXMLNamedExpressionContext::EndElement()
{
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: graphsh.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 20:59:24 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifdef PCH
#include "ui_pch.hxx"
#endif

#pragma hdrstop

//------------------------------------------------------------------

#include <sfx2/app.hxx>
#include <sfx2/objface.hxx>
#include <sfx2/request.hxx>
#include <svtools/whiter.hxx>
#include <svx/svdograf.hxx>
#include <svx/grfflt.hxx>
#include <svx/grafctrl.hxx>

#include "graphsh.hxx"
#include "sc.hrc"
#include "viewdata.hxx"
#include "drawview.hxx"
#include "scresid.hxx"

#define ScGraphicShell
#include "scslots.hxx"

#define ITEMVALUE(ItemSet,Id,Cast) ((const Cast&)(ItemSet).Get(Id)).GetValue()

SFX_IMPL_INTERFACE(ScGraphicShell, ScDrawShell, ScResId(SCSTR_GRAPHICSHELL) )
{
    SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_OBJECT|SFX_VISIBILITY_STANDARD|SFX_VISIBILITY_SERVER,
                                ScResId(RID_GRAPHIC_OBJECTBAR) );
    SFX_POPUPMENU_REGISTRATION( ScResId(RID_POPUP_GRAPHIC) );
    SFX_OBJECTMENU_REGISTRATION( SID_OBJECTMENU0, ScResId(RID_OBJECTMENU_DRAW) );
}

TYPEINIT1( ScGraphicShell, ScDrawShell );

ScGraphicShell::ScGraphicShell(ScViewData* pData) :
    ScDrawShell(pData)
{
    SetHelpId(HID_SCSHELL_GRAPHIC);
    SetName(String::CreateFromAscii(RTL_CONSTASCII_STRINGPARAM("GraphicObject")));
}

ScGraphicShell::~ScGraphicShell()
{
}

void ScGraphicShell::GetAttrState( SfxItemSet& rSet )
{
    ScDrawView* pView = GetViewData()->GetScDrawView();

    if( pView )
        SvxGrafAttrHelper::GetGrafAttrState( rSet, *pView );
}

void ScGraphicShell::Execute( SfxRequest& rReq )
{
    ScDrawView* pView = GetViewData()->GetScDrawView();

    if( pView )
    {
        SvxGrafAttrHelper::ExecuteGrafAttr( rReq, *pView );
        Invalidate();
    }
}

void ScGraphicShell::GetFilterState( SfxItemSet& rSet )
{
    ScDrawView* pView = GetViewData()->GetScDrawView();
    const SdrMarkList& rMarkList = pView->GetMarkedObjectList();
    BOOL bEnable = FALSE;

    if( rMarkList.GetMarkCount() == 1 )
    {
        SdrObject* pObj = rMarkList.GetMark( 0 )->GetObj();

        if( pObj && pObj->ISA( SdrGrafObj ) && ( ( (SdrGrafObj*) pObj )->GetGraphicType() == GRAPHIC_BITMAP ) )
            bEnable = TRUE;
    }

    if( !bEnable )
        SvxGraphicFilter::DisableGraphicFilterSlots( rSet );
}

void ScGraphicShell::ExecuteFilter( SfxRequest& rReq )
{
    ScDrawView* pView = GetViewData()->GetScDrawView();
    const SdrMarkList& rMarkList = pView->GetMarkedObjectList();

    if( rMarkList.GetMarkCount() == 1 )
    {
        SdrObject* pObj = rMarkList.GetMark( 0 )->GetObj();

        if( pObj && pObj->ISA( SdrGrafObj ) && ( (SdrGrafObj*) pObj )->GetGraphicType() == GRAPHIC_BITMAP )
        {
            GraphicObject aFilterObj( ( (SdrGrafObj*) pObj )->GetGraphicObject() );

            if( SVX_GRAPHICFILTER_ERRCODE_NONE ==
                SvxGraphicFilter::ExecuteGrfFilterSlot( rReq, aFilterObj ) )
            {
                SdrPageView* pPageView = pView->GetPageViewPvNum( 0 );

                if( pPageView )
                {
                    SdrGrafObj* pFilteredObj = (SdrGrafObj*) pObj->Clone();
                    String      aStr( pView->GetDescriptionOfMarkedObjects() );

                    aStr.Append( sal_Unicode(' ') );
                    aStr.Append( String( ScResId( SCSTR_UNDO_GRAFFILTER ) ) );
                    pView->BegUndo( aStr );
                    pFilteredObj->SetGraphicObject( aFilterObj );
                    pView->ReplaceObject( pObj, *pPageView, pFilteredObj );
                    pView->EndUndo();
                }
            }
        }
    }

    Invalidate();
}

<commit_msg>INTEGRATION: CWS sfxcleanup (1.6.124); FILE MERGED 2006/03/02 10:39:28 mba 1.6.124.2: #132394#: remove superfluous code 2006/03/02 09:26:20 mba 1.6.124.1: #132394#: remove superfluous code<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: graphsh.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2006-05-02 15:49:17 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifdef PCH
#include "ui_pch.hxx"
#endif

#pragma hdrstop

//------------------------------------------------------------------

#include <sfx2/app.hxx>
#include <sfx2/objface.hxx>
#include <sfx2/request.hxx>
#include <svtools/whiter.hxx>
#include <svx/svdograf.hxx>
#include <svx/grfflt.hxx>
#include <svx/grafctrl.hxx>

#include "graphsh.hxx"
#include "sc.hrc"
#include "viewdata.hxx"
#include "drawview.hxx"
#include "scresid.hxx"

#define ScGraphicShell
#include "scslots.hxx"

#define ITEMVALUE(ItemSet,Id,Cast) ((const Cast&)(ItemSet).Get(Id)).GetValue()

SFX_IMPL_INTERFACE(ScGraphicShell, ScDrawShell, ScResId(SCSTR_GRAPHICSHELL) )
{
    SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_OBJECT|SFX_VISIBILITY_STANDARD|SFX_VISIBILITY_SERVER,
                                ScResId(RID_GRAPHIC_OBJECTBAR) );
    SFX_POPUPMENU_REGISTRATION( ScResId(RID_POPUP_GRAPHIC) );
}

TYPEINIT1( ScGraphicShell, ScDrawShell );

ScGraphicShell::ScGraphicShell(ScViewData* pData) :
    ScDrawShell(pData)
{
    SetHelpId(HID_SCSHELL_GRAPHIC);
    SetName(String::CreateFromAscii(RTL_CONSTASCII_STRINGPARAM("GraphicObject")));
}

ScGraphicShell::~ScGraphicShell()
{
}

void ScGraphicShell::GetAttrState( SfxItemSet& rSet )
{
    ScDrawView* pView = GetViewData()->GetScDrawView();

    if( pView )
        SvxGrafAttrHelper::GetGrafAttrState( rSet, *pView );
}

void ScGraphicShell::Execute( SfxRequest& rReq )
{
    ScDrawView* pView = GetViewData()->GetScDrawView();

    if( pView )
    {
        SvxGrafAttrHelper::ExecuteGrafAttr( rReq, *pView );
        Invalidate();
    }
}

void ScGraphicShell::GetFilterState( SfxItemSet& rSet )
{
    ScDrawView* pView = GetViewData()->GetScDrawView();
    const SdrMarkList& rMarkList = pView->GetMarkedObjectList();
    BOOL bEnable = FALSE;

    if( rMarkList.GetMarkCount() == 1 )
    {
        SdrObject* pObj = rMarkList.GetMark( 0 )->GetObj();

        if( pObj && pObj->ISA( SdrGrafObj ) && ( ( (SdrGrafObj*) pObj )->GetGraphicType() == GRAPHIC_BITMAP ) )
            bEnable = TRUE;
    }

    if( !bEnable )
        SvxGraphicFilter::DisableGraphicFilterSlots( rSet );
}

void ScGraphicShell::ExecuteFilter( SfxRequest& rReq )
{
    ScDrawView* pView = GetViewData()->GetScDrawView();
    const SdrMarkList& rMarkList = pView->GetMarkedObjectList();

    if( rMarkList.GetMarkCount() == 1 )
    {
        SdrObject* pObj = rMarkList.GetMark( 0 )->GetObj();

        if( pObj && pObj->ISA( SdrGrafObj ) && ( (SdrGrafObj*) pObj )->GetGraphicType() == GRAPHIC_BITMAP )
        {
            GraphicObject aFilterObj( ( (SdrGrafObj*) pObj )->GetGraphicObject() );

            if( SVX_GRAPHICFILTER_ERRCODE_NONE ==
                SvxGraphicFilter::ExecuteGrfFilterSlot( rReq, aFilterObj ) )
            {
                SdrPageView* pPageView = pView->GetPageViewPvNum( 0 );

                if( pPageView )
                {
                    SdrGrafObj* pFilteredObj = (SdrGrafObj*) pObj->Clone();
                    String      aStr( pView->GetDescriptionOfMarkedObjects() );

                    aStr.Append( sal_Unicode(' ') );
                    aStr.Append( String( ScResId( SCSTR_UNDO_GRAFFILTER ) ) );
                    pView->BegUndo( aStr );
                    pFilteredObj->SetGraphicObject( aFilterObj );
                    pView->ReplaceObject( pObj, *pPageView, pFilteredObj );
                    pView->EndUndo();
                }
            }
        }
    }

    Invalidate();
}

<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "media/base/media.h"

#include <windows.h>

#include "base/file_path.h"
#include "base/logging.h"
#include "base/path_service.h"

// Enable timing code by turning on TESTING macro.
//#define TESTING 1

#ifdef TESTING
#include "base/string_util.h"
#include "base/time.h"

namespace {
// Fetch current time as milliseconds.
// Return as double for high duration and precision.
// TODO(fbarchard): integrate into base/time.h
static inline double GetTime() {
  return base::TimeTicks::HighResNow().ToInternalValue() * (1.0 / 1000.0);
}
}
#endif

namespace media {

namespace {

enum FFmpegDLLKeys {
  FILE_LIBAVCODEC,       // full path to libavcodec media decoding library.
  FILE_LIBAVFORMAT,      // full path to libavformat media parsing library.
  FILE_LIBAVUTIL,        // full path to libavutil media utility library.
};

// Retrieves the DLLName for the given key.
FilePath::CharType* GetDLLName(FFmpegDLLKeys dll_key) {
  // TODO(ajwong): Do we want to lock to a specific ffmpeg version?
  switch (dll_key) {
    case FILE_LIBAVCODEC:
      return FILE_PATH_LITERAL("avcodec-52.dll");
    case FILE_LIBAVFORMAT:
      return FILE_PATH_LITERAL("avformat-52.dll");
    case FILE_LIBAVUTIL:
      return FILE_PATH_LITERAL("avutil-50.dll");
    default:
      LOG(DFATAL) << "Invalid DLL key requested: " << dll_key;
      return FILE_PATH_LITERAL("");
  }
}

}  // namespace

// Attempts to initialize the media library (loading DLLs, DSOs, etc.).
// Returns true if everything was successfully initialized, false otherwise.
bool InitializeMediaLibrary(const FilePath& base_path) {
  FFmpegDLLKeys path_keys[] = {
    media::FILE_LIBAVCODEC,
    media::FILE_LIBAVFORMAT,
    media::FILE_LIBAVUTIL
  };
  HMODULE libs[arraysize(path_keys)] = {NULL};
  for (size_t i = 0; i < arraysize(path_keys); ++i) {
    FilePath path = base_path.Append(GetDLLName(path_keys[i]));
#ifdef TESTING
    double dll_loadtime_start = GetTime();
#endif
    const wchar_t* cpath = path.value().c_str();
    libs[i] = LoadLibrary(cpath);
    if (!libs[i])
      break;
#ifdef TESTING
    double dll_loadtime_end = GetTime();
    std::wstring outputbuf = StringPrintf(L"DLL loadtime %5.2f ms, %ls\n",
        dll_loadtime_end - dll_loadtime_start,
        cpath);
    OutputDebugStringW(outputbuf.c_str());
#endif
  }

  // Check that we loaded all libraries successfully.  We only need to check the
  // last array element because the loop above will break without initializing
  // it on any prior error.
  if (libs[arraysize(libs)-1])
    return true;

  // Free any loaded libraries if we weren't successful.
  for (size_t i = 0; i < arraysize(libs) && libs[i] != NULL; ++i) {
    FreeLibrary(libs[i]);
    libs[i] = NULL;  // Just to be safe.
  }
  return false;
}

bool InitializeOpenMaxLibrary(const FilePath& module_dir) {
  NOTIMPLEMENTED() << "OpenMAX is not used in Windows.";
  return false;
}

}  // namespace media
<commit_msg>Limit the DLL search path when loading FFmpeg binaries on Windows.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "media/base/media.h"

#include <windows.h>

#include "base/file_path.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/scoped_ptr.h"

// Enable timing code by turning on TESTING macro.
//#define TESTING 1

#ifdef TESTING
#include "base/string_util.h"
#include "base/time.h"

namespace {
// Fetch current time as milliseconds.
// Return as double for high duration and precision.
// TODO(fbarchard): integrate into base/time.h
static inline double GetTime() {
  return base::TimeTicks::HighResNow().ToInternalValue() * (1.0 / 1000.0);
}
}
#endif

namespace media {

namespace {

enum FFmpegDLLKeys {
  FILE_LIBAVCODEC,       // full path to libavcodec media decoding library.
  FILE_LIBAVFORMAT,      // full path to libavformat media parsing library.
  FILE_LIBAVUTIL,        // full path to libavutil media utility library.
};

// Retrieves the DLLName for the given key.
FilePath::CharType* GetDLLName(FFmpegDLLKeys dll_key) {
  // TODO(ajwong): Do we want to lock to a specific ffmpeg version?
  switch (dll_key) {
    case FILE_LIBAVCODEC:
      return FILE_PATH_LITERAL("avcodec-52.dll");
    case FILE_LIBAVFORMAT:
      return FILE_PATH_LITERAL("avformat-52.dll");
    case FILE_LIBAVUTIL:
      return FILE_PATH_LITERAL("avutil-50.dll");
    default:
      LOG(DFATAL) << "Invalid DLL key requested: " << dll_key;
      return FILE_PATH_LITERAL("");
  }
}

}  // namespace

// Attempts to initialize the media library (loading DLLs, DSOs, etc.).
// Returns true if everything was successfully initialized, false otherwise.
bool InitializeMediaLibrary(const FilePath& base_path) {
  FFmpegDLLKeys path_keys[] = {
    media::FILE_LIBAVCODEC,
    media::FILE_LIBAVFORMAT,
    media::FILE_LIBAVUTIL
  };
  HMODULE libs[arraysize(path_keys)] = {NULL};

  // Limit the DLL search path so we don't load dependencies from the system
  // path.  Refer to http://crbug.com/35857
  scoped_array<wchar_t> previous_dll_directory(new wchar_t[MAX_PATH]);
  if (!GetDllDirectory(MAX_PATH, previous_dll_directory.get())) {
    previous_dll_directory.reset();
  }
  SetDllDirectory(base_path.value().c_str());

  for (size_t i = 0; i < arraysize(path_keys); ++i) {
    FilePath path(GetDLLName(path_keys[i]));
#ifdef TESTING
    double dll_loadtime_start = GetTime();
#endif
    const wchar_t* cpath = path.value().c_str();
    libs[i] = LoadLibrary(cpath);
    if (!libs[i])
      break;
#ifdef TESTING
    double dll_loadtime_end = GetTime();
    std::wstring outputbuf = StringPrintf(L"DLL loadtime %5.2f ms, %ls\n",
        dll_loadtime_end - dll_loadtime_start,
        cpath);
    OutputDebugStringW(outputbuf.c_str());
#endif
  }

  SetDllDirectory(previous_dll_directory.get());

  // Check that we loaded all libraries successfully.  We only need to check the
  // last array element because the loop above will break without initializing
  // it on any prior error.
  if (libs[arraysize(libs)-1])
    return true;

  // Free any loaded libraries if we weren't successful.
  for (size_t i = 0; i < arraysize(libs) && libs[i] != NULL; ++i) {
    FreeLibrary(libs[i]);
    libs[i] = NULL;  // Just to be safe.
  }
  return false;
}

bool InitializeOpenMaxLibrary(const FilePath& module_dir) {
  NOTIMPLEMENTED() << "OpenMAX is not used in Windows.";
  return false;
}

}  // namespace media
<|endoftext|>


<commit_before>/* -LICENSE-START-
** Copyright (c) 2013 Blackmagic Design
**
** Permission is hereby granted, free of charge, to any person or organization
** obtaining a copy of the software and accompanying documentation covered by
** this license (the "Software") to use, reproduce, display, distribute,
** execute, and transmit the Software, and to prepare derivative works of the
** Software, and to permit third-parties to whom the Software is furnished to
** do so, all subject to the following:
**
** The copyright notices in the Software and this entire statement, including
** the above license grant, this restriction and the following disclaimer,
** must be included in all copies of the Software, in whole or in part, and
** all derivative works of the Software, unless such copies or derivative
** works are solely in the form of machine-executable object code generated by
** a source language processor.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
** SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
** FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
** ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
** DEALINGS IN THE SOFTWARE.
** -LICENSE-END-
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <fcntl.h>
#include <csignal>
#include <jni.h>
#include <string>

#include "DeckLinkAPI.h"
#include "Capture.h"
#include "Util.hpp"
#include "us_ihmc_javadecklink_Capture.h"

DeckLinkCaptureDelegate::DeckLinkCaptureDelegate(IDeckLink* decklink, IDeckLinkInput* decklinkInput, JavaVM* vm) :
    m_refCount(1),
    decklink(decklink),
    decklinkInput(decklinkInput),
    vm(vm),
    initial_video_pts(AV_NOPTS_VALUE)
{
    av_register_all();
    avcodec_register_all();

    oc = avformat_alloc_context();
    oc->oformat = av_guess_format("mp4", NULL, NULL);

    if(oc->oformat == NULL)
    {
        fprintf(stderr, "AV Format mp4 not found\n");
        exit(1);
    }

    oc->oformat->video_codec = AV_CODEC_ID_MJPEG;
    snprintf(oc->filename, sizeof(oc->filename), "test.mp4");
    oc->oformat->audio_codec = AV_CODEC_ID_NONE;

}

ULONG DeckLinkCaptureDelegate::AddRef(void)
{
	return __sync_add_and_fetch(&m_refCount, 1);
}

ULONG DeckLinkCaptureDelegate::Release(void)
{
	int32_t newRefValue = __sync_sub_and_fetch(&m_refCount, 1);
	if (newRefValue == 0)
	{
		delete this;
		return 0;
	}
	return newRefValue;
}

HRESULT DeckLinkCaptureDelegate::VideoInputFrameArrived(IDeckLinkVideoInputFrame* videoFrame, IDeckLinkAudioInputPacket* audioFrame)
{
    void* frameBytes;

	// Handle Video Frame
	if (videoFrame)
    {

        JNIEnv* env = getEnv(vm);
        if(env == 0)
        {
            // Cannot throw a runtime exception because we don't have an env
            std::cerr << "Cannot load env" << std::endl;
            return S_OK;
        }

		if (videoFrame->GetFlags() & bmdFrameHasNoInputSource)
		{
            printf("Frame received - No input signal detected\n");

            //env->CallVoidMethod(obj, methodID, false, 0, 0, NULL);
		}
		else
        {

            printf("Frame received - Size: %li bytes\n",
				videoFrame->GetRowBytes() * videoFrame->GetHeight());

				videoFrame->GetBytes(&frameBytes);
                //write(g_videoOutputFile, frameBytes, videoFrame->GetRowBytes() * videoFrame->GetHeight());

                av_init_packet(&pkt);
                pkt.data = NULL;    // packet data will be allocated by the encoder
                pkt.size = 0;

                BMDTimeValue frameTime;
                BMDTimeValue frameDuration;
                videoFrame->GetStreamTime(&frameTime, &frameDuration, video_st->time_base.den);
                int64_t pts;
                pts = frameTime / video_st->time_base.num;

                if (initial_video_pts == AV_NOPTS_VALUE) {
                    initial_video_pts = pts;
                }

                pts -= initial_video_pts;

                pictureUYVY->pts = pts;
                pictureYUV420->pts = pts;
                pkt.pts = pkt.dts = pts;

                avpicture_fill((AVPicture*)pictureUYVY, (uint8_t*) frameBytes, AV_PIX_FMT_UYVY422, pictureUYVY->width, pictureUYVY->height);
                sws_scale(img_convert_ctx, pictureUYVY->data, pictureUYVY->linesize, 0, c->height, pictureYUV420->data, pictureYUV420->linesize);

                /* encode the image */
                int got_output;
                int ret = avcodec_encode_video2(c, &pkt, pictureYUV420, &got_output);
                if (ret < 0) {
                    fprintf(stderr, "error encoding frame\n");
                    exit(1);
                }
                if (got_output) {
                    printf("encoding frame %3d (size=%5d)\n", i, pkt.size);
                    av_write_frame(oc, &pkt);
                    av_free_packet(&pkt); //depreacted, use av_packet_unref(&pkt); after Ubuntu 16.04 comes out

                }

            ++i;
		}

	}

	return S_OK;
}

HRESULT DeckLinkCaptureDelegate::VideoInputFormatChanged(BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *mode, BMDDetectedVideoInputFormatFlags formatFlags)
{
    // This only gets called if bmdVideoInputEnableFormatDetection was set
    // when enabling video input
    HRESULT	result;
    char*	displayModeName = NULL;
    BMDPixelFormat	pixelFormat = bmdFormat8BitYUV;

    JNIEnv* env = getEnv(vm);
    if (formatFlags & bmdDetectedVideoInputRGB444)
    {
        throwRuntimeException(env, "Unsupported input format: RGB444");
        goto bail;
    }

    mode->GetName((const char**)&displayModeName);
    printf("Video format changed to %s %s\n", displayModeName, formatFlags & bmdDetectedVideoInputRGB444 ? "RGB" : "YUV");

    if (displayModeName)
        free(displayModeName);

    if (decklinkInput)
    {
        decklinkInput->StopStreams();

        codec = avcodec_find_encoder(AV_CODEC_ID_MJPEG);

        if (!codec) {
            fprintf(stderr, "codec not found\n");
            exit(1);
        }

        video_st = avformat_new_stream(oc, codec);
        if(!video_st)
        {
            throwRuntimeException(env, "Cannot allocate video stream");
            goto bail;
        }

        c = video_st->codec;

        /* put sample parameters */
        c->qcompress = 0.80;
        /* resolution must be a multiple of two */
        c->width = mode->GetWidth();
        c->height = mode->GetHeight();
        /* frames per second */

        BMDTimeValue numerator;
        BMDTimeScale denumerator;

        mode->GetFrameRate(&numerator, &denumerator);

        c->time_base.den = denumerator;
        c->time_base.num = numerator;
        c->pix_fmt = AV_PIX_FMT_YUVJ420P;

        if(oc->oformat->flags & AVFMT_GLOBALHEADER)
        {
            c->flags |= CODEC_FLAG_GLOBAL_HEADER;
        }

        /* open it */
        if (avcodec_open2(c, codec, NULL) < 0) {
            throwRuntimeException(env, "Could not open codec");
            goto bail;
        }

        if(avio_open(&oc->pb, oc->filename, AVIO_FLAG_WRITE) < 0)
        {
            throwRuntimeException(env, "Could not open file");
            goto bail;
        }

        pictureYUV420 = avcodec_alloc_frame();
       int ret = av_image_alloc(pictureYUV420->data, pictureYUV420->linesize, c->width, c->height,
                             c->pix_fmt, 32);
        if (ret < 0) {
            throwRuntimeException(env, "could not alloc raw picture buffer\n");
            goto bail;
        }
        pictureYUV420->format = c->pix_fmt;
        pictureYUV420->width  = c->width;
        pictureYUV420->height = c->height;

        pictureUYVY = avcodec_alloc_frame();
        pictureUYVY->width = c->width;
        pictureUYVY->height = c->height;
        pictureUYVY->format = AV_PIX_FMT_UYVY422;

        img_convert_ctx = sws_getContext(c->width, c->height,
        AV_PIX_FMT_UYVY422,
        c->width, c->height,
        c->pix_fmt,
        sws_flags, NULL, NULL, NULL);

        avformat_write_header(oc, NULL);

        result = decklinkInput->EnableVideoInput(mode->GetDisplayMode(), pixelFormat, bmdVideoInputFlagDefault | bmdVideoInputEnableFormatDetection);
        if (result != S_OK)
        {
            throwRuntimeException(env, "Failed to switch to new video mode");
            goto bail;
        }

        decklinkInput->StartStreams();
    }

bail:
    std::cout << "Detected new mode " << mode->GetWidth() << "x" << mode->GetHeight() << std::endl;
	return S_OK;
}

void DeckLinkCaptureDelegate::Stop()
{
    decklinkInput->StopStreams();
    decklinkInput->DisableVideoInput();

    if (decklinkInput != NULL)
    {
        decklinkInput->Release();
        decklinkInput = NULL;
    }

    if (decklink != NULL)
    {
        decklink->Release();
        decklink = NULL;
    }

    releaseEnv(vm);

    avcodec_close(c);
    av_free(c);
    av_freep(&pictureYUV420->data[0]);
    avcodec_free_frame(&pictureYUV420);

    av_write_trailer(oc);
    avio_close(oc->pb);

}

JNIEXPORT void JNICALL Java_us_ihmc_javadecklink_Capture_stopCaptureNative
  (JNIEnv *, jobject, jlong delegatePtr)
{
    DeckLinkCaptureDelegate* delegate = (DeckLinkCaptureDelegate*) delegatePtr;
    delegate->Stop();
}

JNIEXPORT jlong JNICALL Java_us_ihmc_javadecklink_Capture_startCaptureNative
  (JNIEnv *env, jobject obj, jint idx, jint displayModeId)
{

	IDeckLinkIterator*				deckLinkIterator = NULL;
	IDeckLink*						deckLink = NULL;

	IDeckLinkDisplayModeIterator*	displayModeIterator = NULL;
	IDeckLinkDisplayMode*			displayMode = NULL;
    char*							displayModeName = NULL;
	BMDDisplayModeSupport			displayModeSupported;

	DeckLinkCaptureDelegate*		delegate = NULL;

    HRESULT                                                 result;

    IDeckLinkInput*	g_deckLinkInput = NULL;

    JavaVM* vm;
    JNIassert(env, env->GetJavaVM(&vm) == 0);

	// Get the DeckLink device
	deckLinkIterator = CreateDeckLinkIteratorInstance();
	if (!deckLinkIterator)
	{
		fprintf(stderr, "This application requires the DeckLink drivers installed.\n");
		goto bail;
	}

	while ((result = deckLinkIterator->Next(&deckLink)) == S_OK)
	{
		if (idx == 0)
			break;
		--idx;

		deckLink->Release();
	}

	if (result != S_OK || deckLink == NULL)
	{
        fprintf(stderr, "Unable to get DeckLink device %u\n", idx);
		goto bail;
	}

	// Get the input (capture) interface of the DeckLink device
    result = deckLink->QueryInterface(IID_IDeckLinkInput, (void**)&g_deckLinkInput);
	if (result != S_OK)
		goto bail;

    result = g_deckLinkInput->GetDisplayModeIterator(&displayModeIterator);
	if (result != S_OK)
		goto bail;

    displayModeId = 0;
	while ((result = displayModeIterator->Next(&displayMode)) == S_OK)
	{
        if (displayModeId == 0)
			break;
        --displayModeId;

		displayMode->Release();
	}

	if (result != S_OK || displayMode == NULL)
	{
        fprintf(stderr, "Unable to get display mode %d\n", displayModeId);
		goto bail;
	}

	// Get display mode name
	result = displayMode->GetName((const char**)&displayModeName);
	if (result != S_OK)
	{
		displayModeName = (char *)malloc(32);
        snprintf(displayModeName, 32, "[index %d]", displayModeId);
	}

	// Check display mode is supported with given options
    result = g_deckLinkInput->DoesSupportVideoMode(displayMode->GetDisplayMode(), bmdFormat8BitYUV, bmdVideoInputFlagDefault, &displayModeSupported, NULL);
	if (result != S_OK)
		goto bail;

	if (displayModeSupported == bmdDisplayModeNotSupported)
	{
		fprintf(stderr, "The display mode %s is not supported with the selected pixel format\n", displayModeName);
		goto bail;
	}

	// Configure the capture callback
    delegate = new DeckLinkCaptureDelegate(deckLink, g_deckLinkInput, vm);
	g_deckLinkInput->SetCallback(delegate);

    // Start capturing
    result = g_deckLinkInput->EnableVideoInput(displayMode->GetDisplayMode(), bmdFormat8BitYUV, bmdVideoInputFlagDefault | bmdVideoInputEnableFormatDetection);
    if (result != S_OK)
    {
        fprintf(stderr, "Failed to enable video input. Is another application using the card?\n");
        goto bail;
    }

    result = g_deckLinkInput->StartStreams();
    if (result != S_OK)
        goto bail;

bail:

	if (displayModeName != NULL)
		free(displayModeName);

	if (displayMode != NULL)
		displayMode->Release();

	if (displayModeIterator != NULL)
		displayModeIterator->Release();

    if (deckLinkIterator != NULL)
		deckLinkIterator->Release();

    return (jlong) delegate;
}
<commit_msg>Playing with timecodes<commit_after>/* -LICENSE-START-
** Copyright (c) 2013 Blackmagic Design
**
** Permission is hereby granted, free of charge, to any person or organization
** obtaining a copy of the software and accompanying documentation covered by
** this license (the "Software") to use, reproduce, display, distribute,
** execute, and transmit the Software, and to prepare derivative works of the
** Software, and to permit third-parties to whom the Software is furnished to
** do so, all subject to the following:
**
** The copyright notices in the Software and this entire statement, including
** the above license grant, this restriction and the following disclaimer,
** must be included in all copies of the Software, in whole or in part, and
** all derivative works of the Software, unless such copies or derivative
** works are solely in the form of machine-executable object code generated by
** a source language processor.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
** SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
** FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
** ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
** DEALINGS IN THE SOFTWARE.
** -LICENSE-END-
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <fcntl.h>
#include <csignal>
#include <jni.h>
#include <string>

#include "DeckLinkAPI.h"
#include "Capture.h"
#include "Util.hpp"
#include "us_ihmc_javadecklink_Capture.h"

DeckLinkCaptureDelegate::DeckLinkCaptureDelegate(IDeckLink* decklink, IDeckLinkInput* decklinkInput, JavaVM* vm) :
    m_refCount(1),
    decklink(decklink),
    decklinkInput(decklinkInput),
    vm(vm),
    initial_video_pts(AV_NOPTS_VALUE)
{
    av_register_all();
    avcodec_register_all();

    oc = avformat_alloc_context();
    oc->oformat = av_guess_format("mp4", NULL, NULL);

    if(oc->oformat == NULL)
    {
        fprintf(stderr, "AV Format mp4 not found\n");
        exit(1);
    }

    oc->oformat->video_codec = AV_CODEC_ID_MJPEG;
    snprintf(oc->filename, sizeof(oc->filename), "test.mp4");
    oc->oformat->audio_codec = AV_CODEC_ID_NONE;

}

ULONG DeckLinkCaptureDelegate::AddRef(void)
{
	return __sync_add_and_fetch(&m_refCount, 1);
}

ULONG DeckLinkCaptureDelegate::Release(void)
{
	int32_t newRefValue = __sync_sub_and_fetch(&m_refCount, 1);
	if (newRefValue == 0)
	{
		delete this;
		return 0;
	}
	return newRefValue;
}

HRESULT DeckLinkCaptureDelegate::VideoInputFrameArrived(IDeckLinkVideoInputFrame* videoFrame, IDeckLinkAudioInputPacket* audioFrame)
{
    void* frameBytes;

	// Handle Video Frame
	if (videoFrame)
    {

        JNIEnv* env = getEnv(vm);
        if(env == 0)
        {
            // Cannot throw a runtime exception because we don't have an env
            std::cerr << "Cannot load env" << std::endl;
            return S_OK;
        }

		if (videoFrame->GetFlags() & bmdFrameHasNoInputSource)
		{
            printf("Frame received - No input signal detected\n");

            //env->CallVoidMethod(obj, methodID, false, 0, 0, NULL);
		}
		else
        {

            printf("Frame received - Size: %li bytes\n",
				videoFrame->GetRowBytes() * videoFrame->GetHeight());

				videoFrame->GetBytes(&frameBytes);
                //write(g_videoOutputFile, frameBytes, videoFrame->GetRowBytes() * videoFrame->GetHeight());

                av_init_packet(&pkt);
                pkt.data = NULL;    // packet data will be allocated by the encoder
                pkt.size = 0;

                BMDTimeValue frameTime;
                BMDTimeValue frameDuration;
                videoFrame->GetStreamTime(&frameTime, &frameDuration, video_st->time_base.den);
                int64_t pts;
                pts = frameTime / video_st->time_base.num;

                videoFrame->GetStreamTime(&frameTime, &frameDuration, 1000000);
                printf("Got frame at %ld\n", frameTime);

                if (initial_video_pts == AV_NOPTS_VALUE) {
                    initial_video_pts = pts;
                }

                pts -= initial_video_pts;

                pictureUYVY->pts = pts;
                pictureYUV420->pts = pts;
                pkt.pts = pkt.dts = pts;

                avpicture_fill((AVPicture*)pictureUYVY, (uint8_t*) frameBytes, AV_PIX_FMT_UYVY422, pictureUYVY->width, pictureUYVY->height);
                sws_scale(img_convert_ctx, pictureUYVY->data, pictureUYVY->linesize, 0, c->height, pictureYUV420->data, pictureYUV420->linesize);

                /* encode the image */
                int got_output;
                int ret = avcodec_encode_video2(c, &pkt, pictureYUV420, &got_output);
                if (ret < 0) {
                    fprintf(stderr, "error encoding frame\n");
                    exit(1);
                }
                if (got_output) {
                    printf("encoding frame %3d (size=%5d)\n", i, pkt.size);
                    av_write_frame(oc, &pkt);
                    av_free_packet(&pkt); //depreacted, use av_packet_unref(&pkt); after Ubuntu 16.04 comes out

                }

            ++i;
		}

	}

	return S_OK;
}

HRESULT DeckLinkCaptureDelegate::VideoInputFormatChanged(BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *mode, BMDDetectedVideoInputFormatFlags formatFlags)
{
    // This only gets called if bmdVideoInputEnableFormatDetection was set
    // when enabling video input
    HRESULT	result;
    char*	displayModeName = NULL;
    BMDPixelFormat	pixelFormat = bmdFormat8BitYUV;

    JNIEnv* env = getEnv(vm);
    if (formatFlags & bmdDetectedVideoInputRGB444)
    {
        throwRuntimeException(env, "Unsupported input format: RGB444");
        goto bail;
    }

    mode->GetName((const char**)&displayModeName);
    printf("Video format changed to %s %s\n", displayModeName, formatFlags & bmdDetectedVideoInputRGB444 ? "RGB" : "YUV");

    if (displayModeName)
        free(displayModeName);

    if (decklinkInput)
    {
        decklinkInput->StopStreams();

        codec = avcodec_find_encoder(AV_CODEC_ID_MJPEG);

        if (!codec) {
            fprintf(stderr, "codec not found\n");
            exit(1);
        }

        video_st = avformat_new_stream(oc, codec);
        if(!video_st)
        {
            throwRuntimeException(env, "Cannot allocate video stream");
            goto bail;
        }

        c = video_st->codec;

        /* put sample parameters */
        c->qcompress = 0.80;
        /* resolution must be a multiple of two */
        c->width = mode->GetWidth();
        c->height = mode->GetHeight();
        /* frames per second */

        BMDTimeValue numerator;
        BMDTimeScale denumerator;

        mode->GetFrameRate(&numerator, &denumerator);

        c->time_base.den = denumerator;
        c->time_base.num = numerator;
        c->pix_fmt = AV_PIX_FMT_YUVJ420P;

        if(oc->oformat->flags & AVFMT_GLOBALHEADER)
        {
            c->flags |= CODEC_FLAG_GLOBAL_HEADER;
        }

        /* open it */
        if (avcodec_open2(c, codec, NULL) < 0) {
            throwRuntimeException(env, "Could not open codec");
            goto bail;
        }

        if(avio_open(&oc->pb, oc->filename, AVIO_FLAG_WRITE) < 0)
        {
            throwRuntimeException(env, "Could not open file");
            goto bail;
        }

        pictureYUV420 = avcodec_alloc_frame();
       int ret = av_image_alloc(pictureYUV420->data, pictureYUV420->linesize, c->width, c->height,
                             c->pix_fmt, 32);
        if (ret < 0) {
            throwRuntimeException(env, "could not alloc raw picture buffer\n");
            goto bail;
        }
        pictureYUV420->format = c->pix_fmt;
        pictureYUV420->width  = c->width;
        pictureYUV420->height = c->height;

        pictureUYVY = avcodec_alloc_frame();
        pictureUYVY->width = c->width;
        pictureUYVY->height = c->height;
        pictureUYVY->format = AV_PIX_FMT_UYVY422;

        img_convert_ctx = sws_getContext(c->width, c->height,
        AV_PIX_FMT_UYVY422,
        c->width, c->height,
        c->pix_fmt,
        sws_flags, NULL, NULL, NULL);

        avformat_write_header(oc, NULL);

        result = decklinkInput->EnableVideoInput(mode->GetDisplayMode(), pixelFormat, bmdVideoInputFlagDefault | bmdVideoInputEnableFormatDetection);
        if (result != S_OK)
        {
            throwRuntimeException(env, "Failed to switch to new video mode");
            goto bail;
        }

        decklinkInput->StartStreams();
    }

bail:
    std::cout << "Detected new mode " << mode->GetWidth() << "x" << mode->GetHeight() << std::endl;
	return S_OK;
}

void DeckLinkCaptureDelegate::Stop()
{
    decklinkInput->StopStreams();
    decklinkInput->DisableVideoInput();

    if (decklinkInput != NULL)
    {
        decklinkInput->Release();
        decklinkInput = NULL;
    }

    if (decklink != NULL)
    {
        decklink->Release();
        decklink = NULL;
    }

    releaseEnv(vm);

    avcodec_close(c);
    av_free(c);
    av_freep(&pictureYUV420->data[0]);
    avcodec_free_frame(&pictureYUV420);

    av_write_trailer(oc);
    avio_close(oc->pb);

}

JNIEXPORT void JNICALL Java_us_ihmc_javadecklink_Capture_stopCaptureNative
  (JNIEnv *, jobject, jlong delegatePtr)
{
    DeckLinkCaptureDelegate* delegate = (DeckLinkCaptureDelegate*) delegatePtr;
    delegate->Stop();
}

JNIEXPORT jlong JNICALL Java_us_ihmc_javadecklink_Capture_startCaptureNative
  (JNIEnv *env, jobject obj, jint idx, jint displayModeId)
{

	IDeckLinkIterator*				deckLinkIterator = NULL;
	IDeckLink*						deckLink = NULL;

	IDeckLinkDisplayModeIterator*	displayModeIterator = NULL;
	IDeckLinkDisplayMode*			displayMode = NULL;
    char*							displayModeName = NULL;
	BMDDisplayModeSupport			displayModeSupported;

	DeckLinkCaptureDelegate*		delegate = NULL;

    HRESULT                                                 result;

    IDeckLinkInput*	g_deckLinkInput = NULL;

    JavaVM* vm;
    JNIassert(env, env->GetJavaVM(&vm) == 0);

	// Get the DeckLink device
	deckLinkIterator = CreateDeckLinkIteratorInstance();
	if (!deckLinkIterator)
	{
		fprintf(stderr, "This application requires the DeckLink drivers installed.\n");
		goto bail;
	}

	while ((result = deckLinkIterator->Next(&deckLink)) == S_OK)
	{
		if (idx == 0)
			break;
		--idx;

		deckLink->Release();
	}

	if (result != S_OK || deckLink == NULL)
	{
        fprintf(stderr, "Unable to get DeckLink device %u\n", idx);
		goto bail;
	}

	// Get the input (capture) interface of the DeckLink device
    result = deckLink->QueryInterface(IID_IDeckLinkInput, (void**)&g_deckLinkInput);
	if (result != S_OK)
		goto bail;

    result = g_deckLinkInput->GetDisplayModeIterator(&displayModeIterator);
	if (result != S_OK)
		goto bail;

    displayModeId = 0;
	while ((result = displayModeIterator->Next(&displayMode)) == S_OK)
	{
        if (displayModeId == 0)
			break;
        --displayModeId;

		displayMode->Release();
	}

	if (result != S_OK || displayMode == NULL)
	{
        fprintf(stderr, "Unable to get display mode %d\n", displayModeId);
		goto bail;
	}

	// Get display mode name
	result = displayMode->GetName((const char**)&displayModeName);
	if (result != S_OK)
	{
		displayModeName = (char *)malloc(32);
        snprintf(displayModeName, 32, "[index %d]", displayModeId);
	}

	// Check display mode is supported with given options
    result = g_deckLinkInput->DoesSupportVideoMode(displayMode->GetDisplayMode(), bmdFormat8BitYUV, bmdVideoInputFlagDefault, &displayModeSupported, NULL);
	if (result != S_OK)
		goto bail;

	if (displayModeSupported == bmdDisplayModeNotSupported)
	{
		fprintf(stderr, "The display mode %s is not supported with the selected pixel format\n", displayModeName);
		goto bail;
	}

	// Configure the capture callback
    delegate = new DeckLinkCaptureDelegate(deckLink, g_deckLinkInput, vm);
	g_deckLinkInput->SetCallback(delegate);

    // Start capturing
    result = g_deckLinkInput->EnableVideoInput(displayMode->GetDisplayMode(), bmdFormat8BitYUV, bmdVideoInputFlagDefault | bmdVideoInputEnableFormatDetection);
    if (result != S_OK)
    {
        fprintf(stderr, "Failed to enable video input. Is another application using the card?\n");
        goto bail;
    }

    result = g_deckLinkInput->StartStreams();
    if (result != S_OK)
        goto bail;

bail:

	if (displayModeName != NULL)
		free(displayModeName);

	if (displayMode != NULL)
		displayMode->Release();

	if (displayModeIterator != NULL)
		displayModeIterator->Release();

    if (deckLinkIterator != NULL)
		deckLinkIterator->Release();

    return (jlong) delegate;
}
<|endoftext|>


<commit_before>// ======================================================================== //
// Copyright 2016 Intel Corporation                                         //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#include <chrono>

#include "OSPRayFixture.h"

#include "commandline/Utility.h"
#include "pico_bench/pico_bench.h"

using std::cout;
using std::endl;
using std::string;

// NOTE(jda) - Implement make_unique() as it didn't show up until C++14...
template<typename T, typename ...Args>
std::unique_ptr<T> make_unique(Args&& ...args)
{
  return std::unique_ptr<T>(new T( std::forward<Args>(args)... ));
}

void printUsageAndExit()
{
  cout << "Usage: ospBenchmark [options] model_file" << endl;

  cout << endl << "Args:" << endl;

  cout << endl;
  cout << "    model_file --> Scene used for benchmarking, supported types"
            << " are:" << endl;
  cout << "                   stl, msg, tri, xml, obj, hbp, x3d" << endl;

  cout << endl;
  cout << "Options:" << endl;

  cout << endl;
  cout << "**generic rendering options**" << endl;

  cout << endl;
  cout << "    -i | --image --> Specify the base filename to write the"
       << " framebuffer to a file." << endl;
  cout << "                     If ommitted, no file will be written." << endl;
  cout << "                     NOTE: this option adds '.ppm' to the end of the"
       << " filename" << endl;

  cout << endl;
  cout << "    -w | --width --> Specify the width of the benchmark frame"
       << endl;
  cout << "                     default: 1024" << endl;

  cout << endl;
  cout << "    -h | --height --> Specify the height of the benchmark frame"
       << endl;
  cout << "                      default: 1024" << endl;

  cout << endl;
  cout << "    -r | --renderer --> Specify the renderer to be benchmarked."
       << endl;
  cout << "                        Ex: -r pathtracer" << endl;
  cout << "                        default: ao1" << endl;

  cout << endl;
  cout << "    -bg | --background --> Specify the background color: R G B"
       << endl;

  cout << endl;
  cout << "    -wf | --warmup --> Specify the number of warmup frames: N"
       << endl;
  cout << "                       default: 10" << endl;

  cout << endl;
  cout << "    -bf | --bench --> Specify the number of benchmark frames: N"
       << endl;
  cout << "                      default: 100" << endl;

  cout << endl;
  cout << "    -lft | --log-frame-times --> Log frame time in ms for every frame rendered"
       << endl;

  cout << endl;
  cout << "**camera rendering options**" << endl;

  cout << endl;
  cout << "    -vp | --eye --> Specify the camera eye as: ex ey ez " << endl;

  cout << endl;
  cout << "    -vi | --gaze --> Specify the camera gaze point as: ix iy iz "
       << endl;

  cout << endl;
  cout << "    -vu | --up --> Specify the camera up as: ux uy uz " << endl;

  cout << endl;
  cout << "**volume rendering options**" << endl;

  cout << endl;
  cout << "    -s | --sampling-rate --> Specify the sampling rate for volumes."
       << endl;
  cout << "                             default: 0.125" << endl;

  cout << endl;
  cout << "    -dr | --data-range --> Specify the data range for volumes."
       << " If not specified, then the min and max data" << endl
       << " values will be used when reading the data into memory." << endl;
  cout << "                           Format: low high" << endl;

  cout << endl;
  cout << "    -tfc | --tf-color --> Specify the next color to in the transfer"
       << " function for volumes. Each entry will add to the total list of"
       << " colors in the order they are specified." << endl;
  cout << "                              Format: R G B A" << endl;
  cout << "                         Value Range: [0,1]" << endl;

  cout << "    -tfs | --tf-scale --> Specify the opacity the transfer function"
       << " will scale to: [0,x] where x is the input value." << endl;
  cout << "                          default: 1.0" << endl;

  cout << "    -tff | --tf-file --> Specify the transfer function file to use"
       << endl;

  cout << endl;
  cout << "    -is | --surface --> Specify an isosurface at value: val "
       << endl;

  cout << endl;
  cout << "    --help --> Print this help text" << endl;

  exit(0);
}

void parseCommandLine(int argc, const char *argv[])
{
  if (argc <= 1) {
    printUsageAndExit();
  }

  for (int i = 1; i < argc; ++i) {
    string arg = argv[i];
    if (arg == "--help") {
      printUsageAndExit();
    } else if (arg == "-i" || arg == "--image") {
      OSPRayFixture::imageOutputFile = argv[++i];
    } else if (arg == "-w" || arg == "--width") {
      OSPRayFixture::width = atoi(argv[++i]);
    } else if (arg == "-h" || arg == "--height") {
      OSPRayFixture::height = atoi(argv[++i]);
    } else if (arg == "-wf" || arg == "--warmup") {
      OSPRayFixture::numWarmupFrames = atoi(argv[++i]);
    } else if (arg == "-bf" || arg == "--bench") {
      OSPRayFixture::numBenchFrames = atoi(argv[++i]);
    } else if (arg == "-bg" || arg == "--background") {
      ospcommon::vec3f &color = OSPRayFixture::bg_color;
      color.x = atof(argv[++i]);
      color.y = atof(argv[++i]);
      color.z = atof(argv[++i]);
    } else if (arg == "-lft" || arg == "--log-frame-times") {
      OSPRayFixture::logFrameTimes = true;
    }
  }

  auto ospObjs = parseWithDefaultParsers(argc, argv);

  ospcommon::box3f bbox;
  std::tie(bbox,
           *OSPRayFixture::model,
           *OSPRayFixture::renderer,
           *OSPRayFixture::camera) = ospObjs;

  float width  = OSPRayFixture::width;
  float height = OSPRayFixture::height;
  auto &camera = *OSPRayFixture::camera;
  camera.set("aspect", width/height);
  camera.commit();
}

void allocateFixtureObjects()
{
  // NOTE(jda) - Have to allocate objects here, because we can't allocate them
  //             statically (before ospInit) and can't in the fixture's
  //             constructor because they need to exist during parseCommandLine.
  OSPRayFixture::renderer = make_unique<ospray::cpp::Renderer>();
  OSPRayFixture::camera   = make_unique<ospray::cpp::Camera>();
  OSPRayFixture::model    = make_unique<ospray::cpp::Model>();
  OSPRayFixture::fb       = make_unique<ospray::cpp::FrameBuffer>();
}

int main(int argc, const char *argv[])
{
  ospInit(&argc, argv);
  allocateFixtureObjects();
  parseCommandLine(argc, argv);

  using namespace std::chrono;
  using Millis = duration<double, std::ratio<1, 1000>>;
  auto bencher = pico_bench::Benchmarker<Millis>{OSPRayFixture::numBenchFrames};

  OSPRayFixture fixture;
  fixture.SetUp();
  auto stats = bencher([&]() {
    fixture.renderer->renderFrame(*fixture.fb, OSP_FB_COLOR | OSP_FB_ACCUM);
  });
  stats.time_suffix = "ms";
  if (OSPRayFixture::logFrameTimes) {
    for (size_t i = 0; i < stats.size(); ++i) {
      std::cout << stats[i].count() << stats.time_suffix << "\n";
    }
  }
  std::cout << stats << "\n";
  return 0;
}
<commit_msg>Forgot to teardown fixture<commit_after>// ======================================================================== //
// Copyright 2016 Intel Corporation                                         //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#include <chrono>

#include "OSPRayFixture.h"

#include "commandline/Utility.h"
#include "pico_bench/pico_bench.h"

using std::cout;
using std::endl;
using std::string;

// NOTE(jda) - Implement make_unique() as it didn't show up until C++14...
template<typename T, typename ...Args>
std::unique_ptr<T> make_unique(Args&& ...args)
{
  return std::unique_ptr<T>(new T( std::forward<Args>(args)... ));
}

void printUsageAndExit()
{
  cout << "Usage: ospBenchmark [options] model_file" << endl;

  cout << endl << "Args:" << endl;

  cout << endl;
  cout << "    model_file --> Scene used for benchmarking, supported types"
            << " are:" << endl;
  cout << "                   stl, msg, tri, xml, obj, hbp, x3d" << endl;

  cout << endl;
  cout << "Options:" << endl;

  cout << endl;
  cout << "**generic rendering options**" << endl;

  cout << endl;
  cout << "    -i | --image --> Specify the base filename to write the"
       << " framebuffer to a file." << endl;
  cout << "                     If ommitted, no file will be written." << endl;
  cout << "                     NOTE: this option adds '.ppm' to the end of the"
       << " filename" << endl;

  cout << endl;
  cout << "    -w | --width --> Specify the width of the benchmark frame"
       << endl;
  cout << "                     default: 1024" << endl;

  cout << endl;
  cout << "    -h | --height --> Specify the height of the benchmark frame"
       << endl;
  cout << "                      default: 1024" << endl;

  cout << endl;
  cout << "    -r | --renderer --> Specify the renderer to be benchmarked."
       << endl;
  cout << "                        Ex: -r pathtracer" << endl;
  cout << "                        default: ao1" << endl;

  cout << endl;
  cout << "    -bg | --background --> Specify the background color: R G B"
       << endl;

  cout << endl;
  cout << "    -wf | --warmup --> Specify the number of warmup frames: N"
       << endl;
  cout << "                       default: 10" << endl;

  cout << endl;
  cout << "    -bf | --bench --> Specify the number of benchmark frames: N"
       << endl;
  cout << "                      default: 100" << endl;

  cout << endl;
  cout << "    -lft | --log-frame-times --> Log frame time in ms for every frame rendered"
       << endl;

  cout << endl;
  cout << "**camera rendering options**" << endl;

  cout << endl;
  cout << "    -vp | --eye --> Specify the camera eye as: ex ey ez " << endl;

  cout << endl;
  cout << "    -vi | --gaze --> Specify the camera gaze point as: ix iy iz "
       << endl;

  cout << endl;
  cout << "    -vu | --up --> Specify the camera up as: ux uy uz " << endl;

  cout << endl;
  cout << "**volume rendering options**" << endl;

  cout << endl;
  cout << "    -s | --sampling-rate --> Specify the sampling rate for volumes."
       << endl;
  cout << "                             default: 0.125" << endl;

  cout << endl;
  cout << "    -dr | --data-range --> Specify the data range for volumes."
       << " If not specified, then the min and max data" << endl
       << " values will be used when reading the data into memory." << endl;
  cout << "                           Format: low high" << endl;

  cout << endl;
  cout << "    -tfc | --tf-color --> Specify the next color to in the transfer"
       << " function for volumes. Each entry will add to the total list of"
       << " colors in the order they are specified." << endl;
  cout << "                              Format: R G B A" << endl;
  cout << "                         Value Range: [0,1]" << endl;

  cout << "    -tfs | --tf-scale --> Specify the opacity the transfer function"
       << " will scale to: [0,x] where x is the input value." << endl;
  cout << "                          default: 1.0" << endl;

  cout << "    -tff | --tf-file --> Specify the transfer function file to use"
       << endl;

  cout << endl;
  cout << "    -is | --surface --> Specify an isosurface at value: val "
       << endl;

  cout << endl;
  cout << "    --help --> Print this help text" << endl;

  exit(0);
}

void parseCommandLine(int argc, const char *argv[])
{
  if (argc <= 1) {
    printUsageAndExit();
  }

  for (int i = 1; i < argc; ++i) {
    string arg = argv[i];
    if (arg == "--help") {
      printUsageAndExit();
    } else if (arg == "-i" || arg == "--image") {
      OSPRayFixture::imageOutputFile = argv[++i];
    } else if (arg == "-w" || arg == "--width") {
      OSPRayFixture::width = atoi(argv[++i]);
    } else if (arg == "-h" || arg == "--height") {
      OSPRayFixture::height = atoi(argv[++i]);
    } else if (arg == "-wf" || arg == "--warmup") {
      OSPRayFixture::numWarmupFrames = atoi(argv[++i]);
    } else if (arg == "-bf" || arg == "--bench") {
      OSPRayFixture::numBenchFrames = atoi(argv[++i]);
    } else if (arg == "-bg" || arg == "--background") {
      ospcommon::vec3f &color = OSPRayFixture::bg_color;
      color.x = atof(argv[++i]);
      color.y = atof(argv[++i]);
      color.z = atof(argv[++i]);
    } else if (arg == "-lft" || arg == "--log-frame-times") {
      OSPRayFixture::logFrameTimes = true;
    }
  }

  auto ospObjs = parseWithDefaultParsers(argc, argv);

  ospcommon::box3f bbox;
  std::tie(bbox,
           *OSPRayFixture::model,
           *OSPRayFixture::renderer,
           *OSPRayFixture::camera) = ospObjs;

  float width  = OSPRayFixture::width;
  float height = OSPRayFixture::height;
  auto &camera = *OSPRayFixture::camera;
  camera.set("aspect", width/height);
  camera.commit();
}

void allocateFixtureObjects()
{
  // NOTE(jda) - Have to allocate objects here, because we can't allocate them
  //             statically (before ospInit) and can't in the fixture's
  //             constructor because they need to exist during parseCommandLine.
  OSPRayFixture::renderer = make_unique<ospray::cpp::Renderer>();
  OSPRayFixture::camera   = make_unique<ospray::cpp::Camera>();
  OSPRayFixture::model    = make_unique<ospray::cpp::Model>();
  OSPRayFixture::fb       = make_unique<ospray::cpp::FrameBuffer>();
}

int main(int argc, const char *argv[])
{
  ospInit(&argc, argv);
  allocateFixtureObjects();
  parseCommandLine(argc, argv);

  using namespace std::chrono;
  using Millis = duration<double, std::ratio<1, 1000>>;
  auto bencher = pico_bench::Benchmarker<Millis>{OSPRayFixture::numBenchFrames};

  OSPRayFixture fixture;
  fixture.SetUp();
  auto stats = bencher([&]() {
    fixture.renderer->renderFrame(*fixture.fb, OSP_FB_COLOR | OSP_FB_ACCUM);
  });
  stats.time_suffix = "ms";
  if (OSPRayFixture::logFrameTimes) {
    for (size_t i = 0; i < stats.size(); ++i) {
      std::cout << stats[i].count() << stats.time_suffix << "\n";
    }
  }
  std::cout << stats << "\n";
  fixture.TearDown();
  return 0;
}
<|endoftext|>


<commit_before>#ifndef __SCHEME_MASTER_HPP_INCLUDED
#define __SCHEME_MASTER_HPP_INCLUDED

// Include standard headers
#include <string> // std::string

#include "s7.h"

namespace yli
{
    namespace scheme
    {
        class SchemeMaster
        {
            public:
                // constructor.
                SchemeMaster();

                // destructor.
                ~SchemeMaster();

                std::string eval_string(const std::string& my_string) const;

            private:
                s7_scheme* s7;
        };
    }
}

#endif
<commit_msg>`SchemeMaster`: delete copy constructor and copy assignment.<commit_after>#ifndef __SCHEME_MASTER_HPP_INCLUDED
#define __SCHEME_MASTER_HPP_INCLUDED

// Include standard headers
#include <string> // std::string

#include "s7.h"

namespace yli
{
    namespace scheme
    {
        class SchemeMaster
        {
            public:
                // constructor.
                SchemeMaster();

                SchemeMaster(const SchemeMaster&) = delete;            // Delete copy constructor.
                SchemeMaster &operator=(const SchemeMaster&) = delete; // Delete copy assignment.

                // destructor.
                ~SchemeMaster();

                std::string eval_string(const std::string& my_string) const;

            private:
                s7_scheme* s7;
        };
    }
}

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: typemanager.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2004-06-04 03:09:24 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _CODEMAKER_TYPEMANAGER_HXX_
#define _CODEMAKER_TYPEMANAGER_HXX_

#include "codemaker/global.hxx"

#include "registry/registry.hxx"
#include "registry/types.h"

#include <hash_map>
#include <list>

namespace typereg { class Reader; }

typedef ::std::list< Registry* >    RegistryList;

#if defined( _MSC_VER ) && ( _MSC_VER < 1200 )
typedef ::std::__hash_map__
<
    ::rtl::OString, // Typename
    RTTypeClass,    // TypeClass
    HashString,
    EqualString,
    NewAlloc
> T2TypeClassMap;
#else
typedef ::std::hash_map
<
    ::rtl::OString, // Typename
    RTTypeClass,    // TypeClass
    HashString,
    EqualString
> T2TypeClassMap;
#endif

struct TypeManagerImpl
{
    TypeManagerImpl()
        : m_refCount(0)
        {}

    sal_Int32       m_refCount;
};

class TypeManager
{
public:
    TypeManager();
    ~TypeManager();

    TypeManager( const TypeManager& value )
        : m_pImpl( value.m_pImpl )
    {
        acquire();
    }

    TypeManager& operator = ( const TypeManager& value )
    {
        release();
        m_pImpl = value.m_pImpl;
        acquire();
        return *this;
    }

    virtual sal_Bool isValidType(const ::rtl::OString& name) const
        { return sal_False; }

    virtual RegistryKey getTypeKey(
        const ::rtl::OString& name, sal_Bool * pIsExtraType = 0 ) const
        { return RegistryKey(); }
    virtual typereg::Reader getTypeReader(
        const ::rtl::OString& name, sal_Bool * pIsExtraType = 0 ) const = 0;
    virtual RTTypeClass getTypeClass(const ::rtl::OString& name) const
        { return RT_TYPE_INVALID; }

    virtual void setBase(const ::rtl::OString& base) {}
    virtual ::rtl::OString getBase() const { return ::rtl::OString(); }

    virtual sal_Int32 getSize() const { return 0; }

    static sal_Bool isBaseType(const ::rtl::OString& name);
protected:
    sal_Int32 acquire();
    sal_Int32 release();

protected:
    TypeManagerImpl* m_pImpl;
};

struct RegistryTypeManagerImpl
{
    RegistryTypeManagerImpl()
        : m_base("/")
        {}

    T2TypeClassMap  m_t2TypeClass;
    RegistryList    m_registries;
    RegistryList    m_extra_registries;
    ::rtl::OString  m_base;
};

class RegistryTypeManager : public TypeManager
{
public:
    RegistryTypeManager();
    ~RegistryTypeManager();

    RegistryTypeManager( const RegistryTypeManager& value )
        : TypeManager(value)
        , m_pImpl( value.m_pImpl )
    {
        acquire();
    }

    sal_Bool init(const StringVector& regFiles, const StringVector& extraFiles = StringVector() );

    sal_Bool    isValidType(const ::rtl::OString& name) const
        { return searchTypeKey(name, 0).isValid(); }
    RegistryKey getTypeKey(
        const ::rtl::OString& name, sal_Bool * pIsExtraType = 0 ) const
        { return searchTypeKey(name, pIsExtraType); }
    typereg::Reader getTypeReader(
        const ::rtl::OString& name, sal_Bool * pIsExtraType = 0 ) const;
    RTTypeClass getTypeClass(const ::rtl::OString& name) const;

    void setBase(const ::rtl::OString& base);
    ::rtl::OString getBase() const { return m_pImpl->m_base; }

    sal_Int32 getSize() const { return m_pImpl->m_t2TypeClass.size(); }
protected:
    RegistryKey searchTypeKey(
        const ::rtl::OString& name, sal_Bool * pIsExtraType = 0 ) const;
    void        freeRegistries();

    void acquire();
    void release();

protected:
    RegistryTypeManagerImpl* m_pImpl;
};

#endif // _CODEMAKER_TYPEMANAGER_HXX_
<commit_msg>INTEGRATION: CWS sdksample (1.6.14); FILE MERGED 2004/07/05 11:01:51 jsc 1.6.14.1: #i30954# use registry keys directly instead of typenames<commit_after>/*************************************************************************
 *
 *  $RCSfile: typemanager.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-01-31 15:27:21 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _CODEMAKER_TYPEMANAGER_HXX_
#define _CODEMAKER_TYPEMANAGER_HXX_

#include "codemaker/global.hxx"

#include "registry/registry.hxx"
#include "registry/types.h"

#include <hash_map>
#include <list>

namespace typereg { class Reader; }

//typedef ::std::list< Registry* >  RegistryList;
typedef ::std::vector< Registry* >  RegistryList;
typedef ::std::pair< RegistryKey, sal_Bool >    KeyPair;
typedef ::std::vector< KeyPair >    RegistryKeyList;

#if defined( _MSC_VER ) && ( _MSC_VER < 1200 )
typedef ::std::__hash_map__
<
    ::rtl::OString, // Typename
    RTTypeClass,    // TypeClass
    HashString,
    EqualString,
    NewAlloc
> T2TypeClassMap;
#else
typedef ::std::hash_map
<
    ::rtl::OString, // Typename
    RTTypeClass,    // TypeClass
    HashString,
    EqualString
> T2TypeClassMap;
#endif

struct TypeManagerImpl
{
    TypeManagerImpl()
        : m_refCount(0)
        {}

    sal_Int32       m_refCount;
};

class TypeManager
{
public:
    TypeManager();
    ~TypeManager();

    TypeManager( const TypeManager& value )
        : m_pImpl( value.m_pImpl )
    {
        acquire();
    }

    TypeManager& operator = ( const TypeManager& value )
    {
        release();
        m_pImpl = value.m_pImpl;
        acquire();
        return *this;
    }

    virtual sal_Bool isValidType(const ::rtl::OString& name) const
        { return sal_False; }

    virtual ::rtl::OString getTypeName(RegistryKey& rTypeKey) const
        { return ::rtl::OString(); }

    virtual RegistryKey getTypeKey(
        const ::rtl::OString& name, sal_Bool * pIsExtraType = 0 ) const
        { return RegistryKey(); }
    virtual RegistryKeyList getTypeKeys(const ::rtl::OString& name) const
        { return RegistryKeyList(); }
    virtual typereg::Reader getTypeReader(
        const ::rtl::OString& name, sal_Bool * pIsExtraType = 0 ) const = 0;
    virtual typereg::Reader getTypeReader(RegistryKey& rTypeKey) const = 0;
    virtual RTTypeClass getTypeClass(const ::rtl::OString& name) const
        { return RT_TYPE_INVALID; }
    virtual RTTypeClass getTypeClass(RegistryKey& rTypeKey) const
        { return RT_TYPE_INVALID; }

    virtual void setBase(const ::rtl::OString& base) {}
    virtual ::rtl::OString getBase() const { return ::rtl::OString(); }

    virtual sal_Int32 getSize() const { return 0; }

    static sal_Bool isBaseType(const ::rtl::OString& name);
protected:
    sal_Int32 acquire();
    sal_Int32 release();

protected:
    TypeManagerImpl* m_pImpl;
};

struct RegistryTypeManagerImpl
{
    RegistryTypeManagerImpl()
        : m_base("/")
        {}

    T2TypeClassMap  m_t2TypeClass;
    RegistryList    m_registries;
    RegistryList    m_extra_registries;
    ::rtl::OString  m_base;
};

class RegistryTypeManager : public TypeManager
{
public:
    RegistryTypeManager();
    ~RegistryTypeManager();

    RegistryTypeManager( const RegistryTypeManager& value )
        : TypeManager(value)
        , m_pImpl( value.m_pImpl )
    {
        acquire();
    }

    sal_Bool init(const StringVector& regFiles, const StringVector& extraFiles = StringVector() );

    ::rtl::OString getTypeName(RegistryKey& rTypeKey) const;

    sal_Bool    isValidType(const ::rtl::OString& name) const
        { return searchTypeKey(name, 0).isValid(); }
    RegistryKey getTypeKey(
        const ::rtl::OString& name, sal_Bool * pIsExtraType = 0 ) const
        { return searchTypeKey(name, pIsExtraType); }
    RegistryKeyList getTypeKeys(const ::rtl::OString& name) const;
    typereg::Reader getTypeReader(
        const ::rtl::OString& name, sal_Bool * pIsExtraType = 0 ) const;
    typereg::Reader getTypeReader(RegistryKey& rTypeKey) const;
    RTTypeClass getTypeClass(const ::rtl::OString& name) const;
    RTTypeClass getTypeClass(RegistryKey& rTypeKey) const;

    void setBase(const ::rtl::OString& base);
    ::rtl::OString getBase() const { return m_pImpl->m_base; }

    sal_Int32 getSize() const { return m_pImpl->m_t2TypeClass.size(); }
protected:
    RegistryKey searchTypeKey(
        const ::rtl::OString& name, sal_Bool * pIsExtraType = 0 ) const;
    void        freeRegistries();

    void acquire();
    void release();

protected:
    RegistryTypeManagerImpl* m_pImpl;
};

#endif // _CODEMAKER_TYPEMANAGER_HXX_
<|endoftext|>