<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: propertysetbase.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 00:05:13 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_forms.hxx"

#include "propertysetbase.hxx"

#include <cppuhelper/typeprovider.hxx>  // for getImplementationId()

#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/beans/XMultiPropertySet.hpp>
#include <com/sun/star/beans/XPropertyState.hpp>
#include <com/sun/star/uno/Reference.hxx>

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

#include <vector>

using com::sun::star::uno::Any;
using com::sun::star::uno::Type;
using com::sun::star::uno::Sequence;
using com::sun::star::uno::Reference;
using com::sun::star::uno::Exception;
using com::sun::star::uno::RuntimeException;
using com::sun::star::lang::IllegalArgumentException;
using com::sun::star::beans::Property;
using com::sun::star::beans::XPropertySetInfo;

oslInterlockedCount SAL_CALL PropertyAccessorBase::acquire()
{
    return ++m_refCount;
}

oslInterlockedCount SAL_CALL PropertyAccessorBase::release()
{
    if ( --m_refCount == 0 )
    {
        delete this;
        return 0;
    }
    return m_refCount;
}

PropertySetBase::PropertySetBase( )
    :m_pProperties( NULL )
{
}

PropertySetBase::~PropertySetBase( )
{
    DELETEZ( m_pProperties );
}

cppu::IPropertyArrayHelper& SAL_CALL PropertySetBase::getInfoHelper()
{
    if ( !m_pProperties )
    {
        DBG_ASSERT( !m_aProperties.empty(), "PropertySetBase::getInfoHelper: no registered properties!" );
        m_pProperties = new cppu::OPropertyArrayHelper( &m_aProperties[0], m_aProperties.size(), sal_False );
    }
    return *m_pProperties;
}

Reference< XPropertySetInfo > SAL_CALL PropertySetBase::getPropertySetInfo(  ) throw(RuntimeException)
{
    return cppu::OPropertySetHelper::createPropertySetInfo( getInfoHelper() );
}

void PropertySetBase::registerProperty( const Property& rProperty,
    const ::rtl::Reference< PropertyAccessorBase >& rAccessor )
{
    DBG_ASSERT( rAccessor.get(), "PropertySetBase::registerProperty: invalid property accessor, this will crash!" );
    m_aAccessors.insert( PropertyAccessors::value_type( rProperty.Handle, rAccessor ) );

    DBG_ASSERT( ( rAccessor->isWriteable() == true )
                == ( ( rProperty.Attributes & com::sun::star::beans::PropertyAttribute::READONLY ) == 0 ),
        "PropertySetBase::registerProperty: inconsistence!" );

    m_aProperties.push_back( rProperty );
}

void PropertySetBase::notifyAndCachePropertyValue( sal_Int32 nHandle )
{
    ::osl::ClearableMutexGuard aGuard( GetMutex() );

    PropertyValueCache::iterator aPos = m_aCache.find( nHandle );
    if ( aPos == m_aCache.end() )
    {   // method has never before been invoked for this property
        try
        {
            // determine the type of this property
            ::cppu::IPropertyArrayHelper& rPropertyMetaData = getInfoHelper();
            ::rtl::OUString sPropName;
            OSL_VERIFY( rPropertyMetaData.fillPropertyMembersByHandle( &sPropName, NULL, nHandle ) );
            Property aProperty = rPropertyMetaData.getPropertyByName( sPropName );
            // default construct a value of this type
            Any aEmptyValue( NULL, aProperty.Type );
            // insert into the cache
            aPos = m_aCache.insert( PropertyValueCache::value_type( nHandle, aEmptyValue ) ).first;
        }
        catch( Exception& )
        {
            DBG_ERROR( "PropertySetBase::notifyAndCachePropertyValue: this is not expected to fail!" );
        }
    }
    Any aOldValue = aPos->second;
    // determine the current value
    Any aNewValue;
    getFastPropertyValue( aNewValue, nHandle );
    // remember the old value
    aPos->second = aNewValue;

    aGuard.clear();
    if ( aNewValue != aOldValue )
        firePropertyChange( nHandle, aNewValue, aOldValue );
}

void PropertySetBase::initializePropertyValueCache( sal_Int32 nHandle )
{
    Any aCurrentValue;
    getFastPropertyValue( aCurrentValue, nHandle );

#if OSL_DEBUG_LEVEL > 0
    ::std::pair< PropertyValueCache::iterator, bool > aInsertResult =
#endif
    m_aCache.insert( PropertyValueCache::value_type( nHandle, aCurrentValue ) );
    DBG_ASSERT( aInsertResult.second, "PropertySetBase::initializePropertyValueCache: already cached a value for this property!" );
}

PropertyAccessorBase& PropertySetBase::locatePropertyHandler( sal_Int32 nHandle ) const
{
    PropertyAccessors::const_iterator aPropertyPos = m_aAccessors.find( nHandle );
    DBG_ASSERT( aPropertyPos != m_aAccessors.end() && aPropertyPos->second.get(),
        "PropertySetBase::locatePropertyHandler: accessor map is corrupted!" );
        // neither should this be called for handles where there is no accessor, nor should a
        // NULL accssor be in the map
    return *aPropertyPos->second;
}

sal_Bool SAL_CALL PropertySetBase::convertFastPropertyValue( Any& rConvertedValue, Any& rOldValue, sal_Int32 nHandle,
    const Any& rValue )
    throw (IllegalArgumentException)
{
    PropertyAccessorBase& rAccessor = locatePropertyHandler( nHandle );
    if ( !rAccessor.approveValue( rValue ) )
        throw IllegalArgumentException( ::rtl::OUString(), *this, 0 );

    rAccessor.getValue( rOldValue );
    if ( rOldValue != rValue )
    {
        rConvertedValue = rValue;   // no conversion at all
        return sal_True;
    }
    return sal_False;
}

void SAL_CALL PropertySetBase::setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const Any& rValue )
    throw (Exception)
{
    PropertyAccessorBase& rAccessor = locatePropertyHandler( nHandle );
    rAccessor.setValue( rValue );
}

void SAL_CALL PropertySetBase::getFastPropertyValue( Any& rValue, sal_Int32 nHandle ) const
{
    PropertyAccessorBase& rAccessor = locatePropertyHandler( nHandle );
    rAccessor.getValue( rValue );
}
<commit_msg>INTEGRATION: CWS changefileheader (1.6.134); FILE MERGED 2008/04/01 15:16:41 thb 1.6.134.2: #i85898# Stripping all external header guards 2008/03/31 13:11:45 rt 1.6.134.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: propertysetbase.cxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_forms.hxx"

#include "propertysetbase.hxx"

#include <cppuhelper/typeprovider.hxx>  // for getImplementationId()

#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/beans/XMultiPropertySet.hpp>
#include <com/sun/star/beans/XPropertyState.hpp>
#include <com/sun/star/uno/Reference.hxx>
#include <tools/debug.hxx>

#include <vector>

using com::sun::star::uno::Any;
using com::sun::star::uno::Type;
using com::sun::star::uno::Sequence;
using com::sun::star::uno::Reference;
using com::sun::star::uno::Exception;
using com::sun::star::uno::RuntimeException;
using com::sun::star::lang::IllegalArgumentException;
using com::sun::star::beans::Property;
using com::sun::star::beans::XPropertySetInfo;

oslInterlockedCount SAL_CALL PropertyAccessorBase::acquire()
{
    return ++m_refCount;
}

oslInterlockedCount SAL_CALL PropertyAccessorBase::release()
{
    if ( --m_refCount == 0 )
    {
        delete this;
        return 0;
    }
    return m_refCount;
}

PropertySetBase::PropertySetBase( )
    :m_pProperties( NULL )
{
}

PropertySetBase::~PropertySetBase( )
{
    DELETEZ( m_pProperties );
}

cppu::IPropertyArrayHelper& SAL_CALL PropertySetBase::getInfoHelper()
{
    if ( !m_pProperties )
    {
        DBG_ASSERT( !m_aProperties.empty(), "PropertySetBase::getInfoHelper: no registered properties!" );
        m_pProperties = new cppu::OPropertyArrayHelper( &m_aProperties[0], m_aProperties.size(), sal_False );
    }
    return *m_pProperties;
}

Reference< XPropertySetInfo > SAL_CALL PropertySetBase::getPropertySetInfo(  ) throw(RuntimeException)
{
    return cppu::OPropertySetHelper::createPropertySetInfo( getInfoHelper() );
}

void PropertySetBase::registerProperty( const Property& rProperty,
    const ::rtl::Reference< PropertyAccessorBase >& rAccessor )
{
    DBG_ASSERT( rAccessor.get(), "PropertySetBase::registerProperty: invalid property accessor, this will crash!" );
    m_aAccessors.insert( PropertyAccessors::value_type( rProperty.Handle, rAccessor ) );

    DBG_ASSERT( ( rAccessor->isWriteable() == true )
                == ( ( rProperty.Attributes & com::sun::star::beans::PropertyAttribute::READONLY ) == 0 ),
        "PropertySetBase::registerProperty: inconsistence!" );

    m_aProperties.push_back( rProperty );
}

void PropertySetBase::notifyAndCachePropertyValue( sal_Int32 nHandle )
{
    ::osl::ClearableMutexGuard aGuard( GetMutex() );

    PropertyValueCache::iterator aPos = m_aCache.find( nHandle );
    if ( aPos == m_aCache.end() )
    {   // method has never before been invoked for this property
        try
        {
            // determine the type of this property
            ::cppu::IPropertyArrayHelper& rPropertyMetaData = getInfoHelper();
            ::rtl::OUString sPropName;
            OSL_VERIFY( rPropertyMetaData.fillPropertyMembersByHandle( &sPropName, NULL, nHandle ) );
            Property aProperty = rPropertyMetaData.getPropertyByName( sPropName );
            // default construct a value of this type
            Any aEmptyValue( NULL, aProperty.Type );
            // insert into the cache
            aPos = m_aCache.insert( PropertyValueCache::value_type( nHandle, aEmptyValue ) ).first;
        }
        catch( Exception& )
        {
            DBG_ERROR( "PropertySetBase::notifyAndCachePropertyValue: this is not expected to fail!" );
        }
    }
    Any aOldValue = aPos->second;
    // determine the current value
    Any aNewValue;
    getFastPropertyValue( aNewValue, nHandle );
    // remember the old value
    aPos->second = aNewValue;

    aGuard.clear();
    if ( aNewValue != aOldValue )
        firePropertyChange( nHandle, aNewValue, aOldValue );
}

void PropertySetBase::initializePropertyValueCache( sal_Int32 nHandle )
{
    Any aCurrentValue;
    getFastPropertyValue( aCurrentValue, nHandle );

#if OSL_DEBUG_LEVEL > 0
    ::std::pair< PropertyValueCache::iterator, bool > aInsertResult =
#endif
    m_aCache.insert( PropertyValueCache::value_type( nHandle, aCurrentValue ) );
    DBG_ASSERT( aInsertResult.second, "PropertySetBase::initializePropertyValueCache: already cached a value for this property!" );
}

PropertyAccessorBase& PropertySetBase::locatePropertyHandler( sal_Int32 nHandle ) const
{
    PropertyAccessors::const_iterator aPropertyPos = m_aAccessors.find( nHandle );
    DBG_ASSERT( aPropertyPos != m_aAccessors.end() && aPropertyPos->second.get(),
        "PropertySetBase::locatePropertyHandler: accessor map is corrupted!" );
        // neither should this be called for handles where there is no accessor, nor should a
        // NULL accssor be in the map
    return *aPropertyPos->second;
}

sal_Bool SAL_CALL PropertySetBase::convertFastPropertyValue( Any& rConvertedValue, Any& rOldValue, sal_Int32 nHandle,
    const Any& rValue )
    throw (IllegalArgumentException)
{
    PropertyAccessorBase& rAccessor = locatePropertyHandler( nHandle );
    if ( !rAccessor.approveValue( rValue ) )
        throw IllegalArgumentException( ::rtl::OUString(), *this, 0 );

    rAccessor.getValue( rOldValue );
    if ( rOldValue != rValue )
    {
        rConvertedValue = rValue;   // no conversion at all
        return sal_True;
    }
    return sal_False;
}

void SAL_CALL PropertySetBase::setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const Any& rValue )
    throw (Exception)
{
    PropertyAccessorBase& rAccessor = locatePropertyHandler( nHandle );
    rAccessor.setValue( rValue );
}

void SAL_CALL PropertySetBase::getFastPropertyValue( Any& rValue, sal_Int32 nHandle ) const
{
    PropertyAccessorBase& rAccessor = locatePropertyHandler( nHandle );
    rAccessor.getValue( rValue );
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include <algorithm>

#include "formula/formulahelper.hxx"
#include <unotools/charclass.hxx>
#include <unotools/syslocale.hxx>

#include <boost/scoped_ptr.hpp>

namespace formula
{

    namespace
    {

        class OEmptyFunctionDescription : public IFunctionDescription
        {
        public:
            OEmptyFunctionDescription(){}
            virtual ~OEmptyFunctionDescription(){}

            virtual OUString getFunctionName() const SAL_OVERRIDE { return OUString(); }
            virtual const IFunctionCategory* getCategory() const SAL_OVERRIDE { return NULL; }
            virtual OUString getDescription() const SAL_OVERRIDE { return OUString(); }
            virtual sal_Int32 getSuppressedArgumentCount() const SAL_OVERRIDE { return 0; }
            virtual OUString getFormula(const ::std::vector< OUString >& ) const SAL_OVERRIDE { return OUString(); }
            virtual void fillVisibleArgumentMapping(::std::vector<sal_uInt16>& ) const SAL_OVERRIDE {}
            virtual void initArgumentInfo()  const SAL_OVERRIDE {}
            virtual OUString getSignature() const SAL_OVERRIDE { return OUString(); }
            virtual OString getHelpId() const SAL_OVERRIDE { return ""; }
            virtual sal_uInt32 getParameterCount() const SAL_OVERRIDE { return 0; }
            virtual OUString getParameterName(sal_uInt32 ) const SAL_OVERRIDE { return OUString(); }
            virtual OUString getParameterDescription(sal_uInt32 ) const SAL_OVERRIDE { return OUString(); }
            virtual bool isParameterOptional(sal_uInt32 ) const SAL_OVERRIDE { return false; }
        };
    }

//  class FormulaHelper - static Method

#define FUNC_NOTFOUND 0xffff

FormulaHelper::FormulaHelper(const IFunctionManager* _pFunctionManager)
    :m_pSysLocale(new SvtSysLocale)
    ,m_pFunctionManager(_pFunctionManager)
    ,open(_pFunctionManager->getSingleToken(IFunctionManager::eOk))
    ,close(_pFunctionManager->getSingleToken(IFunctionManager::eClose))
    ,sep(_pFunctionManager->getSingleToken(IFunctionManager::eSep))
    ,arrayOpen(_pFunctionManager->getSingleToken(IFunctionManager::eArrayOpen))
    ,arrayClose(_pFunctionManager->getSingleToken(IFunctionManager::eArrayClose))
{
    m_pCharClass = m_pSysLocale->GetCharClassPtr();
}

bool FormulaHelper::GetNextFunc( const OUString&  rFormula,
                                     bool             bBack,
                                     sal_Int32&       rFStart,   // Input and output
                                     sal_Int32*       pFEnd,     // = NULL
                                     const IFunctionDescription**   ppFDesc,   // = NULL
                                     ::std::vector< OUString>*   pArgs )  const // = NULL
{
    sal_Int32  nOldStart = rFStart;
    OUString   aFname;

    rFStart = GetFunctionStart( rFormula, rFStart, bBack, ppFDesc ? &aFname : NULL );
    bool bFound  = ( rFStart != FUNC_NOTFOUND );

    if ( bFound )
    {
        if ( pFEnd )
            *pFEnd = GetFunctionEnd( rFormula, rFStart );

        if ( ppFDesc )
        {
            *ppFDesc = NULL;
            const OUString sTemp( aFname );
            const sal_uInt32 nCategoryCount = m_pFunctionManager->getCount();
            for(sal_uInt32 j= 0; j < nCategoryCount && !*ppFDesc; ++j)
            {
                boost::scoped_ptr<const IFunctionCategory> pCategory(m_pFunctionManager->getCategory(j));
                const sal_uInt32 nCount = pCategory->getCount();
                for(sal_uInt32 i = 0 ; i < nCount; ++i)
                {
                    const IFunctionDescription* pCurrent = pCategory->getFunction(i);
                    if ( pCurrent->getFunctionName().equalsIgnoreAsciiCase(sTemp) )
                    {
                        *ppFDesc = pCurrent;
                        break;
                    }
                }// for(sal_uInt32 i = 0 ; i < nCount; ++i)
            }
            if ( *ppFDesc && pArgs )
            {
                GetArgStrings( *pArgs,rFormula, rFStart, static_cast<sal_uInt16>((*ppFDesc)->getParameterCount() ));
            }
            else
            {
                static OEmptyFunctionDescription s_aFunctionDescription;
                *ppFDesc = &s_aFunctionDescription;
            }
        }
    }
    else
        rFStart = nOldStart;

    return bFound;
}

void FormulaHelper::FillArgStrings( const OUString&   rFormula,
                                    sal_Int32         nFuncPos,
                                    sal_uInt16        nArgs,
                                    ::std::vector< OUString >& _rArgs ) const
{
    sal_Int32       nStart  = 0;
    sal_Int32       nEnd    = 0;
    sal_uInt16      i;
    bool        bLast   = false;

    for ( i=0; i<nArgs && !bLast; i++ )
    {
        nStart = GetArgStart( rFormula, nFuncPos, i );

        if ( i+1<nArgs ) // last argument?
        {
            nEnd = GetArgStart( rFormula, nFuncPos, i+1 );

            if ( nEnd != nStart )
                _rArgs.push_back(rFormula.copy( nStart, nEnd-1-nStart ));
            else
                _rArgs.push_back(OUString()), bLast = true;
        }
        else
        {
            nEnd = GetFunctionEnd( rFormula, nFuncPos )-1;
            if ( nStart < nEnd )
                _rArgs.push_back( rFormula.copy( nStart, nEnd-nStart ) );
            else
                _rArgs.push_back(OUString());
        }
    }

    if ( bLast )
        for ( ; i<nArgs; i++ )
            _rArgs.push_back(OUString());
}

void FormulaHelper::GetArgStrings( ::std::vector< OUString >& _rArgs,
                                   const OUString& rFormula,
                                   sal_Int32 nFuncPos,
                                   sal_uInt16 nArgs ) const
{
    if (nArgs)
    {
        FillArgStrings( rFormula, nFuncPos, nArgs, _rArgs );
    }
}

inline bool IsFormulaText( const CharClass* _pCharClass,const OUString& rStr, sal_Int32 nPos )
{
    if( _pCharClass->isLetterNumeric( rStr, nPos ) )
        return true;
    else
    {   // In internationalized versions function names may contain a dot
        //  and in every version also an underscore... ;-)
        sal_Unicode c = rStr[nPos];
        return c == '.' || c == '_';
    }

}

sal_Int32 FormulaHelper::GetFunctionStart( const OUString&   rFormula,
                                            sal_Int32         nStart,
                                            bool              bBack,
                                            OUString*         pFuncName ) const
{
    sal_Int32 nStrLen = rFormula.getLength();

    if ( nStrLen < nStart )
        return nStart;

    sal_Int32  nFStart = FUNC_NOTFOUND;
    sal_Int32  nParPos = bBack ? ::std::min( nStart, nStrLen - 1) : nStart;

    bool bRepeat;
    do
    {
        bool bFound  = false;
        bRepeat = false;

        if ( bBack )
        {
            while ( !bFound && (nParPos > 0) )
            {
                if ( rFormula[nParPos] == '"' )
                {
                    nParPos--;
                    while ( (nParPos > 0) && rFormula[nParPos] != '"' )
                        nParPos--;
                    if (nParPos > 0)
                        nParPos--;
                }
                else if ( (bFound = ( rFormula[nParPos] == '(' ) ) == false )
                    nParPos--;
            }
        }
        else
        {
            while ( !bFound && (nParPos < nStrLen) )
            {
                if ( rFormula[nParPos] == '"' )
                {
                    nParPos++;
                    while ( (nParPos < nStrLen) && rFormula[nParPos] != '"' )
                        nParPos++;
                    nParPos++;
                }
                else if ( (bFound = ( rFormula[nParPos] == '(' ) ) == false )
                    nParPos++;
            }
        }

        if ( bFound && (nParPos > 0) )
        {
            nFStart = nParPos-1;

            while ( (nFStart > 0) && IsFormulaText(m_pCharClass, rFormula, nFStart ))
                nFStart--;
        }

        nFStart++;

        if ( bFound )
        {
            if ( IsFormulaText( m_pCharClass,rFormula, nFStart ) )
            {
                                    //  Function found
                if ( pFuncName )
                    *pFuncName = rFormula.copy( nFStart, nParPos-nFStart );
            }
            else                    // Brackets without function -> keep searching
            {
                bRepeat = true;
                if ( !bBack )
                    nParPos++;
                else if (nParPos > 0)
                    nParPos--;
                else
                    bRepeat = false;
            }
        }
        else                        // No brackets found
        {
            nFStart = FUNC_NOTFOUND;
            if ( pFuncName )
                pFuncName->clear();
        }
    }
    while(bRepeat);

    return nFStart;
}

sal_Int32  FormulaHelper::GetFunctionEnd( const OUString& rStr, sal_Int32 nStart ) const
{
    sal_Int32 nStrLen = rStr.getLength();

    if ( nStrLen < nStart )
        return nStart;

    short   nParCount = 0;
    bool    bInArray = false;
    bool    bFound = false;

    while ( !bFound && (nStart < nStrLen) )
    {
        sal_Unicode c = rStr[nStart];

        if ( c == '"' )
        {
            nStart++;
            while ( (nStart < nStrLen) && rStr[nStart] != '"' )
                nStart++;
        }
        else if ( c == open )
            nParCount++;
        else if ( c == close )
        {
            nParCount--;
            if ( nParCount == 0 )
                bFound = true;
            else if ( nParCount < 0 )
            {
                bFound = true;
                nStart--;   // read one too far
            }
        }
        else if ( c == arrayOpen )
        {
            bInArray = true;
        }
        else if ( c == arrayClose )
        {
            bInArray = false;
        }
        else if ( c == sep )
        {
            if ( !bInArray && nParCount == 0 )
            {
                bFound = true;
                nStart--;   // read one too far
            }
        }
        nStart++; // Set behind found position
    }

    return nStart;
}

sal_Int32 FormulaHelper::GetArgStart( const OUString& rStr, sal_Int32 nStart, sal_uInt16 nArg ) const
{
    sal_Int32 nStrLen = rStr.getLength();

    if ( nStrLen < nStart )
        return nStart;

    short   nParCount   = 0;
    bool    bInArray    = false;
    bool    bFound      = false;

    while ( !bFound && (nStart < nStrLen) )
    {
        sal_Unicode c = rStr[nStart];

        if ( c == '"' )
        {
            nStart++;
            while ( (nStart < nStrLen) && rStr[nStart] != '"' )
                nStart++;
        }
        else if ( c == open )
        {
            bFound = ( nArg == 0 );
            nParCount++;
        }
        else if ( c == close )
        {
            nParCount--;
            bFound = ( nParCount == 0 );
        }
        else if ( c == arrayOpen )
        {
            bInArray = true;
        }
        else if ( c == arrayClose )
        {
            bInArray = false;
        }
        else if ( c == sep )
        {
            if ( !bInArray && nParCount == 1 )
            {
                nArg--;
                bFound = ( nArg == 0  );
            }
        }
        nStart++;
    }

    return nStart;
}

} // formula

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>most likely formulas won't be longer than 64k characters, but...<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include <algorithm>

#include "formula/formulahelper.hxx"
#include <unotools/charclass.hxx>
#include <unotools/syslocale.hxx>

#include <boost/scoped_ptr.hpp>

namespace formula
{

    namespace
    {

        class OEmptyFunctionDescription : public IFunctionDescription
        {
        public:
            OEmptyFunctionDescription(){}
            virtual ~OEmptyFunctionDescription(){}

            virtual OUString getFunctionName() const SAL_OVERRIDE { return OUString(); }
            virtual const IFunctionCategory* getCategory() const SAL_OVERRIDE { return NULL; }
            virtual OUString getDescription() const SAL_OVERRIDE { return OUString(); }
            virtual sal_Int32 getSuppressedArgumentCount() const SAL_OVERRIDE { return 0; }
            virtual OUString getFormula(const ::std::vector< OUString >& ) const SAL_OVERRIDE { return OUString(); }
            virtual void fillVisibleArgumentMapping(::std::vector<sal_uInt16>& ) const SAL_OVERRIDE {}
            virtual void initArgumentInfo()  const SAL_OVERRIDE {}
            virtual OUString getSignature() const SAL_OVERRIDE { return OUString(); }
            virtual OString getHelpId() const SAL_OVERRIDE { return ""; }
            virtual sal_uInt32 getParameterCount() const SAL_OVERRIDE { return 0; }
            virtual OUString getParameterName(sal_uInt32 ) const SAL_OVERRIDE { return OUString(); }
            virtual OUString getParameterDescription(sal_uInt32 ) const SAL_OVERRIDE { return OUString(); }
            virtual bool isParameterOptional(sal_uInt32 ) const SAL_OVERRIDE { return false; }
        };
    }

//  class FormulaHelper - static Method

#define FUNC_NOTFOUND -1

FormulaHelper::FormulaHelper(const IFunctionManager* _pFunctionManager)
    :m_pSysLocale(new SvtSysLocale)
    ,m_pFunctionManager(_pFunctionManager)
    ,open(_pFunctionManager->getSingleToken(IFunctionManager::eOk))
    ,close(_pFunctionManager->getSingleToken(IFunctionManager::eClose))
    ,sep(_pFunctionManager->getSingleToken(IFunctionManager::eSep))
    ,arrayOpen(_pFunctionManager->getSingleToken(IFunctionManager::eArrayOpen))
    ,arrayClose(_pFunctionManager->getSingleToken(IFunctionManager::eArrayClose))
{
    m_pCharClass = m_pSysLocale->GetCharClassPtr();
}

bool FormulaHelper::GetNextFunc( const OUString&  rFormula,
                                     bool             bBack,
                                     sal_Int32&       rFStart,   // Input and output
                                     sal_Int32*       pFEnd,     // = NULL
                                     const IFunctionDescription**   ppFDesc,   // = NULL
                                     ::std::vector< OUString>*   pArgs )  const // = NULL
{
    sal_Int32  nOldStart = rFStart;
    OUString   aFname;

    rFStart = GetFunctionStart( rFormula, rFStart, bBack, ppFDesc ? &aFname : NULL );
    bool bFound  = ( rFStart != FUNC_NOTFOUND );

    if ( bFound )
    {
        if ( pFEnd )
            *pFEnd = GetFunctionEnd( rFormula, rFStart );

        if ( ppFDesc )
        {
            *ppFDesc = NULL;
            const OUString sTemp( aFname );
            const sal_uInt32 nCategoryCount = m_pFunctionManager->getCount();
            for(sal_uInt32 j= 0; j < nCategoryCount && !*ppFDesc; ++j)
            {
                boost::scoped_ptr<const IFunctionCategory> pCategory(m_pFunctionManager->getCategory(j));
                const sal_uInt32 nCount = pCategory->getCount();
                for(sal_uInt32 i = 0 ; i < nCount; ++i)
                {
                    const IFunctionDescription* pCurrent = pCategory->getFunction(i);
                    if ( pCurrent->getFunctionName().equalsIgnoreAsciiCase(sTemp) )
                    {
                        *ppFDesc = pCurrent;
                        break;
                    }
                }// for(sal_uInt32 i = 0 ; i < nCount; ++i)
            }
            if ( *ppFDesc && pArgs )
            {
                GetArgStrings( *pArgs,rFormula, rFStart, static_cast<sal_uInt16>((*ppFDesc)->getParameterCount() ));
            }
            else
            {
                static OEmptyFunctionDescription s_aFunctionDescription;
                *ppFDesc = &s_aFunctionDescription;
            }
        }
    }
    else
        rFStart = nOldStart;

    return bFound;
}

void FormulaHelper::FillArgStrings( const OUString&   rFormula,
                                    sal_Int32         nFuncPos,
                                    sal_uInt16        nArgs,
                                    ::std::vector< OUString >& _rArgs ) const
{
    sal_Int32       nStart  = 0;
    sal_Int32       nEnd    = 0;
    sal_uInt16      i;
    bool        bLast   = false;

    for ( i=0; i<nArgs && !bLast; i++ )
    {
        nStart = GetArgStart( rFormula, nFuncPos, i );

        if ( i+1<nArgs ) // last argument?
        {
            nEnd = GetArgStart( rFormula, nFuncPos, i+1 );

            if ( nEnd != nStart )
                _rArgs.push_back(rFormula.copy( nStart, nEnd-1-nStart ));
            else
                _rArgs.push_back(OUString()), bLast = true;
        }
        else
        {
            nEnd = GetFunctionEnd( rFormula, nFuncPos )-1;
            if ( nStart < nEnd )
                _rArgs.push_back( rFormula.copy( nStart, nEnd-nStart ) );
            else
                _rArgs.push_back(OUString());
        }
    }

    if ( bLast )
        for ( ; i<nArgs; i++ )
            _rArgs.push_back(OUString());
}

void FormulaHelper::GetArgStrings( ::std::vector< OUString >& _rArgs,
                                   const OUString& rFormula,
                                   sal_Int32 nFuncPos,
                                   sal_uInt16 nArgs ) const
{
    if (nArgs)
    {
        FillArgStrings( rFormula, nFuncPos, nArgs, _rArgs );
    }
}

inline bool IsFormulaText( const CharClass* _pCharClass,const OUString& rStr, sal_Int32 nPos )
{
    if( _pCharClass->isLetterNumeric( rStr, nPos ) )
        return true;
    else
    {   // In internationalized versions function names may contain a dot
        //  and in every version also an underscore... ;-)
        sal_Unicode c = rStr[nPos];
        return c == '.' || c == '_';
    }

}

sal_Int32 FormulaHelper::GetFunctionStart( const OUString&   rFormula,
                                            sal_Int32         nStart,
                                            bool              bBack,
                                            OUString*         pFuncName ) const
{
    sal_Int32 nStrLen = rFormula.getLength();

    if ( nStrLen < nStart )
        return nStart;

    sal_Int32  nFStart = FUNC_NOTFOUND;
    sal_Int32  nParPos = bBack ? ::std::min( nStart, nStrLen - 1) : nStart;

    bool bRepeat;
    do
    {
        bool bFound  = false;
        bRepeat = false;

        if ( bBack )
        {
            while ( !bFound && (nParPos > 0) )
            {
                if ( rFormula[nParPos] == '"' )
                {
                    nParPos--;
                    while ( (nParPos > 0) && rFormula[nParPos] != '"' )
                        nParPos--;
                    if (nParPos > 0)
                        nParPos--;
                }
                else if ( (bFound = ( rFormula[nParPos] == '(' ) ) == false )
                    nParPos--;
            }
        }
        else
        {
            while ( !bFound && (nParPos < nStrLen) )
            {
                if ( rFormula[nParPos] == '"' )
                {
                    nParPos++;
                    while ( (nParPos < nStrLen) && rFormula[nParPos] != '"' )
                        nParPos++;
                    nParPos++;
                }
                else if ( (bFound = ( rFormula[nParPos] == '(' ) ) == false )
                    nParPos++;
            }
        }

        if ( bFound && (nParPos > 0) )
        {
            nFStart = nParPos-1;

            while ( (nFStart > 0) && IsFormulaText(m_pCharClass, rFormula, nFStart ))
                nFStart--;
        }

        nFStart++;

        if ( bFound )
        {
            if ( IsFormulaText( m_pCharClass,rFormula, nFStart ) )
            {
                                    //  Function found
                if ( pFuncName )
                    *pFuncName = rFormula.copy( nFStart, nParPos-nFStart );
            }
            else                    // Brackets without function -> keep searching
            {
                bRepeat = true;
                if ( !bBack )
                    nParPos++;
                else if (nParPos > 0)
                    nParPos--;
                else
                    bRepeat = false;
            }
        }
        else                        // No brackets found
        {
            nFStart = FUNC_NOTFOUND;
            if ( pFuncName )
                pFuncName->clear();
        }
    }
    while(bRepeat);

    return nFStart;
}

sal_Int32  FormulaHelper::GetFunctionEnd( const OUString& rStr, sal_Int32 nStart ) const
{
    sal_Int32 nStrLen = rStr.getLength();

    if ( nStrLen < nStart )
        return nStart;

    short   nParCount = 0;
    bool    bInArray = false;
    bool    bFound = false;

    while ( !bFound && (nStart < nStrLen) )
    {
        sal_Unicode c = rStr[nStart];

        if ( c == '"' )
        {
            nStart++;
            while ( (nStart < nStrLen) && rStr[nStart] != '"' )
                nStart++;
        }
        else if ( c == open )
            nParCount++;
        else if ( c == close )
        {
            nParCount--;
            if ( nParCount == 0 )
                bFound = true;
            else if ( nParCount < 0 )
            {
                bFound = true;
                nStart--;   // read one too far
            }
        }
        else if ( c == arrayOpen )
        {
            bInArray = true;
        }
        else if ( c == arrayClose )
        {
            bInArray = false;
        }
        else if ( c == sep )
        {
            if ( !bInArray && nParCount == 0 )
            {
                bFound = true;
                nStart--;   // read one too far
            }
        }
        nStart++; // Set behind found position
    }

    return nStart;
}

sal_Int32 FormulaHelper::GetArgStart( const OUString& rStr, sal_Int32 nStart, sal_uInt16 nArg ) const
{
    sal_Int32 nStrLen = rStr.getLength();

    if ( nStrLen < nStart )
        return nStart;

    short   nParCount   = 0;
    bool    bInArray    = false;
    bool    bFound      = false;

    while ( !bFound && (nStart < nStrLen) )
    {
        sal_Unicode c = rStr[nStart];

        if ( c == '"' )
        {
            nStart++;
            while ( (nStart < nStrLen) && rStr[nStart] != '"' )
                nStart++;
        }
        else if ( c == open )
        {
            bFound = ( nArg == 0 );
            nParCount++;
        }
        else if ( c == close )
        {
            nParCount--;
            bFound = ( nParCount == 0 );
        }
        else if ( c == arrayOpen )
        {
            bInArray = true;
        }
        else if ( c == arrayClose )
        {
            bInArray = false;
        }
        else if ( c == sep )
        {
            if ( !bInArray && nParCount == 1 )
            {
                nArg--;
                bFound = ( nArg == 0  );
            }
        }
        nStart++;
    }

    return nStart;
}

} // formula

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


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

#include "xwalk/application/browser/application.h"

#include <string>

#include "base/files/file_enumerator.h"
#include "base/json/json_reader.h"
#include "base/macros.h"
#include "base/message_loop/message_loop.h"
#include "base/stl_util.h"
#include "base/strings/string_split.h"
#include "base/threading/thread_restrictions.h"
#include "base/values.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/site_instance.h"
#include "net/base/net_util.h"
#include "xwalk/application/common/application_manifest_constants.h"
#include "xwalk/application/common/constants.h"
#include "xwalk/application/common/manifest_handlers/warp_handler.h"
#include "xwalk/runtime/browser/runtime.h"
#include "xwalk/runtime/browser/runtime_ui_delegate.h"
#include "xwalk/runtime/browser/xwalk_browser_context.h"
#include "xwalk/runtime/browser/xwalk_runner.h"

#if defined(OS_TIZEN)
#include "xwalk/application/browser/application_tizen.h"
#endif

using content::RenderProcessHost;

namespace xwalk {

namespace keys = application_manifest_keys;
namespace widget_keys = application_widget_keys;

namespace {
const char* kDefaultWidgetEntryPage[] = {
"index.html",
"index.htm",
"index.svg",
"index.xhtml",
"index.xht"};

GURL GetDefaultWidgetEntryPage(
    scoped_refptr<xwalk::application::ApplicationData> data) {
  base::ThreadRestrictions::SetIOAllowed(true);
  base::FileEnumerator iter(
      data->path(), true,
      base::FileEnumerator::FILES,
      FILE_PATH_LITERAL("index.*"));
  size_t priority = arraysize(kDefaultWidgetEntryPage);
  std::string source;

  for (base::FilePath file = iter.Next(); !file.empty(); file = iter.Next()) {
    for (size_t i = 0; i < arraysize(kDefaultWidgetEntryPage); ++i) {
      if (file.BaseName().MaybeAsASCII() == kDefaultWidgetEntryPage[i] &&
          i < priority) {
        source = kDefaultWidgetEntryPage[i];
        priority = i;
      }
    }
  }

  return source.empty() ? GURL() : data->GetResourceURL(source);
}

}  // namespace

namespace application {

scoped_ptr<Application> Application::Create(
    scoped_refptr<ApplicationData> data,
    XWalkBrowserContext* context) {
#if defined(OS_TIZEN)
  return make_scoped_ptr<Application>(new ApplicationTizen(data, context));
#else
  return make_scoped_ptr(new Application(data, context));
#endif
}

Application::Application(
    scoped_refptr<ApplicationData> data,
    XWalkBrowserContext* browser_context)
    : data_(data),
      render_process_host_(NULL),
      web_contents_(NULL),
      security_mode_enabled_(false),
      browser_context_(browser_context),
      observer_(NULL),
      remote_debugging_enabled_(false),
      weak_factory_(this) {
  DCHECK(browser_context_);
  DCHECK(data_.get());
}

Application::~Application() {
  Terminate();
  if (render_process_host_)
    render_process_host_->RemoveObserver(this);
}

template<>
GURL Application::GetStartURL<Manifest::TYPE_WIDGET>() {
#if defined(OS_TIZEN)
  if (data_->IsHostedApp()) {
    std::string source;
    GURL url;
    if (data_->GetManifest()->GetString(
        widget_keys::kLaunchLocalPathKey, &source)) {
      url = GURL(source);
    }

    if (url.is_valid() && url.SchemeIsHTTPOrHTTPS())
      return url;
  }
#endif

  GURL url = GetAbsoluteURLFromKey(widget_keys::kLaunchLocalPathKey);
  if (url.is_valid())
    return url;

  LOG(WARNING) << "Failed to find start URL from the 'config.xml'"
               << "trying to find default entry page.";
  url = GetDefaultWidgetEntryPage(data_);
  if (url.is_valid())
    return url;

  LOG(WARNING) << "Failed to find a valid start URL in the manifest.";
  return GURL();
}

template<>
GURL Application::GetStartURL<Manifest::TYPE_MANIFEST>() {
  if (data_->IsHostedApp()) {
    std::string source;
    // Not trying to get a relative path for the "fake" application.
    if (data_->GetManifest()->GetString(keys::kStartURLKey, &source))
      return GURL(source);
    return GURL();
  }

  GURL url = GetAbsoluteURLFromKey(keys::kStartURLKey);
  if (url.is_valid())
    return url;

  url = GetAbsoluteURLFromKey(keys::kLaunchLocalPathKey);
  if (url.is_valid())
    return url;

  url = GetAbsoluteURLFromKey(keys::kDeprecatedURLKey);
  if (url.is_valid()) {
    LOG(WARNING) << "Deprecated key '" << keys::kDeprecatedURLKey
        << "' found. Please migrate to using '" << keys::kStartURLKey
        << "' instead.";
    return url;
  }

  LOG(WARNING) << "Failed to find a valid start URL in the manifest.";
  return GURL();
}

template<>
ui::WindowShowState Application::GetWindowShowState<Manifest::TYPE_WIDGET>(
    const LaunchParams& params) {
  if (params.force_fullscreen)
    return ui::SHOW_STATE_FULLSCREEN;

  const Manifest* manifest = data_->GetManifest();
  std::string view_modes_string;
  if (manifest->GetString(widget_keys::kViewModesKey, &view_modes_string)) {
    // FIXME: ATM only 'fullscreen' and 'windowed' values are supported.
    // If the first user prefererence is 'fullscreen', set window show state
    // FULLSCREEN, otherwise set the default window show state.
    std::vector<std::string> modes;
    base::SplitString(view_modes_string, ' ', &modes);
    if (!modes.empty() && modes[0] == "fullscreen")
      return ui::SHOW_STATE_FULLSCREEN;
  }

  return ui::SHOW_STATE_DEFAULT;
}

template<>
ui::WindowShowState Application::GetWindowShowState<Manifest::TYPE_MANIFEST>(
    const LaunchParams& params) {
  if (params.force_fullscreen)
    return ui::SHOW_STATE_FULLSCREEN;

  const Manifest* manifest = data_->GetManifest();
  std::string display_string;
  if (manifest->GetString(keys::kDisplay, &display_string)) {
    // FIXME: ATM only 'fullscreen' and 'standalone' (which is fallback value)
    // values are supported.
    if (display_string.find("fullscreen") != std::string::npos)
      return ui::SHOW_STATE_FULLSCREEN;
  }

  return ui::SHOW_STATE_DEFAULT;
}

bool Application::Launch(const LaunchParams& launch_params) {
  if (!runtimes_.empty()) {
    LOG(ERROR) << "Attempt to launch app with id " << id()
               << ", but it is already running.";
    return false;
  }

  CHECK(!render_process_host_);
  bool is_wgt = data_->manifest_type() == Manifest::TYPE_WIDGET;

  GURL url = is_wgt ? GetStartURL<Manifest::TYPE_WIDGET>() :
                      GetStartURL<Manifest::TYPE_MANIFEST>();
  if (!url.is_valid())
    return false;

  remote_debugging_enabled_ = launch_params.remote_debugging;
  auto site = content::SiteInstance::CreateForURL(browser_context_, url);
  Runtime* runtime = Runtime::Create(browser_context_, site);
  runtime->set_observer(this);
  runtime->set_remote_debugging_enabled(remote_debugging_enabled_);
  runtimes_.push_back(runtime);
  render_process_host_ = runtime->GetRenderProcessHost();
  render_process_host_->AddObserver(this);
  web_contents_ = runtime->web_contents();
  InitSecurityPolicy();
  runtime->LoadURL(url);

  NativeAppWindow::CreateParams params;
  params.net_wm_pid = launch_params.launcher_pid;
  params.state = is_wgt ?
      GetWindowShowState<Manifest::TYPE_WIDGET>(launch_params) :
      GetWindowShowState<Manifest::TYPE_MANIFEST>(launch_params);

  window_show_params_ = params;
  // Only the first runtime can have a launch screen.
  params.splash_screen_path = GetSplashScreenPath();
  runtime->set_ui_delegate(DefaultRuntimeUIDelegate::Create(runtime, params));
  // We call "Show" after RP is initialized to reduce
  // the application start up time.

  return true;
}

GURL Application::GetAbsoluteURLFromKey(const std::string& key) {
  const Manifest* manifest = data_->GetManifest();
  std::string source;

  if (!manifest->GetString(key, &source) || source.empty())
    return GURL();

  return data_->GetResourceURL(source);
}

void Application::Terminate() {
  std::vector<Runtime*> to_be_closed(runtimes_.get());
  for (Runtime* runtime : to_be_closed)
    runtime->Close();
}

int Application::GetRenderProcessHostID() const {
  DCHECK(render_process_host_);
  return render_process_host_->GetID();
}

void Application::OnNewRuntimeAdded(Runtime* runtime) {
  runtime->set_remote_debugging_enabled(remote_debugging_enabled_);
  runtime->set_observer(this);
  runtime->set_ui_delegate(
      DefaultRuntimeUIDelegate::Create(runtime, window_show_params_));
  runtime->Show();
  runtimes_.push_back(runtime);
}

void Application::OnRuntimeClosed(Runtime* runtime) {
  auto found = std::find(runtimes_.begin(), runtimes_.end(), runtime);
  CHECK(found != runtimes_.end());
  LOG(INFO) << "Application::OnRuntimeClosed " << runtime;
  runtimes_.erase(found);

  if (runtimes_.empty())
    base::MessageLoop::current()->PostTask(FROM_HERE,
        base::Bind(&Application::NotifyTermination,
                   weak_factory_.GetWeakPtr()));
}

void Application::RenderProcessExited(RenderProcessHost* host,
                                      base::ProcessHandle,
                                      base::TerminationStatus,
                                      int) {
  DCHECK(render_process_host_ == host);
  VLOG(1) << "RenderProcess id: " << host->GetID() << " is gone!";
  XWalkRunner::GetInstance()->OnRenderProcessHostGone(host);
}

void Application::RenderProcessHostDestroyed(RenderProcessHost* host) {
  DCHECK(render_process_host_ == host);
  render_process_host_ = NULL;
  web_contents_ = NULL;
}

void Application::NotifyTermination() {
  CHECK(!render_process_host_);
  if (observer_)
    observer_->OnApplicationTerminated(this);
}

void Application::RenderChannelCreated() {
  CHECK(!runtimes_.empty());
  runtimes_.front()->Show();
}

bool Application::UseExtension(const std::string& extension_name) const {
  // TODO(Bai): Tells whether the application contains the specified extension
  return true;
}

bool Application::RegisterPermissions(const std::string& extension_name,
                                      const std::string& perm_table) {
  // TODO(Bai): Parse the permission table and fill in the name_perm_map_
  // The perm_table format is a simple JSON string, like
  // [{"permission_name":"echo","apis":["add","remove","get"]}]
  scoped_ptr<base::Value> root;
  root.reset(base::JSONReader().ReadToValue(perm_table));
  if (root.get() == NULL || !root->IsType(base::Value::TYPE_LIST))
    return false;

  base::ListValue* permission_list = static_cast<base::ListValue*>(root.get());
  if (permission_list->GetSize() == 0)
    return false;

  for (base::ListValue::const_iterator iter = permission_list->begin();
      iter != permission_list->end(); ++iter) {
    if (!(*iter)->IsType(base::Value::TYPE_DICTIONARY))
        return false;

    base::DictionaryValue* dict_val =
        static_cast<base::DictionaryValue*>(*iter);
    std::string permission_name;
    if (!dict_val->GetString("permission_name", &permission_name))
      return false;

    base::ListValue* api_list = NULL;
    if (!dict_val->GetList("apis", &api_list))
      return false;

    for (base::ListValue::const_iterator api_iter = api_list->begin();
        api_iter != api_list->end(); ++api_iter) {
      std::string api;
      if (!((*api_iter)->IsType(base::Value::TYPE_STRING)
          && (*api_iter)->GetAsString(&api)))
        return false;
      // register the permission and api
      name_perm_map_[api] = permission_name;
      DLOG(INFO) << "Permission Registered [PERM] " << permission_name
                 << " [API] " << api;
    }
  }

  return true;
}

std::string Application::GetRegisteredPermissionName(
    const std::string& extension_name,
    const std::string& api_name) const {
  std::map<std::string, std::string>::const_iterator iter =
      name_perm_map_.find(api_name);
  if (iter == name_perm_map_.end())
    return std::string("");
  return iter->second;
}

StoredPermission Application::GetPermission(PermissionType type,
                               const std::string& permission_name) const {
  if (type == SESSION_PERMISSION) {
    StoredPermissionMap::const_iterator iter =
        permission_map_.find(permission_name);
    if (iter == permission_map_.end())
      return UNDEFINED_STORED_PERM;
    return iter->second;
  }
  if (type == PERSISTENT_PERMISSION) {
    return data_->GetPermission(permission_name);
  }
  NOTREACHED();
  return UNDEFINED_STORED_PERM;
}

bool Application::SetPermission(PermissionType type,
                                const std::string& permission_name,
                                StoredPermission perm) {
  if (type == SESSION_PERMISSION) {
    permission_map_[permission_name] = perm;
    return true;
  }
  if (type == PERSISTENT_PERMISSION)
    return data_->SetPermission(permission_name, perm);

  NOTREACHED();
  return false;
}

void Application::InitSecurityPolicy() {
  // CSP policy takes precedence over WARP.
  if (data_->HasCSPDefined())
    security_policy_.reset(new ApplicationSecurityPolicyCSP(this));
  else if (data_->manifest_type() == Manifest::TYPE_WIDGET)
    security_policy_.reset(new ApplicationSecurityPolicyWARP(this));

  if (security_policy_)
    security_policy_->Enforce();
}

bool Application::CanRequestURL(const GURL& url) const {
  if (security_policy_)
    return security_policy_->IsAccessAllowed(url);
  return true;
}

base::FilePath Application::GetSplashScreenPath() {
  return base::FilePath();
}

}  // namespace application
}  // namespace xwalk
<commit_msg>Speed up GetDefaultWidgetEntryPage function<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "xwalk/application/browser/application.h"

#include <string>

#include "base/files/file_enumerator.h"
#include "base/json/json_reader.h"
#include "base/macros.h"
#include "base/message_loop/message_loop.h"
#include "base/stl_util.h"
#include "base/strings/string_split.h"
#include "base/threading/thread_restrictions.h"
#include "base/values.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/site_instance.h"
#include "net/base/net_util.h"
#include "xwalk/application/common/application_manifest_constants.h"
#include "xwalk/application/common/constants.h"
#include "xwalk/application/common/manifest_handlers/warp_handler.h"
#include "xwalk/runtime/browser/runtime.h"
#include "xwalk/runtime/browser/runtime_ui_delegate.h"
#include "xwalk/runtime/browser/xwalk_browser_context.h"
#include "xwalk/runtime/browser/xwalk_runner.h"

#if defined(OS_TIZEN)
#include "xwalk/application/browser/application_tizen.h"
#endif

using content::RenderProcessHost;

namespace xwalk {

namespace keys = application_manifest_keys;
namespace widget_keys = application_widget_keys;

namespace {
const char* kDefaultWidgetEntryPage[] = {
"index.html",
"index.htm",
"index.svg",
"index.xhtml",
"index.xht"};

GURL GetDefaultWidgetEntryPage(
    scoped_refptr<xwalk::application::ApplicationData> data) {
  base::ThreadRestrictions::SetIOAllowed(true);
  base::FileEnumerator iter(
      data->path(), true,
      base::FileEnumerator::FILES,
      FILE_PATH_LITERAL("index.*"));
  size_t priority = arraysize(kDefaultWidgetEntryPage);
  std::string source;

  for (base::FilePath file = iter.Next(); !file.empty(); file = iter.Next()) {
    for (size_t i = 0; i < priority; ++i) {
      if (file.BaseName().MaybeAsASCII() == kDefaultWidgetEntryPage[i]) {
        source = kDefaultWidgetEntryPage[i];
        priority = i;
        break;
      }
    }
    if (!priority)
      break;
  }

  return source.empty() ? GURL() : data->GetResourceURL(source);
}

}  // namespace

namespace application {

scoped_ptr<Application> Application::Create(
    scoped_refptr<ApplicationData> data,
    XWalkBrowserContext* context) {
#if defined(OS_TIZEN)
  return make_scoped_ptr<Application>(new ApplicationTizen(data, context));
#else
  return make_scoped_ptr(new Application(data, context));
#endif
}

Application::Application(
    scoped_refptr<ApplicationData> data,
    XWalkBrowserContext* browser_context)
    : data_(data),
      render_process_host_(NULL),
      web_contents_(NULL),
      security_mode_enabled_(false),
      browser_context_(browser_context),
      observer_(NULL),
      remote_debugging_enabled_(false),
      weak_factory_(this) {
  DCHECK(browser_context_);
  DCHECK(data_.get());
}

Application::~Application() {
  Terminate();
  if (render_process_host_)
    render_process_host_->RemoveObserver(this);
}

template<>
GURL Application::GetStartURL<Manifest::TYPE_WIDGET>() {
#if defined(OS_TIZEN)
  if (data_->IsHostedApp()) {
    std::string source;
    GURL url;
    if (data_->GetManifest()->GetString(
        widget_keys::kLaunchLocalPathKey, &source)) {
      url = GURL(source);
    }

    if (url.is_valid() && url.SchemeIsHTTPOrHTTPS())
      return url;
  }
#endif

  GURL url = GetAbsoluteURLFromKey(widget_keys::kLaunchLocalPathKey);
  if (url.is_valid())
    return url;

  LOG(WARNING) << "Failed to find start URL from the 'config.xml'"
               << "trying to find default entry page.";
  url = GetDefaultWidgetEntryPage(data_);
  if (url.is_valid())
    return url;

  LOG(WARNING) << "Failed to find a valid start URL in the manifest.";
  return GURL();
}

template<>
GURL Application::GetStartURL<Manifest::TYPE_MANIFEST>() {
  if (data_->IsHostedApp()) {
    std::string source;
    // Not trying to get a relative path for the "fake" application.
    if (data_->GetManifest()->GetString(keys::kStartURLKey, &source))
      return GURL(source);
    return GURL();
  }

  GURL url = GetAbsoluteURLFromKey(keys::kStartURLKey);
  if (url.is_valid())
    return url;

  url = GetAbsoluteURLFromKey(keys::kLaunchLocalPathKey);
  if (url.is_valid())
    return url;

  url = GetAbsoluteURLFromKey(keys::kDeprecatedURLKey);
  if (url.is_valid()) {
    LOG(WARNING) << "Deprecated key '" << keys::kDeprecatedURLKey
        << "' found. Please migrate to using '" << keys::kStartURLKey
        << "' instead.";
    return url;
  }

  LOG(WARNING) << "Failed to find a valid start URL in the manifest.";
  return GURL();
}

template<>
ui::WindowShowState Application::GetWindowShowState<Manifest::TYPE_WIDGET>(
    const LaunchParams& params) {
  if (params.force_fullscreen)
    return ui::SHOW_STATE_FULLSCREEN;

  const Manifest* manifest = data_->GetManifest();
  std::string view_modes_string;
  if (manifest->GetString(widget_keys::kViewModesKey, &view_modes_string)) {
    // FIXME: ATM only 'fullscreen' and 'windowed' values are supported.
    // If the first user prefererence is 'fullscreen', set window show state
    // FULLSCREEN, otherwise set the default window show state.
    std::vector<std::string> modes;
    base::SplitString(view_modes_string, ' ', &modes);
    if (!modes.empty() && modes[0] == "fullscreen")
      return ui::SHOW_STATE_FULLSCREEN;
  }

  return ui::SHOW_STATE_DEFAULT;
}

template<>
ui::WindowShowState Application::GetWindowShowState<Manifest::TYPE_MANIFEST>(
    const LaunchParams& params) {
  if (params.force_fullscreen)
    return ui::SHOW_STATE_FULLSCREEN;

  const Manifest* manifest = data_->GetManifest();
  std::string display_string;
  if (manifest->GetString(keys::kDisplay, &display_string)) {
    // FIXME: ATM only 'fullscreen' and 'standalone' (which is fallback value)
    // values are supported.
    if (display_string.find("fullscreen") != std::string::npos)
      return ui::SHOW_STATE_FULLSCREEN;
  }

  return ui::SHOW_STATE_DEFAULT;
}

bool Application::Launch(const LaunchParams& launch_params) {
  if (!runtimes_.empty()) {
    LOG(ERROR) << "Attempt to launch app with id " << id()
               << ", but it is already running.";
    return false;
  }

  CHECK(!render_process_host_);
  bool is_wgt = data_->manifest_type() == Manifest::TYPE_WIDGET;

  GURL url = is_wgt ? GetStartURL<Manifest::TYPE_WIDGET>() :
                      GetStartURL<Manifest::TYPE_MANIFEST>();
  if (!url.is_valid())
    return false;

  remote_debugging_enabled_ = launch_params.remote_debugging;
  auto site = content::SiteInstance::CreateForURL(browser_context_, url);
  Runtime* runtime = Runtime::Create(browser_context_, site);
  runtime->set_observer(this);
  runtime->set_remote_debugging_enabled(remote_debugging_enabled_);
  runtimes_.push_back(runtime);
  render_process_host_ = runtime->GetRenderProcessHost();
  render_process_host_->AddObserver(this);
  web_contents_ = runtime->web_contents();
  InitSecurityPolicy();
  runtime->LoadURL(url);

  NativeAppWindow::CreateParams params;
  params.net_wm_pid = launch_params.launcher_pid;
  params.state = is_wgt ?
      GetWindowShowState<Manifest::TYPE_WIDGET>(launch_params) :
      GetWindowShowState<Manifest::TYPE_MANIFEST>(launch_params);

  window_show_params_ = params;
  // Only the first runtime can have a launch screen.
  params.splash_screen_path = GetSplashScreenPath();
  runtime->set_ui_delegate(DefaultRuntimeUIDelegate::Create(runtime, params));
  // We call "Show" after RP is initialized to reduce
  // the application start up time.

  return true;
}

GURL Application::GetAbsoluteURLFromKey(const std::string& key) {
  const Manifest* manifest = data_->GetManifest();
  std::string source;

  if (!manifest->GetString(key, &source) || source.empty())
    return GURL();

  return data_->GetResourceURL(source);
}

void Application::Terminate() {
  std::vector<Runtime*> to_be_closed(runtimes_.get());
  for (Runtime* runtime : to_be_closed)
    runtime->Close();
}

int Application::GetRenderProcessHostID() const {
  DCHECK(render_process_host_);
  return render_process_host_->GetID();
}

void Application::OnNewRuntimeAdded(Runtime* runtime) {
  runtime->set_remote_debugging_enabled(remote_debugging_enabled_);
  runtime->set_observer(this);
  runtime->set_ui_delegate(
      DefaultRuntimeUIDelegate::Create(runtime, window_show_params_));
  runtime->Show();
  runtimes_.push_back(runtime);
}

void Application::OnRuntimeClosed(Runtime* runtime) {
  auto found = std::find(runtimes_.begin(), runtimes_.end(), runtime);
  CHECK(found != runtimes_.end());
  LOG(INFO) << "Application::OnRuntimeClosed " << runtime;
  runtimes_.erase(found);

  if (runtimes_.empty())
    base::MessageLoop::current()->PostTask(FROM_HERE,
        base::Bind(&Application::NotifyTermination,
                   weak_factory_.GetWeakPtr()));
}

void Application::RenderProcessExited(RenderProcessHost* host,
                                      base::ProcessHandle,
                                      base::TerminationStatus,
                                      int) {
  DCHECK(render_process_host_ == host);
  VLOG(1) << "RenderProcess id: " << host->GetID() << " is gone!";
  XWalkRunner::GetInstance()->OnRenderProcessHostGone(host);
}

void Application::RenderProcessHostDestroyed(RenderProcessHost* host) {
  DCHECK(render_process_host_ == host);
  render_process_host_ = NULL;
  web_contents_ = NULL;
}

void Application::NotifyTermination() {
  CHECK(!render_process_host_);
  if (observer_)
    observer_->OnApplicationTerminated(this);
}

void Application::RenderChannelCreated() {
  CHECK(!runtimes_.empty());
  runtimes_.front()->Show();
}

bool Application::UseExtension(const std::string& extension_name) const {
  // TODO(Bai): Tells whether the application contains the specified extension
  return true;
}

bool Application::RegisterPermissions(const std::string& extension_name,
                                      const std::string& perm_table) {
  // TODO(Bai): Parse the permission table and fill in the name_perm_map_
  // The perm_table format is a simple JSON string, like
  // [{"permission_name":"echo","apis":["add","remove","get"]}]
  scoped_ptr<base::Value> root;
  root.reset(base::JSONReader().ReadToValue(perm_table));
  if (root.get() == NULL || !root->IsType(base::Value::TYPE_LIST))
    return false;

  base::ListValue* permission_list = static_cast<base::ListValue*>(root.get());
  if (permission_list->GetSize() == 0)
    return false;

  for (base::ListValue::const_iterator iter = permission_list->begin();
      iter != permission_list->end(); ++iter) {
    if (!(*iter)->IsType(base::Value::TYPE_DICTIONARY))
      return false;

    base::DictionaryValue* dict_val =
        static_cast<base::DictionaryValue*>(*iter);
    std::string permission_name;
    if (!dict_val->GetString("permission_name", &permission_name))
      return false;

    base::ListValue* api_list = NULL;
    if (!dict_val->GetList("apis", &api_list))
      return false;

    for (base::ListValue::const_iterator api_iter = api_list->begin();
        api_iter != api_list->end(); ++api_iter) {
      std::string api;
      if (!((*api_iter)->IsType(base::Value::TYPE_STRING)
          && (*api_iter)->GetAsString(&api)))
        return false;
      // register the permission and api
      name_perm_map_[api] = permission_name;
      DLOG(INFO) << "Permission Registered [PERM] " << permission_name
                 << " [API] " << api;
    }
  }

  return true;
}

std::string Application::GetRegisteredPermissionName(
    const std::string& extension_name,
    const std::string& api_name) const {
  std::map<std::string, std::string>::const_iterator iter =
      name_perm_map_.find(api_name);
  if (iter == name_perm_map_.end())
    return std::string();
  return iter->second;
}

StoredPermission Application::GetPermission(PermissionType type,
    const std::string& permission_name) const {
  if (type == SESSION_PERMISSION) {
    StoredPermissionMap::const_iterator iter =
        permission_map_.find(permission_name);
    if (iter == permission_map_.end())
      return UNDEFINED_STORED_PERM;
    return iter->second;
  }
  if (type == PERSISTENT_PERMISSION) {
    return data_->GetPermission(permission_name);
  }
  NOTREACHED();
  return UNDEFINED_STORED_PERM;
}

bool Application::SetPermission(PermissionType type,
                                const std::string& permission_name,
                                StoredPermission perm) {
  if (type == SESSION_PERMISSION) {
    permission_map_[permission_name] = perm;
    return true;
  }
  if (type == PERSISTENT_PERMISSION)
    return data_->SetPermission(permission_name, perm);

  NOTREACHED();
  return false;
}

void Application::InitSecurityPolicy() {
  // CSP policy takes precedence over WARP.
  if (data_->HasCSPDefined())
    security_policy_.reset(new ApplicationSecurityPolicyCSP(this));
  else if (data_->manifest_type() == Manifest::TYPE_WIDGET)
    security_policy_.reset(new ApplicationSecurityPolicyWARP(this));

  if (security_policy_)
    security_policy_->Enforce();
}

bool Application::CanRequestURL(const GURL& url) const {
  if (security_policy_)
    return security_policy_->IsAccessAllowed(url);
  return true;
}

base::FilePath Application::GetSplashScreenPath() {
  return base::FilePath();
}

}  // namespace application
}  // namespace xwalk
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: menuconfiguration.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 00:53:09 $
 *
 *  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
 *
 ************************************************************************/

#ifndef __FRAMEWORK_XML_MENUCONFIGURATION_HXX_
#define __FRAMEWORK_XML_MENUCONFIGURATION_HXX_

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_WRAPPEDTARGETEXCEPTION_HPP_
#include <com/sun/star/lang/WrappedTargetException.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXCONTAINER_HPP_
#include <com/sun/star/container/XIndexContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_
#include <com/sun/star/container/XIndexAccess.hpp>
#endif

//_________________________________________________________________________________________________________________
//  includes of other projects
//_________________________________________________________________________________________________________________

#include <vcl/menu.hxx>
#include <vcl/toolbox.hxx>

#define BOOKMARK_NEWMENU        ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "private:menu_bookmark_new" ))
#define BOOKMARK_WIZARDMENU     ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "private:menu_bookmark_wizard" ))
#define ADDONS_POPUPMENU        ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "private:menu_addons_popup" ))

// Prepare for inclusion by framework and sfx
// Please consider that there is a corresponding define also in sfxsids.hrc!! (SID_SFX_START)/(SID_ADDONS)
#define FWK_SID_SFX_START 5000
#define FWK_SID_ADDONS (FWK_SID_SFX_START+1678)
#define FWK_SID_ADDONHELP (FWK_SID_SFX_START+1684)

const USHORT START_ITEMID_PICKLIST      = 4500;
const USHORT END_ITEMID_PICKLIST        = 4599;
const USHORT MAX_ITEMCOUNT_PICKLIST     =   99; // difference between START_... & END_... for picklist / must be changed too, if these values are changed!
const USHORT START_ITEMID_WINDOWLIST    = 4600;
const USHORT END_ITEMID_WINDOWLIST      = 4699;
const USHORT ITEMID_ADDONLIST           = FWK_SID_ADDONS;
const USHORT ITEMID_ADDONHELP           = FWK_SID_ADDONHELP;

namespace framework
{

class MenuConfiguration
{
    public:
        struct Attributes
        {
            Attributes( const ::rtl::OUString& aFrame, const ::rtl::OUString& aImageIdStr ) :
                aTargetFrame( aFrame ), aImageId( aImageIdStr ) {}

            ::rtl::OUString aTargetFrame;
            ::rtl::OUString aImageId;
        };

        MenuConfiguration(
            // #110897#-1 use const when giving a uno reference by reference
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& rServiceManager );

        virtual ~MenuConfiguration();

        ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess > CreateMenuBarConfigurationFromXML(
            ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& rInputStream )
            throw ( ::com::sun::star::lang::WrappedTargetException );

        PopupMenu* CreateBookmarkMenu(
                ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame,
                const ::rtl::OUString& aURL )
            throw ( ::com::sun::star::lang::WrappedTargetException );

        ToolBox* CreateToolBoxFromConfiguration(
            ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& rInputStream )
            throw ( ::com::sun::star::lang::WrappedTargetException );

        void StoreMenuBarConfigurationToXML( ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& rMenuBarConfiguration,
                      ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >& rOutputStream )
            throw ( ::com::sun::star::lang::WrappedTargetException );

        void StoreToolBox( ToolBox* pToolBox,
                      ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >& rOutputStream )
            throw ( ::com::sun::star::lang::WrappedTargetException );

        static BOOL IsPickListItemId( USHORT nId );
        static BOOL IsWindowListItemId( USHORT nId );

    private:
        // #110897#-1 do not hold the uno reference by reference
        const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& m_rxServiceManager;
};

}

#endif // __FRAMEWORK_XML_MENUCONFIGURATION_HXX_
<commit_msg>INTEGRATION: CWS chart2mst3 (1.4.16); FILE MERGED 2006/10/27 07:25:05 cd 1.4.16.1: #i65734# Support menu merging with non-sfx based application modules using provided dispatch providers<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: menuconfiguration.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-22 15:26:26 $
 *
 *  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
 *
 ************************************************************************/

#ifndef __FRAMEWORK_XML_MENUCONFIGURATION_HXX_
#define __FRAMEWORK_XML_MENUCONFIGURATION_HXX_

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_WRAPPEDTARGETEXCEPTION_HPP_
#include <com/sun/star/lang/WrappedTargetException.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXCONTAINER_HPP_
#include <com/sun/star/container/XIndexContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_
#include <com/sun/star/container/XIndexAccess.hpp>
#endif
#include <com/sun/star/frame/XDispatchProvider.hpp>

//_________________________________________________________________________________________________________________
//  includes of other projects
//_________________________________________________________________________________________________________________

#include <cppuhelper/weak.hxx>
#include <vcl/menu.hxx>
#include <vcl/toolbox.hxx>

#define BOOKMARK_NEWMENU        ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "private:menu_bookmark_new" ))
#define BOOKMARK_WIZARDMENU     ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "private:menu_bookmark_wizard" ))
#define ADDONS_POPUPMENU        ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "private:menu_addons_popup" ))

// Prepare for inclusion by framework and sfx
// Please consider that there is a corresponding define also in sfxsids.hrc!! (SID_SFX_START)/(SID_ADDONS)
#define FWK_SID_SFX_START 5000
#define FWK_SID_ADDONS (FWK_SID_SFX_START+1678)
#define FWK_SID_ADDONHELP (FWK_SID_SFX_START+1684)

const USHORT START_ITEMID_PICKLIST      = 4500;
const USHORT END_ITEMID_PICKLIST        = 4599;
const USHORT MAX_ITEMCOUNT_PICKLIST     =   99; // difference between START_... & END_... for picklist / must be changed too, if these values are changed!
const USHORT START_ITEMID_WINDOWLIST    = 4600;
const USHORT END_ITEMID_WINDOWLIST      = 4699;
const USHORT ITEMID_ADDONLIST           = FWK_SID_ADDONS;
const USHORT ITEMID_ADDONHELP           = FWK_SID_ADDONHELP;

namespace framework
{

class MenuConfiguration
{
    public:
        struct Attributes
        {
            Attributes() {}
            Attributes( const ::rtl::OUString& aFrame, const ::rtl::OUString& aImageIdStr ) :
                aTargetFrame( aFrame ), aImageId( aImageIdStr ) {}

            ::rtl::OUString aTargetFrame;
            ::rtl::OUString aImageId;
            ::com::sun::star::uno::WeakReference< ::com::sun::star::frame::XDispatchProvider > xDispatchProvider;
        };

        MenuConfiguration(
            // #110897#-1 use const when giving a uno reference by reference
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& rServiceManager );

        virtual ~MenuConfiguration();

        ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess > CreateMenuBarConfigurationFromXML(
            ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& rInputStream )
            throw ( ::com::sun::star::lang::WrappedTargetException );

        PopupMenu* CreateBookmarkMenu(
                ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame,
                const ::rtl::OUString& aURL )
            throw ( ::com::sun::star::lang::WrappedTargetException );

        ToolBox* CreateToolBoxFromConfiguration(
            ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& rInputStream )
            throw ( ::com::sun::star::lang::WrappedTargetException );

        void StoreMenuBarConfigurationToXML( ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& rMenuBarConfiguration,
                      ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >& rOutputStream )
            throw ( ::com::sun::star::lang::WrappedTargetException );

        void StoreToolBox( ToolBox* pToolBox,
                      ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >& rOutputStream )
            throw ( ::com::sun::star::lang::WrappedTargetException );

        static BOOL IsPickListItemId( USHORT nId );
        static BOOL IsWindowListItemId( USHORT nId );

    private:
        // #110897#-1 do not hold the uno reference by reference
        const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& m_rxServiceManager;
};

}

#endif // __FRAMEWORK_XML_MENUCONFIGURATION_HXX_
<|endoftext|>


<commit_before>// SciTE - Scintilla based Text Editor
// LexBullant.cxx - lexer for Bullant

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"

static int classifyWordBullant(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) {
	char s[100];
	for (unsigned int i = 0; i < end - start + 1 && i < 30; i++) {
		s[i] = static_cast<char>(tolower(styler[start + i]));
		s[i + 1] = '\0';
	}
	int lev= 0;
	char chAttr = SCE_C_IDENTIFIER;
	if (isdigit(s[0]) || (s[0] == '.')){
		chAttr = SCE_C_NUMBER;
	}
	else {
		if (keywords.InList(s)) {
			chAttr = SCE_C_WORD;
/*			if (strcmp(s, "end method") == 0 ||
				strcmp(s, "end case") == 0 ||
				strcmp(s, "end class") == 0 ||
				strcmp(s, "end debug") == 0 ||
				strcmp(s, "end test") == 0 ||
				strcmp(s, "end if") == 0 ||
				strcmp(s, "end lock") == 0 ||
				strcmp(s, "end transaction") == 0 ||
				strcmp(s, "end trap") == 0 ||
				strcmp(s, "end until") == 0 ||
				strcmp(s, "end while") == 0)
				lev = -1;*/
			if (strcmp(s, "end") == 0)
				lev = -1;
			else if (strcmp(s, "method") == 0 ||
				strcmp(s, "case") == 0 ||
				strcmp(s, "class") == 0 ||
				strcmp(s, "debug") == 0 ||
				strcmp(s, "test") == 0 ||
				strcmp(s, "if") == 0 ||
				strcmp(s, "lock") == 0 ||
				strcmp(s, "transaction") == 0 ||
				strcmp(s, "trap") == 0 ||
				strcmp(s, "until") == 0 ||
				strcmp(s, "while") == 0)
				lev = 1;
		}
	}
	styler.ColourTo(end, chAttr);
	return lev;
}

static void ColouriseBullantDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
	Accessor &styler) {
	WordList &keywords = *keywordlists[0];

	styler.StartAt(startPos);

	bool fold = styler.GetPropertyInt("fold") != 0;
	int lineCurrent = styler.GetLine(startPos);
	int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
	int levelCurrent = levelPrev;

	int state = initStyle;
	if (state == SCE_C_STRINGEOL)	// Does not leak onto next line
		state = SCE_C_DEFAULT;
	char chPrev = ' ';
	char chNext = styler[startPos];
	unsigned int lengthDoc = startPos + length;
	int visibleChars = 0;
	// int blockChange = 0;
	styler.StartSegment(startPos);
	int endFoundThisLine = 0;
	for (unsigned int i = startPos; i < lengthDoc; i++) {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);

		if ((ch == '\r' && chNext != '\n') || (ch == '\n')) {
			// Trigger on CR only (Mac style) or either on LF from CR+LF (Dos/Win) or on LF alone (Unix)
			// Avoid triggering two times on Dos/Win
			// End of line
			endFoundThisLine = 0;
			if (state == SCE_C_STRINGEOL) {
				styler.ColourTo(i, state);
				state = SCE_C_DEFAULT;
			}
			if (fold) {
				int lev = levelPrev;
				if (visibleChars == 0)
					lev |= SC_FOLDLEVELWHITEFLAG;
				if ((levelCurrent > levelPrev) && (visibleChars > 0))
					lev |= SC_FOLDLEVELHEADERFLAG;
				styler.SetLevel(lineCurrent, lev);
				lineCurrent++;
				levelPrev = levelCurrent;
			}
			visibleChars = 0;

/*			int indentBlock = GetLineIndentation(lineCurrent);
			if (blockChange==1){
				lineCurrent++;
				int pos=SetLineIndentation(lineCurrent, indentBlock + indentSize);
			} else if (blockChange==-1) {
				indentBlock -= indentSize;
				if (indentBlock < 0)
					indentBlock = 0;
				SetLineIndentation(lineCurrent, indentBlock);
				lineCurrent++;
			}
			blockChange=0;
*/		}
		if (!isspace(ch))
			visibleChars++;

		if (styler.IsLeadByte(ch)) {
			chNext = styler.SafeGetCharAt(i + 2);
			chPrev = ' ';
			i += 1;
			continue;
		}

		if (state == SCE_C_DEFAULT) {
			if (iswordstart(ch)) {
				styler.ColourTo(i-1, state);
					state = SCE_C_IDENTIFIER;
			} else if (ch == '@' && chNext == 'o') {
				if ((styler.SafeGetCharAt(i+2) =='f') && (styler.SafeGetCharAt(i+3) == 'f')) {
					styler.ColourTo(i-1, state);
					state = SCE_C_COMMENT;
				}
			} else if (ch == '#') {
				styler.ColourTo(i-1, state);
				state = SCE_C_COMMENTLINE;
			} else if (ch == '\"') {
				styler.ColourTo(i-1, state);
				state = SCE_C_STRING;
			} else if (ch == '\'') {
				styler.ColourTo(i-1, state);
				state = SCE_C_CHARACTER;
			} else if (isoperator(ch)) {
				styler.ColourTo(i-1, state);
				styler.ColourTo(i, SCE_C_OPERATOR);
			}
		} else if (state == SCE_C_IDENTIFIER) {
			if (!iswordchar(ch)) {
				int levelChange = classifyWordBullant(styler.GetStartSegment(), i - 1, keywords, styler);
				state = SCE_C_DEFAULT;
				chNext = styler.SafeGetCharAt(i + 1);
				if (ch == '#') {
					state = SCE_C_COMMENTLINE;
				} else if (ch == '\"') {
					state = SCE_C_STRING;
				} else if (ch == '\'') {
					state = SCE_C_CHARACTER;
				} else if (isoperator(ch)) {
					styler.ColourTo(i, SCE_C_OPERATOR);
				}
				if (endFoundThisLine == 0)
					levelCurrent+=levelChange;
				if (levelChange == -1)
					endFoundThisLine=1;
			}
		} else if (state == SCE_C_COMMENT) {
			if (ch == '@' && chNext == 'o') {
				if (styler.SafeGetCharAt(i+2) == 'n') {
					styler.ColourTo(i+2, state);
					state = SCE_C_DEFAULT;
					i+=2;
				}
			}
		} else if (state == SCE_C_COMMENTLINE) {
			if (ch == '\r' || ch == '\n') {
				endFoundThisLine = 0;
				styler.ColourTo(i-1, state);
				state = SCE_C_DEFAULT;
			}
		} else if (state == SCE_C_STRING) {
			if (ch == '\\') {
				if (chNext == '\"' || chNext == '\'' || chNext == '\\') {
					i++;
					ch = chNext;
					chNext = styler.SafeGetCharAt(i + 1);
				}
			} else if (ch == '\"') {
				styler.ColourTo(i, state);
				state = SCE_C_DEFAULT;
			} else if (chNext == '\r' || chNext == '\n') {
				endFoundThisLine = 0;
				styler.ColourTo(i-1, SCE_C_STRINGEOL);
				state = SCE_C_STRINGEOL;
			}
		} else if (state == SCE_C_CHARACTER) {
			if ((ch == '\r' || ch == '\n') && (chPrev != '\\')) {
				endFoundThisLine = 0;
				styler.ColourTo(i-1, SCE_C_STRINGEOL);
				state = SCE_C_STRINGEOL;
			} else if (ch == '\\') {
				if (chNext == '\"' || chNext == '\'' || chNext == '\\') {
					i++;
					ch = chNext;
					chNext = styler.SafeGetCharAt(i + 1);
				}
			} else if (ch == '\'') {
				styler.ColourTo(i, state);
				state = SCE_C_DEFAULT;
			}
		}
		chPrev = ch;
	}
	styler.ColourTo(lengthDoc - 1, state);

	// Fill in the real level of the next line, keeping the current flags as they will be filled in later
	if (fold) {
		int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
		//styler.SetLevel(lineCurrent, levelCurrent | flagsNext);
		styler.SetLevel(lineCurrent, levelPrev | flagsNext);

	}
}

LexerModule lmBullant(SCLEX_BULLANT, ColouriseBullantDoc, "bullant");
<commit_msg>Upgraded keyword list descriptions from Brian Quinlan.<commit_after>// SciTE - Scintilla based Text Editor
// LexBullant.cxx - lexer for Bullant

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"

static int classifyWordBullant(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) {
	char s[100];
	for (unsigned int i = 0; i < end - start + 1 && i < 30; i++) {
		s[i] = static_cast<char>(tolower(styler[start + i]));
		s[i + 1] = '\0';
	}
	int lev= 0;
	char chAttr = SCE_C_IDENTIFIER;
	if (isdigit(s[0]) || (s[0] == '.')){
		chAttr = SCE_C_NUMBER;
	}
	else {
		if (keywords.InList(s)) {
			chAttr = SCE_C_WORD;
			if (strcmp(s, "end") == 0)
				lev = -1;
			else if (strcmp(s, "method") == 0 ||
				strcmp(s, "case") == 0 ||
				strcmp(s, "class") == 0 ||
				strcmp(s, "debug") == 0 ||
				strcmp(s, "test") == 0 ||
				strcmp(s, "if") == 0 ||
				strcmp(s, "lock") == 0 ||
				strcmp(s, "transaction") == 0 ||
				strcmp(s, "trap") == 0 ||
				strcmp(s, "until") == 0 ||
				strcmp(s, "while") == 0)
				lev = 1;
		}
	}
	styler.ColourTo(end, chAttr);
	return lev;
}

static void ColouriseBullantDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
	Accessor &styler) {
	WordList &keywords = *keywordlists[0];

	styler.StartAt(startPos);

	bool fold = styler.GetPropertyInt("fold") != 0;
	int lineCurrent = styler.GetLine(startPos);
	int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
	int levelCurrent = levelPrev;

	int state = initStyle;
	if (state == SCE_C_STRINGEOL)	// Does not leak onto next line
		state = SCE_C_DEFAULT;
	char chPrev = ' ';
	char chNext = styler[startPos];
	unsigned int lengthDoc = startPos + length;
	int visibleChars = 0;
	styler.StartSegment(startPos);
	int endFoundThisLine = 0;
	for (unsigned int i = startPos; i < lengthDoc; i++) {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);

		if ((ch == '\r' && chNext != '\n') || (ch == '\n')) {
			// Trigger on CR only (Mac style) or either on LF from CR+LF (Dos/Win) or on LF alone (Unix)
			// Avoid triggering two times on Dos/Win
			// End of line
			endFoundThisLine = 0;
			if (state == SCE_C_STRINGEOL) {
				styler.ColourTo(i, state);
				state = SCE_C_DEFAULT;
			}
			if (fold) {
				int lev = levelPrev;
				if (visibleChars == 0)
					lev |= SC_FOLDLEVELWHITEFLAG;
				if ((levelCurrent > levelPrev) && (visibleChars > 0))
					lev |= SC_FOLDLEVELHEADERFLAG;
				styler.SetLevel(lineCurrent, lev);
				lineCurrent++;
				levelPrev = levelCurrent;
			}
			visibleChars = 0;

/*			int indentBlock = GetLineIndentation(lineCurrent);
			if (blockChange==1){
				lineCurrent++;
				int pos=SetLineIndentation(lineCurrent, indentBlock + indentSize);
			} else if (blockChange==-1) {
				indentBlock -= indentSize;
				if (indentBlock < 0)
					indentBlock = 0;
				SetLineIndentation(lineCurrent, indentBlock);
				lineCurrent++;
			}
			blockChange=0;
*/		}
		if (!isspace(ch))
			visibleChars++;

		if (styler.IsLeadByte(ch)) {
			chNext = styler.SafeGetCharAt(i + 2);
			chPrev = ' ';
			i += 1;
			continue;
		}

		if (state == SCE_C_DEFAULT) {
			if (iswordstart(ch)) {
				styler.ColourTo(i-1, state);
					state = SCE_C_IDENTIFIER;
			} else if (ch == '@' && chNext == 'o') {
				if ((styler.SafeGetCharAt(i+2) =='f') && (styler.SafeGetCharAt(i+3) == 'f')) {
					styler.ColourTo(i-1, state);
					state = SCE_C_COMMENT;
				}
			} else if (ch == '#') {
				styler.ColourTo(i-1, state);
				state = SCE_C_COMMENTLINE;
			} else if (ch == '\"') {
				styler.ColourTo(i-1, state);
				state = SCE_C_STRING;
			} else if (ch == '\'') {
				styler.ColourTo(i-1, state);
				state = SCE_C_CHARACTER;
			} else if (isoperator(ch)) {
				styler.ColourTo(i-1, state);
				styler.ColourTo(i, SCE_C_OPERATOR);
			}
		} else if (state == SCE_C_IDENTIFIER) {
			if (!iswordchar(ch)) {
				int levelChange = classifyWordBullant(styler.GetStartSegment(), i - 1, keywords, styler);
				state = SCE_C_DEFAULT;
				chNext = styler.SafeGetCharAt(i + 1);
				if (ch == '#') {
					state = SCE_C_COMMENTLINE;
				} else if (ch == '\"') {
					state = SCE_C_STRING;
				} else if (ch == '\'') {
					state = SCE_C_CHARACTER;
				} else if (isoperator(ch)) {
					styler.ColourTo(i, SCE_C_OPERATOR);
				}
				if (endFoundThisLine == 0)
					levelCurrent+=levelChange;
				if (levelChange == -1)
					endFoundThisLine=1;
			}
		} else if (state == SCE_C_COMMENT) {
			if (ch == '@' && chNext == 'o') {
				if (styler.SafeGetCharAt(i+2) == 'n') {
					styler.ColourTo(i+2, state);
					state = SCE_C_DEFAULT;
					i+=2;
				}
			}
		} else if (state == SCE_C_COMMENTLINE) {
			if (ch == '\r' || ch == '\n') {
				endFoundThisLine = 0;
				styler.ColourTo(i-1, state);
				state = SCE_C_DEFAULT;
			}
		} else if (state == SCE_C_STRING) {
			if (ch == '\\') {
				if (chNext == '\"' || chNext == '\'' || chNext == '\\') {
					i++;
					ch = chNext;
					chNext = styler.SafeGetCharAt(i + 1);
				}
			} else if (ch == '\"') {
				styler.ColourTo(i, state);
				state = SCE_C_DEFAULT;
			} else if (chNext == '\r' || chNext == '\n') {
				endFoundThisLine = 0;
				styler.ColourTo(i-1, SCE_C_STRINGEOL);
				state = SCE_C_STRINGEOL;
			}
		} else if (state == SCE_C_CHARACTER) {
			if ((ch == '\r' || ch == '\n') && (chPrev != '\\')) {
				endFoundThisLine = 0;
				styler.ColourTo(i-1, SCE_C_STRINGEOL);
				state = SCE_C_STRINGEOL;
			} else if (ch == '\\') {
				if (chNext == '\"' || chNext == '\'' || chNext == '\\') {
					i++;
					ch = chNext;
					chNext = styler.SafeGetCharAt(i + 1);
				}
			} else if (ch == '\'') {
				styler.ColourTo(i, state);
				state = SCE_C_DEFAULT;
			}
		}
		chPrev = ch;
	}
	styler.ColourTo(lengthDoc - 1, state);

	// Fill in the real level of the next line, keeping the current flags as they will be filled in later
	if (fold) {
		int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
		//styler.SetLevel(lineCurrent, levelCurrent | flagsNext);
		styler.SetLevel(lineCurrent, levelPrev | flagsNext);

	}
}

static const char * const bullantWordListDesc[] = {
	"Keywords",
	0
};

LexerModule lmBullant(SCLEX_BULLANT, ColouriseBullantDoc, "bullant", 0, bullantWordListDesc);
<|endoftext|>


<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

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 "paddle/framework/executor.h"
#include <memory>
#include "paddle/framework/scope.h"
#include "paddle/platform/device_context.h"

namespace paddle {
namespace framework {

class LinearListView;
class GraphView;

// Immutable view of a ProgramDesc organized for efficient execution.
class ProgramDescView {
 public:
  virtual ~ProgramDescView() {}
  virtual void Initialize(const ProgramDesc*) = 0;
  static ProgramDescView* Create(bool is_linear);
};

class LinearListView : public ProgramDescView {
 public:
  void Initialize(const ProgramDesc*) override;
};

class GraphView : public ProgramDescView {
 public:
  void Initialize(const ProgramDesc*) override;
};

ProgramDescView* ProgramDescView::Create(bool is_linear) {
  if (is_linear) {
    return new LinearListView();
  } else {
    return new GraphView();
  }
}

void LinearListView::Initialize(const ProgramDesc*) {
  // get a LinearView of ProgramDesc
}

void GraphView::Initialize(const ProgramDesc*) {
  // get a GraphView of ProgramDesc
}

class ExecutorImpl : public Executor {
 public:
  ExecutorImpl(Scope* scope, const platform::DeviceContext* ctx,
               const ProgramDesc* pdesc, bool is_linear)
      : scope_(scope),
        device_context_(ctx),
        program_desc_(pdesc),
        view_(ProgramDescView::Create(is_linear)) {}

  virtual ~ExecutorImpl() {
    if (view_) delete view_;
  }

  void Run() override;

  void Initialize();

 private:
  Scope* scope_;
  const platform::DeviceContext* device_context_;
  const ProgramDesc* program_desc_;
  ProgramDescView* view_;
};

template <typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args) {
  return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}

platform::CPUDeviceContext* GetCPUDeviceContext() {
  static std::unique_ptr<platform::CPUDeviceContext> g_cpu_device_context =
      make_unique<platform::CPUDeviceContext>(platform::CPUPlace());
  return g_cpu_device_context.get();
}

#ifndef PADDLE_ONLY_CPU
platform::CUDADeviceContext* GetCUDADeviceContext() {
  static std::unique_ptr<platform::CUDADeviceContext> g_cuda_device_context =
      make_unique<platform::CUDADeviceContext>(platform::GPUPlace(0));
  return g_cuda_device_context.get();
}
#endif

framework::Scope* GetScope() {
  static std::unique_ptr<framework::Scope> g_scope =
      make_unique<framework::Scope>();
  return g_scope.get();
}

Executor* NewLocalExecutor(const platform::Place& place,
                           const ProgramDesc& pdesc, bool is_linear) {
  platform::DeviceContext* device_context = nullptr;
  if (platform::is_cpu_place(place)) {
    device_context = GetCPUDeviceContext();
  } else if (platform::is_gpu_place(place)) {
#ifndef PADDLE_ONLY_CPU
    device_context = GetCUDADeviceContext();
  }
#else
    PADDLE_THROW("'GPUPlace' is not supported in CPU only device.");
  }
#endif
  return new ExecutorImpl(GetScope(), device_context, &pdesc, is_linear);
}

void ExecutorImpl::Run() {
  // operators running
  scope_->NewVar();
  device_context_->Wait();
}

void ExecutorImpl::Initialize() {
  // Initialize the ProgramDescView
  view_->Initialize(program_desc_);
}

}  // namespace framework
}  // namespace paddle
<commit_msg>pass place to GetCUDADeviceContext<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

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 "paddle/framework/executor.h"
#include <memory>
#include "paddle/framework/scope.h"
#include "paddle/platform/device_context.h"

namespace paddle {
namespace framework {

class LinearListView;
class GraphView;

// Immutable view of a ProgramDesc organized for efficient execution.
class ProgramDescView {
 public:
  virtual ~ProgramDescView() {}
  virtual void Initialize(const ProgramDesc*) = 0;
  static ProgramDescView* Create(bool is_linear);
};

class LinearListView : public ProgramDescView {
 public:
  void Initialize(const ProgramDesc*) override;
};

class GraphView : public ProgramDescView {
 public:
  void Initialize(const ProgramDesc*) override;
};

ProgramDescView* ProgramDescView::Create(bool is_linear) {
  if (is_linear) {
    return new LinearListView();
  } else {
    return new GraphView();
  }
}

void LinearListView::Initialize(const ProgramDesc*) {
  // get a LinearView of ProgramDesc
}

void GraphView::Initialize(const ProgramDesc*) {
  // get a GraphView of ProgramDesc
}

class ExecutorImpl : public Executor {
 public:
  ExecutorImpl(Scope* scope, const platform::DeviceContext* ctx,
               const ProgramDesc* pdesc, bool is_linear)
      : scope_(scope),
        device_context_(ctx),
        program_desc_(pdesc),
        view_(ProgramDescView::Create(is_linear)) {}

  virtual ~ExecutorImpl() {
    if (view_) delete view_;
  }

  void Run() override;

  void Initialize();

 private:
  Scope* scope_;
  const platform::DeviceContext* device_context_;
  const ProgramDesc* program_desc_;
  ProgramDescView* view_;
};

template <typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args) {
  return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}

platform::CPUDeviceContext* GetCPUDeviceContext(platform::CPUPlace& place) {
  static std::unique_ptr<platform::CPUDeviceContext> g_cpu_device_context =
      make_unique<platform::CPUDeviceContext>(place);
  return g_cpu_device_context.get();
}

#ifndef PADDLE_ONLY_CPU
platform::CUDADeviceContext* GetCUDADeviceContext(platform::GPUPlace& place) {
  static std::unique_ptr<platform::CUDADeviceContext> g_cuda_device_context =
      make_unique<platform::CUDADeviceContext>(place);
  return g_cuda_device_context.get();
}
#endif

framework::Scope* GetScope() {
  static std::unique_ptr<framework::Scope> g_scope =
      make_unique<framework::Scope>();
  return g_scope.get();
}

Executor* NewLocalExecutor(const platform::Place& place,
                           const ProgramDesc& pdesc, bool is_linear) {
  platform::DeviceContext* device_context = nullptr;
  if (platform::is_cpu_place(place)) {
    auto cpu_place = boost::get<platform::CPUPlace>(place);
    device_context = GetCPUDeviceContext(cpu_place);
  } else if (platform::is_gpu_place(place)) {
#ifndef PADDLE_ONLY_CPU
    auto gpu_place = boost::get<platform::GPUPlace>(place);
    device_context = GetCUDADeviceContext(gpu_place);
  }
#else
    PADDLE_THROW("'GPUPlace' is not supported in CPU only device.");
  }
#endif
  return new ExecutorImpl(GetScope(), device_context, &pdesc, is_linear);
}

void ExecutorImpl::Run() {
  // operators running
  scope_->NewVar();
  device_context_->Wait();
}

void ExecutorImpl::Initialize() {
  // Initialize the ProgramDescView
  view_->Initialize(program_desc_);
}

}  // namespace framework
}  // namespace paddle
<|endoftext|>