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

#ifndef SCRIPTING_BASMETHNODE_HXX
#include "basmethnode.hxx"
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDESKTOP_HPP_
#include <com/sun/star/frame/XDesktop.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHHELPER_HPP_
#include <com/sun/star/frame/XDispatchHelper.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTICOMPONENTFACTORY_HPP_
#include <com/sun/star/lang/XMultiComponentFactory.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_SCRIPT_BROWSE_BROWSENODETYPES_HPP_
#include <drafts/com/sun/star/script/browse/BrowseNodeTypes.hpp>
#endif

#ifndef _SB_SBSTAR_HXX
#include <basic/sbstar.hxx>
#endif
#ifndef _SB_SBMETH_HXX
#include <basic/sbmeth.hxx>
#endif
#ifndef _SB_SBMOD_HXX
#include <basic/sbmod.hxx>
#endif

using namespace ::com::sun::star;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::comphelper;
using namespace ::drafts::com::sun::star::script;

#define BASPROV_PROPERTY_ID_URI         1
#define BASPROV_PROPERTY_ID_EDITABLE    2

#define BASPROV_PROPERTY_URI            ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "URI" ) )
#define BASPROV_PROPERTY_EDITABLE       ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Editable" ) )

#define BASPROV_DEFAULT_ATTRIBS()       PropertyAttribute::BOUND | PropertyAttribute::TRANSIENT | PropertyAttribute::READONLY

//.........................................................................
namespace basprov
{
//.........................................................................

    // =============================================================================
    // BasicMethodNodeImpl
    // =============================================================================

    BasicMethodNodeImpl::BasicMethodNodeImpl( const Reference< XComponentContext >& rxContext,
        const Reference< XPropertySet >& rxScriptingContext, SbMethod* pMethod, bool isAppScript )
        : ::scripting_helper::OBroadcastHelperHolder( StarBASIC::GetGlobalMutex() )
        ,OPropertyContainer( GetBroadcastHelper() )
        ,m_xContext( rxContext )
        ,m_xScriptingContext( rxScriptingContext )
        ,m_pMethod( pMethod )
        ,m_bIsAppScript( isAppScript )
        ,m_bEditable( sal_True )
    {
        if ( m_pMethod )
        {
            SbModule* pModule = m_pMethod->GetModule();
            if ( pModule )
            {
                StarBASIC* pBasic = static_cast< StarBASIC* >( pModule->GetParent() );
                if ( pBasic )
                {
                    m_sURI = ::rtl::OUString::createFromAscii( "vnd.sun.star.script://" );
                    m_sURI += pBasic->GetName();
                    m_sURI += ::rtl::OUString::createFromAscii( "." );
                    m_sURI += pModule->GetName();
                    m_sURI += ::rtl::OUString::createFromAscii( "." );
                    m_sURI += m_pMethod->GetName();
                    m_sURI += ::rtl::OUString::createFromAscii( "?language=Basic&location=" );
                    if ( m_bIsAppScript )
                        m_sURI += ::rtl::OUString::createFromAscii( "application" );
                    else
                        m_sURI += ::rtl::OUString::createFromAscii( "document" );
                }
            }
        }

        registerProperty( BASPROV_PROPERTY_URI,      BASPROV_PROPERTY_ID_URI,      BASPROV_DEFAULT_ATTRIBS(), &m_sURI,      ::getCppuType( &m_sURI ) );
        registerProperty( BASPROV_PROPERTY_EDITABLE, BASPROV_PROPERTY_ID_EDITABLE, BASPROV_DEFAULT_ATTRIBS(), &m_bEditable, ::getCppuType( &m_bEditable ) );
    }

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

    BasicMethodNodeImpl::~BasicMethodNodeImpl()
    {
    }

    // -----------------------------------------------------------------------------
    // XInterface
    // -----------------------------------------------------------------------------

    IMPLEMENT_FORWARD_XINTERFACE2( BasicMethodNodeImpl, BasicMethodNodeImpl_BASE, OPropertyContainer )

    // -----------------------------------------------------------------------------
    // XTypeProvider
    // -----------------------------------------------------------------------------

    IMPLEMENT_FORWARD_XTYPEPROVIDER2( BasicMethodNodeImpl, BasicMethodNodeImpl_BASE, OPropertyContainer )

    // -----------------------------------------------------------------------------
    // XBrowseNode
    // -----------------------------------------------------------------------------

    ::rtl::OUString BasicMethodNodeImpl::getName(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( StarBASIC::GetGlobalMutex() );

        ::rtl::OUString sMethodName;
        if ( m_pMethod )
            sMethodName = m_pMethod->GetName();

        return sMethodName;
    }

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

    Sequence< Reference< browse::XBrowseNode > > BasicMethodNodeImpl::getChildNodes(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( StarBASIC::GetGlobalMutex() );

        return Sequence< Reference< browse::XBrowseNode > >();
    }

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

    sal_Bool BasicMethodNodeImpl::hasChildNodes(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( StarBASIC::GetGlobalMutex() );

        return sal_False;
    }

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

    sal_Int16 BasicMethodNodeImpl::getType(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( StarBASIC::GetGlobalMutex() );

        return browse::BrowseNodeTypes::SCRIPT;
    }

    // -----------------------------------------------------------------------------
    // OPropertySetHelper
    // -----------------------------------------------------------------------------

    ::cppu::IPropertyArrayHelper& BasicMethodNodeImpl::getInfoHelper(  )
    {
        return *getArrayHelper();
    }

    // -----------------------------------------------------------------------------
    // OPropertyArrayUsageHelper
    // -----------------------------------------------------------------------------

    ::cppu::IPropertyArrayHelper* BasicMethodNodeImpl::createArrayHelper(  ) const
    {
        Sequence< Property > aProps;
        describeProperties( aProps );
        return new ::cppu::OPropertyArrayHelper( aProps );
    }

    // -----------------------------------------------------------------------------
    // XPropertySet
    // -----------------------------------------------------------------------------

    Reference< XPropertySetInfo > BasicMethodNodeImpl::getPropertySetInfo(  ) throw (RuntimeException)
    {
        Reference< XPropertySetInfo > xInfo( createPropertySetInfo( getInfoHelper() ) );
        return xInfo;
    }

    // -----------------------------------------------------------------------------
    // XInvocation
    // -----------------------------------------------------------------------------

    Reference< XIntrospectionAccess > BasicMethodNodeImpl::getIntrospection(  ) throw (RuntimeException)
    {
        return Reference< XIntrospectionAccess >();
    }

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

    Any BasicMethodNodeImpl::invoke( const ::rtl::OUString& aFunctionName, const Sequence< Any >& aParams,
        Sequence< sal_Int16 >& aOutParamIndex, Sequence< Any >& aOutParam )
        throw (IllegalArgumentException, script::CannotConvertException,
               reflection::InvocationTargetException, RuntimeException)
    {
        if ( aFunctionName == BASPROV_PROPERTY_EDITABLE )
        {
            ::rtl::OUString sDocURL, sLibName, sModName;
            USHORT nLine1, nLine2;

            if ( !m_bIsAppScript && m_xScriptingContext.is() )
            {
                Reference< frame::XModel > xModel;
                // TODO: use ScriptingContantsPool for SCRIPTING_DOC_REF
                m_xScriptingContext->getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "SCRIPTING_DOC_REF" ) ) ) >>= xModel;

                if ( xModel.is() )
                {
                    sDocURL = xModel->getURL();
                    if ( sDocURL.getLength() == 0 )
                    {
                        Sequence < PropertyValue > aProps = xModel->getArgs();
                        sal_Int32 nProps = aProps.getLength();
                        const PropertyValue* pProps = aProps.getConstArray();
                        for ( sal_Int32 i = 0; i < nProps; ++i )
                        {
                            // TODO: according to MBA the property 'Title' may change in future
                            if ( pProps[i].Name == ::rtl::OUString::createFromAscii( "Title" ) )
                            {
                                pProps[i].Value >>= sDocURL;
                                break;
                            }
                        }
                    }
                }
            }

            if ( m_pMethod )
            {
                m_pMethod->GetLineRange( nLine1, nLine2 );
                SbModule* pModule = m_pMethod->GetModule();
                if ( pModule )
                {
                    sModName = pModule->GetName();
                    StarBASIC* pBasic = static_cast< StarBASIC* >( pModule->GetParent() );
                    if ( pBasic )
                        sLibName = pBasic->GetName();
                }
            }

            if ( m_xContext.is() )
            {
                Reference< XMultiComponentFactory > xSMgr( m_xContext->getServiceManager() );

                if ( xSMgr.is() )
                {
                    Reference< frame::XDesktop > xDesktop( xSMgr->createInstanceWithContext(
                        ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.frame.Desktop" ) ), m_xContext ), UNO_QUERY );

                    if ( xDesktop.is() )
                    {
                        Reference < frame::XDispatchProvider > xProv( xDesktop->getCurrentFrame(), UNO_QUERY );

                        if ( xProv.is() )
                        {
                            Reference< frame::XDispatchHelper > xHelper( xSMgr->createInstanceWithContext(
                                ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.frame.DispatchHelper" ) ), m_xContext ), UNO_QUERY );

                            if ( xHelper.is() )
                            {
                                Sequence < PropertyValue > aArgs(7);
                                aArgs[0].Name = ::rtl::OUString::createFromAscii( "Document" );
                                aArgs[0].Value <<= sDocURL;
                                aArgs[1].Name = ::rtl::OUString::createFromAscii( "LibName" );
                                aArgs[1].Value <<= sLibName;
                                aArgs[2].Name = ::rtl::OUString::createFromAscii( "Name" );
                                aArgs[2].Value <<= sModName;
                                aArgs[3].Name = ::rtl::OUString::createFromAscii( "Type" );
                                aArgs[3].Value <<= ::rtl::OUString::createFromAscii( "Module" );
                                aArgs[4].Name = ::rtl::OUString::createFromAscii( "Line" );
                                aArgs[4].Value <<= static_cast< sal_uInt32 >( nLine1 );
                                xHelper->executeDispatch( xProv, ::rtl::OUString::createFromAscii( ".uno:BasicIDEAppear" ), ::rtl::OUString(), 0, aArgs );
                            }
                        }
                    }
                }
            }
        }
        else
        {
            throw IllegalArgumentException(
                ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "BasicMethodNodeImpl::invoke: function name not supported!" ) ),
                Reference< XInterface >(), 1 );
        }

        return Any();
    }

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

    void BasicMethodNodeImpl::setValue( const ::rtl::OUString& aPropertyName, const Any& aValue )
        throw (UnknownPropertyException, script::CannotConvertException,
               reflection::InvocationTargetException, RuntimeException)
    {
        throw UnknownPropertyException(
            ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "BasicMethodNodeImpl::setValue: property name is unknown!" ) ),
            Reference< XInterface >() );
    }

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

    Any BasicMethodNodeImpl::getValue( const ::rtl::OUString& aPropertyName ) throw (UnknownPropertyException, RuntimeException)
    {
        throw UnknownPropertyException(
            ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "BasicMethodNodeImpl::getValue: property name is unknown!" ) ),
            Reference< XInterface >() );
    }

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

    sal_Bool BasicMethodNodeImpl::hasMethod( const ::rtl::OUString& aName ) throw (RuntimeException)
    {
        sal_Bool bReturn = sal_False;
        if ( aName == BASPROV_PROPERTY_EDITABLE )
            bReturn = sal_True;

        return bReturn;
    }

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

    sal_Bool BasicMethodNodeImpl::hasProperty( const ::rtl::OUString& aName ) throw (RuntimeException)
    {
        return sal_False;
    }

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

//.........................................................................
}   // namespace basprov
//.........................................................................
<commit_msg>INTEGRATION: CWS scriptingf5 (1.5.14); FILE MERGED 2004/03/05 10:33:43 npower 1.5.14.1: #i22570# Changes to support new URL parsing service. A side affect of using the new service is that the format of the URI has changed a little. The URI is now nt hierarchical. Changes to the files below involve removing methods to parse data from the URI instread new service UriReferenceFactory, adding the new types to build project xml  files.<commit_after>/*************************************************************************
 *
 *  $RCSfile: basmethnode.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: svesik $ $Date: 2004-04-19 23:13:31 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SCRIPTING_BASMETHNODE_HXX
#include "basmethnode.hxx"
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDESKTOP_HPP_
#include <com/sun/star/frame/XDesktop.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHHELPER_HPP_
#include <com/sun/star/frame/XDispatchHelper.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTICOMPONENTFACTORY_HPP_
#include <com/sun/star/lang/XMultiComponentFactory.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_SCRIPT_BROWSE_BROWSENODETYPES_HPP_
#include <drafts/com/sun/star/script/browse/BrowseNodeTypes.hpp>
#endif

#ifndef _SB_SBSTAR_HXX
#include <basic/sbstar.hxx>
#endif
#ifndef _SB_SBMETH_HXX
#include <basic/sbmeth.hxx>
#endif
#ifndef _SB_SBMOD_HXX
#include <basic/sbmod.hxx>
#endif

using namespace ::com::sun::star;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::comphelper;
using namespace ::drafts::com::sun::star::script;

#define BASPROV_PROPERTY_ID_URI         1
#define BASPROV_PROPERTY_ID_EDITABLE    2

#define BASPROV_PROPERTY_URI            ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "URI" ) )
#define BASPROV_PROPERTY_EDITABLE       ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Editable" ) )

#define BASPROV_DEFAULT_ATTRIBS()       PropertyAttribute::BOUND | PropertyAttribute::TRANSIENT | PropertyAttribute::READONLY

//.........................................................................
namespace basprov
{
//.........................................................................

    // =============================================================================
    // BasicMethodNodeImpl
    // =============================================================================

    BasicMethodNodeImpl::BasicMethodNodeImpl( const Reference< XComponentContext >& rxContext,
        const Reference< XPropertySet >& rxScriptingContext, SbMethod* pMethod, bool isAppScript )
        : ::scripting_helper::OBroadcastHelperHolder( StarBASIC::GetGlobalMutex() )
        ,OPropertyContainer( GetBroadcastHelper() )
        ,m_xContext( rxContext )
        ,m_xScriptingContext( rxScriptingContext )
        ,m_pMethod( pMethod )
        ,m_bIsAppScript( isAppScript )
        ,m_bEditable( sal_True )
    {
        if ( m_pMethod )
        {
            SbModule* pModule = m_pMethod->GetModule();
            if ( pModule )
            {
                StarBASIC* pBasic = static_cast< StarBASIC* >( pModule->GetParent() );
                if ( pBasic )
                {
                    m_sURI = ::rtl::OUString::createFromAscii( "vnd.sun.star.script:" );
                    m_sURI += pBasic->GetName();
                    m_sURI += ::rtl::OUString::createFromAscii( "." );
                    m_sURI += pModule->GetName();
                    m_sURI += ::rtl::OUString::createFromAscii( "." );
                    m_sURI += m_pMethod->GetName();
                    m_sURI += ::rtl::OUString::createFromAscii( "?language=Basic&location=" );
                    if ( m_bIsAppScript )
                        m_sURI += ::rtl::OUString::createFromAscii( "application" );
                    else
                        m_sURI += ::rtl::OUString::createFromAscii( "document" );
                }
            }
        }

        registerProperty( BASPROV_PROPERTY_URI,      BASPROV_PROPERTY_ID_URI,      BASPROV_DEFAULT_ATTRIBS(), &m_sURI,      ::getCppuType( &m_sURI ) );
        registerProperty( BASPROV_PROPERTY_EDITABLE, BASPROV_PROPERTY_ID_EDITABLE, BASPROV_DEFAULT_ATTRIBS(), &m_bEditable, ::getCppuType( &m_bEditable ) );
    }

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

    BasicMethodNodeImpl::~BasicMethodNodeImpl()
    {
    }

    // -----------------------------------------------------------------------------
    // XInterface
    // -----------------------------------------------------------------------------

    IMPLEMENT_FORWARD_XINTERFACE2( BasicMethodNodeImpl, BasicMethodNodeImpl_BASE, OPropertyContainer )

    // -----------------------------------------------------------------------------
    // XTypeProvider
    // -----------------------------------------------------------------------------

    IMPLEMENT_FORWARD_XTYPEPROVIDER2( BasicMethodNodeImpl, BasicMethodNodeImpl_BASE, OPropertyContainer )

    // -----------------------------------------------------------------------------
    // XBrowseNode
    // -----------------------------------------------------------------------------

    ::rtl::OUString BasicMethodNodeImpl::getName(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( StarBASIC::GetGlobalMutex() );

        ::rtl::OUString sMethodName;
        if ( m_pMethod )
            sMethodName = m_pMethod->GetName();

        return sMethodName;
    }

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

    Sequence< Reference< browse::XBrowseNode > > BasicMethodNodeImpl::getChildNodes(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( StarBASIC::GetGlobalMutex() );

        return Sequence< Reference< browse::XBrowseNode > >();
    }

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

    sal_Bool BasicMethodNodeImpl::hasChildNodes(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( StarBASIC::GetGlobalMutex() );

        return sal_False;
    }

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

    sal_Int16 BasicMethodNodeImpl::getType(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( StarBASIC::GetGlobalMutex() );

        return browse::BrowseNodeTypes::SCRIPT;
    }

    // -----------------------------------------------------------------------------
    // OPropertySetHelper
    // -----------------------------------------------------------------------------

    ::cppu::IPropertyArrayHelper& BasicMethodNodeImpl::getInfoHelper(  )
    {
        return *getArrayHelper();
    }

    // -----------------------------------------------------------------------------
    // OPropertyArrayUsageHelper
    // -----------------------------------------------------------------------------

    ::cppu::IPropertyArrayHelper* BasicMethodNodeImpl::createArrayHelper(  ) const
    {
        Sequence< Property > aProps;
        describeProperties( aProps );
        return new ::cppu::OPropertyArrayHelper( aProps );
    }

    // -----------------------------------------------------------------------------
    // XPropertySet
    // -----------------------------------------------------------------------------

    Reference< XPropertySetInfo > BasicMethodNodeImpl::getPropertySetInfo(  ) throw (RuntimeException)
    {
        Reference< XPropertySetInfo > xInfo( createPropertySetInfo( getInfoHelper() ) );
        return xInfo;
    }

    // -----------------------------------------------------------------------------
    // XInvocation
    // -----------------------------------------------------------------------------

    Reference< XIntrospectionAccess > BasicMethodNodeImpl::getIntrospection(  ) throw (RuntimeException)
    {
        return Reference< XIntrospectionAccess >();
    }

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

    Any BasicMethodNodeImpl::invoke( const ::rtl::OUString& aFunctionName, const Sequence< Any >& aParams,
        Sequence< sal_Int16 >& aOutParamIndex, Sequence< Any >& aOutParam )
        throw (IllegalArgumentException, script::CannotConvertException,
               reflection::InvocationTargetException, RuntimeException)
    {
        if ( aFunctionName == BASPROV_PROPERTY_EDITABLE )
        {
            ::rtl::OUString sDocURL, sLibName, sModName;
            USHORT nLine1, nLine2;

            if ( !m_bIsAppScript && m_xScriptingContext.is() )
            {
                Reference< frame::XModel > xModel;
                // TODO: use ScriptingContantsPool for SCRIPTING_DOC_REF
                m_xScriptingContext->getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "SCRIPTING_DOC_REF" ) ) ) >>= xModel;

                if ( xModel.is() )
                {
                    sDocURL = xModel->getURL();
                    if ( sDocURL.getLength() == 0 )
                    {
                        Sequence < PropertyValue > aProps = xModel->getArgs();
                        sal_Int32 nProps = aProps.getLength();
                        const PropertyValue* pProps = aProps.getConstArray();
                        for ( sal_Int32 i = 0; i < nProps; ++i )
                        {
                            // TODO: according to MBA the property 'Title' may change in future
                            if ( pProps[i].Name == ::rtl::OUString::createFromAscii( "Title" ) )
                            {
                                pProps[i].Value >>= sDocURL;
                                break;
                            }
                        }
                    }
                }
            }

            if ( m_pMethod )
            {
                m_pMethod->GetLineRange( nLine1, nLine2 );
                SbModule* pModule = m_pMethod->GetModule();
                if ( pModule )
                {
                    sModName = pModule->GetName();
                    StarBASIC* pBasic = static_cast< StarBASIC* >( pModule->GetParent() );
                    if ( pBasic )
                        sLibName = pBasic->GetName();
                }
            }

            if ( m_xContext.is() )
            {
                Reference< XMultiComponentFactory > xSMgr( m_xContext->getServiceManager() );

                if ( xSMgr.is() )
                {
                    Reference< frame::XDesktop > xDesktop( xSMgr->createInstanceWithContext(
                        ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.frame.Desktop" ) ), m_xContext ), UNO_QUERY );

                    if ( xDesktop.is() )
                    {
                        Reference < frame::XDispatchProvider > xProv( xDesktop->getCurrentFrame(), UNO_QUERY );

                        if ( xProv.is() )
                        {
                            Reference< frame::XDispatchHelper > xHelper( xSMgr->createInstanceWithContext(
                                ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.frame.DispatchHelper" ) ), m_xContext ), UNO_QUERY );

                            if ( xHelper.is() )
                            {
                                Sequence < PropertyValue > aArgs(7);
                                aArgs[0].Name = ::rtl::OUString::createFromAscii( "Document" );
                                aArgs[0].Value <<= sDocURL;
                                aArgs[1].Name = ::rtl::OUString::createFromAscii( "LibName" );
                                aArgs[1].Value <<= sLibName;
                                aArgs[2].Name = ::rtl::OUString::createFromAscii( "Name" );
                                aArgs[2].Value <<= sModName;
                                aArgs[3].Name = ::rtl::OUString::createFromAscii( "Type" );
                                aArgs[3].Value <<= ::rtl::OUString::createFromAscii( "Module" );
                                aArgs[4].Name = ::rtl::OUString::createFromAscii( "Line" );
                                aArgs[4].Value <<= static_cast< sal_uInt32 >( nLine1 );
                                xHelper->executeDispatch( xProv, ::rtl::OUString::createFromAscii( ".uno:BasicIDEAppear" ), ::rtl::OUString(), 0, aArgs );
                            }
                        }
                    }
                }
            }
        }
        else
        {
            throw IllegalArgumentException(
                ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "BasicMethodNodeImpl::invoke: function name not supported!" ) ),
                Reference< XInterface >(), 1 );
        }

        return Any();
    }

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

    void BasicMethodNodeImpl::setValue( const ::rtl::OUString& aPropertyName, const Any& aValue )
        throw (UnknownPropertyException, script::CannotConvertException,
               reflection::InvocationTargetException, RuntimeException)
    {
        throw UnknownPropertyException(
            ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "BasicMethodNodeImpl::setValue: property name is unknown!" ) ),
            Reference< XInterface >() );
    }

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

    Any BasicMethodNodeImpl::getValue( const ::rtl::OUString& aPropertyName ) throw (UnknownPropertyException, RuntimeException)
    {
        throw UnknownPropertyException(
            ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "BasicMethodNodeImpl::getValue: property name is unknown!" ) ),
            Reference< XInterface >() );
    }

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

    sal_Bool BasicMethodNodeImpl::hasMethod( const ::rtl::OUString& aName ) throw (RuntimeException)
    {
        sal_Bool bReturn = sal_False;
        if ( aName == BASPROV_PROPERTY_EDITABLE )
            bReturn = sal_True;

        return bReturn;
    }

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

    sal_Bool BasicMethodNodeImpl::hasProperty( const ::rtl::OUString& aName ) throw (RuntimeException)
    {
        return sal_False;
    }

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

//.........................................................................
}   // namespace basprov
//.........................................................................
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2016 Rhys Ulerich
 *
 * 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/.
 */

#ifndef DESCENDU_HEXMAP_H
#define DESCENDU_HEXMAP_H

#include <deque>
#include <functional>
#include <limits>
#include <unordered_map>
#include <utility>
#include <stdexcept>

#include "hex.hpp"
#include "optional.hpp"

namespace descendu {

template <class MappedType>
class hexmap : std::unordered_map<hex<int,spec::absolute>,MappedType>
{
    typedef std::unordered_map<hex<int,spec::absolute>,MappedType> base_type;

public:

    // Deliberately no base_type::size as removal of "dead" tiles TBD
    using typename base_type::begin;
    using typename base_type::cbegin;
    using typename base_type::cend;
    using typename base_type::const_iterator;
    using typename base_type::end;
    using typename base_type::iterator;
    using typename base_type::key_type;
    using typename base_type::mapped_type;

    // Retrieve tile at the given hex, creating if non-existent
    mapped_type& populate(const key_type& hex) {
        return base_type::emplace(
                std::piecewise_construct,
                std::forward_as_tuple(hex),
                std::forward_as_tuple()).first->second;
    }

    // Retrieve tile at the given hex should one exist
    std::experimental::optional<mapped_type&>
    lookup(const key_type& hex) {
        const auto& result = this->find(hex);
        return result == this->cend()
            ? std::experimental::optional<mapped_type&>()
            : std::experimental::make_optional(std::ref(result->second));
    }

    // Retrieve tile at the given hex should one exist
    std::experimental::optional<const mapped_type&>
    lookup(const key_type& hex) const {
        const auto& result = this->find(hex);
        return result == this->cend()
            ? std::experimental::optional<const mapped_type&>()
            : std::experimental::make_optional(std::cref(result->second));
    }

    // TODO Cardinality?
    // TODO Removal?

};

// When investigating some tile in the course of a search, should the
// tile be included as usable, excluded as unusable, or should the search
// stop immediately?
enum class search_result { stop, exclude, include };

// TODO Make hexmap<optional<hex>>
// TODO Use optional to track attempted visitation
// TODO Consider making it optional<pair<hex,distance>
// Breadth first search returning a map from destination to source,
// which may be traversed back to origin for navigational purposes.
// Predicate query(...) is assumed to be inexpensive-- revisit if otherwise.
template <class MappedType>
hexmap<typename hexmap<MappedType>::key_type>
breadth_first_search(
    const hexmap<MappedType>& map,
    const typename hexmap<MappedType>::key_type origin,
    std::function<search_result(const typename hexmap<MappedType>::mapped_type&)> query,
    const int max_distance = std::numeric_limits<int>::max())
{
    hexmap<typename hexmap<MappedType>::key_type> retval;

    // Tracks locations to visit as well as their distance from origin
    std::deque<std::pair<typename hexmap<MappedType>::key_type,int>> frontier;
    frontier.emplace_back(
        std::piecewise_construct,
        std::forward_as_tuple(origin),
        std::forward_as_tuple(0));

    // Proceed with breadth first search until one of exhaustion criteria met
    while (frontier.size()) {

        const auto& current  = frontier.front();
        const auto& contents = map.lookup(current.first);
        const auto  result   = current.second <= max_distance && contents
                             ? query(contents.value())
                             : search_result::exclude;

        switch (result) {
        default:
            throw std::logic_error("missing case");
        case search_result::stop:
            goto done;
        case search_result::exclude:
            break;
        case search_result::include:
            for (const auto& neighbor : neighbors(current.first)) {
                if (retval.find(neighbor) == retval.cend()) {
                    frontier.emplace_back(
                        std::piecewise_construct,
                        std::forward_as_tuple(neighbor),
                        std::forward_as_tuple(current.second + 1));
                }
            }
        }

        frontier.pop_front();
    }

    done: return retval;
}

} // namespace

#endif
<commit_msg>Don't put typename on functions<commit_after>/*
 * Copyright (C) 2016 Rhys Ulerich
 *
 * 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/.
 */

#ifndef DESCENDU_HEXMAP_H
#define DESCENDU_HEXMAP_H

#include <deque>
#include <functional>
#include <limits>
#include <unordered_map>
#include <utility>
#include <stdexcept>

#include "hex.hpp"
#include "optional.hpp"

namespace descendu {

template <class MappedType>
class hexmap : std::unordered_map<hex<int,spec::absolute>,MappedType>
{
    typedef std::unordered_map<hex<int,spec::absolute>,MappedType> base_type;

public:

    // Deliberately no base_type::size as removal of "dead" tiles TBD
    using typename base_type::const_iterator;
    using typename base_type::iterator;
    using typename base_type::key_type;
    using typename base_type::mapped_type;
    using base_type::begin;
    using base_type::cbegin;
    using base_type::cend;
    using base_type::end;

    // Retrieve tile at the given hex, creating if non-existent
    mapped_type& populate(const key_type& hex) {
        return base_type::emplace(
                std::piecewise_construct,
                std::forward_as_tuple(hex),
                std::forward_as_tuple()).first->second;
    }

    // Retrieve tile at the given hex should one exist
    std::experimental::optional<mapped_type&>
    lookup(const key_type& hex) {
        const auto& result = this->find(hex);
        return result == this->cend()
            ? std::experimental::optional<mapped_type&>()
            : std::experimental::make_optional(std::ref(result->second));
    }

    // Retrieve tile at the given hex should one exist
    std::experimental::optional<const mapped_type&>
    lookup(const key_type& hex) const {
        const auto& result = this->find(hex);
        return result == this->cend()
            ? std::experimental::optional<const mapped_type&>()
            : std::experimental::make_optional(std::cref(result->second));
    }

    // TODO Cardinality?
    // TODO Removal?

};

// When investigating some tile in the course of a search, should the
// tile be included as usable, excluded as unusable, or should the search
// stop immediately?
enum class search_result { stop, exclude, include };

// TODO Make hexmap<optional<hex>>
// TODO Use optional to track attempted visitation
// TODO Consider making it optional<pair<hex,distance>
// Breadth first search returning a map from destination to source,
// which may be traversed back to origin for navigational purposes.
// Predicate query(...) is assumed to be inexpensive-- revisit if otherwise.
template <class MappedType>
hexmap<typename hexmap<MappedType>::key_type>
breadth_first_search(
    const hexmap<MappedType>& map,
    const typename hexmap<MappedType>::key_type origin,
    std::function<search_result(const typename hexmap<MappedType>::mapped_type&)> query,
    const int max_distance = std::numeric_limits<int>::max())
{
    hexmap<typename hexmap<MappedType>::key_type> retval;

    // Tracks locations to visit as well as their distance from origin
    std::deque<std::pair<typename hexmap<MappedType>::key_type,int>> frontier;
    frontier.emplace_back(
        std::piecewise_construct,
        std::forward_as_tuple(origin),
        std::forward_as_tuple(0));

    // Proceed with breadth first search until one of exhaustion criteria met
    while (frontier.size()) {

        const auto& current  = frontier.front();
        const auto& contents = map.lookup(current.first);
        const auto  result   = current.second <= max_distance && contents
                             ? query(contents.value())
                             : search_result::exclude;

        switch (result) {
        default:
            throw std::logic_error("missing case");
        case search_result::stop:
            goto done;
        case search_result::exclude:
            break;
        case search_result::include:
            for (const auto& neighbor : neighbors(current.first)) {
                if (retval.find(neighbor) == retval.cend()) {
                    frontier.emplace_back(
                        std::piecewise_construct,
                        std::forward_as_tuple(neighbor),
                        std::forward_as_tuple(current.second + 1));
                }
            }
        }

        frontier.pop_front();
    }

    done: return retval;
}

} // namespace

#endif
<|endoftext|>


<commit_before>#define LOCAL_TEST 0

//#include "../shutdown/shutdown.h"
#include "../windlg/windlg.h"

#include <unistd.h>
#include <stdlib.h>
#include <vector>
#include <string>
#include <curses.h>

using namespace std;

string local_user;

int draw_desktop(int selected, bool open_label, bool new_draw, unsigned int maxX, unsigned int maxY) {
	unsigned x, y;
	if (new_draw) {
		for (x = 15; x < maxX; x++) mvprintw(0, x, "-");
		for (x = 0; x < maxX; x++) mvprintw(maxY - 1, x, "-");
		for (y = 0; y < maxY; y++) {mvprintw(y, 0, "|"); mvprintw(y, maxX - 1, "|");}
	}
		if (selected == 0) attron(COLOR_PAIR(1) | A_BOLD); // Белый цвет
		mvprintw(0, 1, "Menu");
		if (selected == 0) attroff(COLOR_PAIR(1) | A_BOLD);
		if (selected == 1) attron(COLOR_PAIR(1) | A_BOLD); // Белый цвет
		mvprintw(0, 6, "Edit");
		if (selected == 1) attroff(COLOR_PAIR(1) | A_BOLD);
		if (selected == 2) attron(COLOR_PAIR(1) | A_BOLD); // Белый цвет
		mvprintw(0, 11, "Exit");
		if (selected == 2) attroff(COLOR_PAIR(1) | A_BOLD);
	return 0;
}

int work_desktop() {
	unsigned int maxY, maxYb = 0, maxX, maxXb = 0;
	bool cycle = true, open_label = false, new_draw = false;
	int key_pressed, selected = 2;
	while (cycle) {
		getmaxyx(stdscr, maxY, maxX); // Получение размера терминала
		if ((maxX != maxXb) || (maxY != maxYb)) {
			new_draw = true;
			erase();
		}
		timeout(0);
		draw_desktop(selected, open_label, new_draw, maxX, maxY);
		new_draw = false;
		key_pressed = getch();
		switch (key_pressed) {
			case KEY_RIGHT: if (selected != 2) selected++; break;
			case KEY_LEFT: if (selected != 0) selected--; break;
			case '\n': switch (selected) {
							case 2: cycle = false; break;
							// default: warning_win("Ooops... It's not work...", 0); /*open_label = true;*/ break;
						}
			case 27: if (open_label) open_label = false;
					/*else shutdown_process();*/
					break;
		}
	}
	return 0;
}

#if LOCAL_TEST == 1
int main(/*...*/) {
	string user_name = "0";
	setlocale(LC_ALL, "");
	initscr();
	start_color();
	keypad (stdscr, TRUE);
	noecho();
	curs_set(0);
	erase();
	init_pair (1, COLOR_BLACK, COLOR_WHITE);
#else
int main_desktop(string user_name/*...*/) {
#endif
	local_user = user_name;
	work_desktop();
#if LOCAL_TEST == 1
	endwin();
#endif
	return 0;
}<commit_msg>Clean up<commit_after>//#include "../shutdown/shutdown.h"
#include "../windlg/windlg.h"
#include "../fswork/fswork.h"

#include <unistd.h>
#include <stdlib.h>
#include <vector>
#include <string>
#include <curses.h>

using namespace std;

string local_user;

int draw_desktop(int selected, bool open_label, bool new_draw, unsigned int maxX, unsigned int maxY) {
	unsigned x, y;
	if (new_draw) {
		for (x = 15; x < maxX; x++) mvprintw(0, x, "-");
		for (x = 0; x < maxX; x++) mvprintw(maxY - 1, x, "-");
		for (y = 0; y < maxY; y++) {mvprintw(y, 0, "|"); mvprintw(y, maxX - 1, "|");}
	}
		if (selected == 0) attron(COLOR_PAIR(1) | A_BOLD); // Белый цвет
		mvprintw(0, 1, "Menu");
		if (selected == 0) attroff(COLOR_PAIR(1) | A_BOLD);
		if (selected == 1) attron(COLOR_PAIR(1) | A_BOLD); // Белый цвет
		mvprintw(0, 6, "Edit");
		if (selected == 1) attroff(COLOR_PAIR(1) | A_BOLD);
		if (selected == 2) attron(COLOR_PAIR(1) | A_BOLD); // Белый цвет
		mvprintw(0, 11, "Exit");
		if (selected == 2) attroff(COLOR_PAIR(1) | A_BOLD);
	return 0;
}

int work_desktop() {
	unsigned int maxY, maxYb = 0, maxX, maxXb = 0;
	bool cycle = true, open_label = false, new_draw = false;
	int key_pressed, selected = 2;
	while (cycle) {
		getmaxyx(stdscr, maxY, maxX); // Получение размера терминала
		if ((maxX != maxXb) || (maxY != maxYb)) {
			new_draw = true;
			erase();
		}
		timeout(0);
		draw_desktop(selected, open_label, new_draw, maxX, maxY);
		new_draw = false;
		key_pressed = getch();
		switch (key_pressed) {
			case KEY_RIGHT: if (selected != 2) selected++; break;
			case KEY_LEFT: if (selected != 0) selected--; break;
			case '\n': switch (selected) {
							case 2: cycle = false; break;
							// default: warning_win("Ooops... It's not work...", 0); /*open_label = true;*/ break;
						}
			case 27: if (open_label) open_label = false;
					/*else shutdown_process();*/
					break;
		}
	}
	return 0;
}

int main_desktop(string user_name/*...*/) {
	local_user = user_name;
	work_desktop();
	return 0;
}<|endoftext|>


<commit_before>/*  This file is part of the Vc library.

    Copyright (C) 2009 Matthias Kretz <kretz@kde.org>

    Vc is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as
    published by the Free Software Foundation, either version 3 of
    the License, or (at your option) any later version.

    Vc 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 Vc.  If not, see <http://www.gnu.org/licenses/>.

*/

#include <Vc/Vc>
#include "unittest.h"

using namespace Vc;

template<typename V, unsigned int Size> struct TestEntries { static void run(); };
template<typename V> struct TestEntries<V, 0> { static void run() {} };

template<typename V, unsigned int Size> struct TestVectors { static void run(); };
template<typename V> struct TestVectors<V, 0> { static void run() {} };

template<typename V, unsigned int Size> struct TestVectorReorganization { static void run(); };
template<typename V> struct TestVectorReorganization<V, 0> { static void run() {} };

template<typename V, unsigned int Size> void TestEntries<V, Size>::run()
{
    TestEntries<V, Size - 1>::run();
    typedef typename V::EntryType T;
    const T x = Size;
    Memory<V, Size> m;
    const Memory<V, Size> &m2 = m;
    Memory<V> m3(Size);
    for (unsigned int i = 0; i < Size; ++i) {
        m[i] = x;
        m3[i] = x;
    }
    for (unsigned int i = 0; i < Size; ++i) {
        COMPARE(m[i], x);
        COMPARE(m2[i], x);
        COMPARE(m3[i], x);
    }
    for (unsigned int i = 0; i < Size; ++i) {
        COMPARE(m.entries()[i], x);
        COMPARE(m2.entries()[i], x);
        COMPARE(m3.entries()[i], x);
    }
    const T *ptr = m2;
    for (unsigned int i = 0; i < Size; ++i) {
        COMPARE(ptr[i], x);
    }
    ptr = m3;
    for (unsigned int i = 0; i < Size; ++i) {
        COMPARE(ptr[i], x);
    }
}

template<typename V, unsigned int Size> void TestVectors<V, Size>::run()
{
    TestVectors<V, Size - 1>::run();
    typedef typename V::EntryType T;
    const V x = Size;
    Memory<V, Size> m;
    const Memory<V, Size> &m2 = m;
    Memory<V> m3(Size);
    for (unsigned int i = 0; i < m.vectorsCount(); ++i) {
        x.store(m.vector(i));
        x.store(m3.vector(i));
    }
    for (unsigned int i = 0; i < m.vectorsCount(); ++i) {
        COMPARE(V(m.vector(i)), x);
        COMPARE(V(m2.vector(i)), x);
        COMPARE(V(m3.vector(i)), x);
    }
}

template<typename V, unsigned int Size> void TestVectorReorganization<V, Size>::run()
{
    TestVectors<V, Size - 1>::run();
    typedef typename V::EntryType T;
    typename V::Memory init;
    for (unsigned int i = 0; i < V::Size; ++i) {
        init[i] = i;
    }
    V x(init);
    Memory<V, Size> m;
    Memory<V> m3(Size);
    for (unsigned int i = 0; i < m.vectorsCount(); ++i) {
        x.store(m.vector(i));
        x.store(m3.vector(i));
        x += V::Size;
    }
    ///////////////////////////////////////////////////////////////////////////
    x = V(init);
    for (unsigned int i = 0; i < m.vectorsCount(); ++i) {
        COMPARE(V(m.vector(i)), x);
        COMPARE(V(m3.vector(i)), x);
        x += V::Size;
    }
    ///////////////////////////////////////////////////////////////////////////
    x = V(init);
    unsigned int indexes[Size];
    for (unsigned int i = 0; i < Size; ++i) {
        indexes[i] = i;
    }
    for (unsigned int i = 0; i < Size - V::Size; ++i) {
        COMPARE(m.gather(&indexes[i]), x);
        COMPARE(m3.gather(&indexes[i]), x);
        x += 1;
    }
    ///////////////////////////////////////////////////////////////////////////
    for (unsigned int i = 0; i < V::Size; ++i) {
        init[i] = i * 2;
    }
    x = V(init);
    for (unsigned int i = 0; i < Size; ++i) {
        indexes[i] = (i * 2) % Size;
    }
    for (unsigned int i = 0; i < Size - V::Size; ++i) {
        COMPARE(m.gather(&indexes[i]), x);
        COMPARE(m3.gather(&indexes[i]), x);
        x += 2;
        x(x >= Size) -= Size;
    }
}

template<typename V> void testEntries()
{
    TestEntries<V, 128>::run();
}

template<typename V> void testVectors()
{
    TestVectors<V, 128>::run();
}

template<typename V> void testVectorReorganization()
{
    TestVectorReorganization<V, 128>::run();
}

int main()
{
    testAllTypes(testEntries);
    testAllTypes(testVectors);
    testAllTypes(testVectorReorganization);

    return 0;
}
<commit_msg>add unit test for memory operators<commit_after>/*  This file is part of the Vc library.

    Copyright (C) 2009 Matthias Kretz <kretz@kde.org>

    Vc is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as
    published by the Free Software Foundation, either version 3 of
    the License, or (at your option) any later version.

    Vc 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 Vc.  If not, see <http://www.gnu.org/licenses/>.

*/

#include <Vc/Vc>
#include "unittest.h"

using namespace Vc;

template<typename V, unsigned int Size> struct TestEntries { static void run(); };
template<typename V> struct TestEntries<V, 0> { static void run() {} };

template<typename V, unsigned int Size> struct TestVectors { static void run(); };
template<typename V> struct TestVectors<V, 0> { static void run() {} };

template<typename V, unsigned int Size> struct TestVectorReorganization { static void run(); };
template<typename V> struct TestVectorReorganization<V, 0> { static void run() {} };

template<typename V, unsigned int Size> void TestEntries<V, Size>::run()
{
    TestEntries<V, Size - 1>::run();
    typedef typename V::EntryType T;
    const T x = Size;
    Memory<V, Size> m;
    const Memory<V, Size> &m2 = m;
    Memory<V> m3(Size);
    for (unsigned int i = 0; i < Size; ++i) {
        m[i] = x;
        m3[i] = x;
    }
    for (unsigned int i = 0; i < Size; ++i) {
        COMPARE(m[i], x);
        COMPARE(m2[i], x);
        COMPARE(m3[i], x);
    }
    for (unsigned int i = 0; i < Size; ++i) {
        COMPARE(m.entries()[i], x);
        COMPARE(m2.entries()[i], x);
        COMPARE(m3.entries()[i], x);
    }
    const T *ptr = m2;
    for (unsigned int i = 0; i < Size; ++i) {
        COMPARE(ptr[i], x);
    }
    ptr = m3;
    for (unsigned int i = 0; i < Size; ++i) {
        COMPARE(ptr[i], x);
    }
}

template<typename V, unsigned int Size> void TestVectors<V, Size>::run()
{
    TestVectors<V, Size - 1>::run();
    typedef typename V::EntryType T;
    const V x = Size;
    Memory<V, Size> m;
    const Memory<V, Size> &m2 = m;
    Memory<V> m3(Size);
    for (unsigned int i = 0; i < m.vectorsCount(); ++i) {
        x.store(m.vector(i));
        x.store(m3.vector(i));
    }
    for (unsigned int i = 0; i < m.vectorsCount(); ++i) {
        COMPARE(V(m.vector(i)), x);
        COMPARE(V(m2.vector(i)), x);
        COMPARE(V(m3.vector(i)), x);
    }
}

template<typename V, unsigned int Size> void TestVectorReorganization<V, Size>::run()
{
    TestVectors<V, Size - 1>::run();
    typedef typename V::EntryType T;
    typename V::Memory init;
    for (unsigned int i = 0; i < V::Size; ++i) {
        init[i] = i;
    }
    V x(init);
    Memory<V, Size> m;
    Memory<V> m3(Size);
    for (unsigned int i = 0; i < m.vectorsCount(); ++i) {
        x.store(m.vector(i));
        x.store(m3.vector(i));
        x += V::Size;
    }
    ///////////////////////////////////////////////////////////////////////////
    x = V(init);
    for (unsigned int i = 0; i < m.vectorsCount(); ++i) {
        COMPARE(V(m.vector(i)), x);
        COMPARE(V(m3.vector(i)), x);
        x += V::Size;
    }
    ///////////////////////////////////////////////////////////////////////////
    x = V(init);
    unsigned int indexes[Size];
    for (unsigned int i = 0; i < Size; ++i) {
        indexes[i] = i;
    }
    for (unsigned int i = 0; i < Size - V::Size; ++i) {
        COMPARE(m.gather(&indexes[i]), x);
        COMPARE(m3.gather(&indexes[i]), x);
        x += 1;
    }
    ///////////////////////////////////////////////////////////////////////////
    for (unsigned int i = 0; i < V::Size; ++i) {
        init[i] = i * 2;
    }
    x = V(init);
    for (unsigned int i = 0; i < Size; ++i) {
        indexes[i] = (i * 2) % Size;
    }
    for (unsigned int i = 0; i < Size - V::Size; ++i) {
        COMPARE(m.gather(&indexes[i]), x);
        COMPARE(m3.gather(&indexes[i]), x);
        x += 2;
        x(x >= Size) -= Size;
    }
}

template<typename V> void testEntries()
{
    TestEntries<V, 128>::run();
}

template<typename V> void testVectors()
{
    TestVectors<V, 128>::run();
}

template<typename V> void testVectorReorganization()
{
    TestVectorReorganization<V, 128>::run();
}

template<typename V> void memoryOperators()
{
    Memory<V, 129> m1, m2;
    m1.setZero();
    m2.setZero();
    VERIFY(m1 == m2);
    VERIFY(!(m1 != m2));
    VERIFY(!(m1 < m2));
    VERIFY(!(m1 > m2));
    m1 += m2;
    VERIFY(m1 == m2);
    VERIFY(m1 <= m2);
    VERIFY(m1 >= m2);
    m1 += 1;
    VERIFY(m1 != m2);
    VERIFY(m1 > m2);
    VERIFY(m1 >= m2);
    VERIFY(m2 < m1);
    VERIFY(m2 <= m1);
    VERIFY(!(m1 == m2));
    VERIFY(!(m1 <= m2));
    VERIFY(!(m2 >= m1));
    m2 += m1;
    VERIFY(m1 == m2);
    m2 *= 2;
    m1 += 1;
    VERIFY(m1 == m2);
    m2 /= 2;
    m1 -= 1;
    VERIFY(m1 == m2);
    m1 *= m2;
    VERIFY(m1 == m2);
    m1 /= m2;
    VERIFY(m1 == m2);
    m1 -= m2;
    m2 -= m2;
    VERIFY(m1 == m2);
}

int main()
{
    testAllTypes(testEntries);
    testAllTypes(testVectors);
    testAllTypes(testVectorReorganization);
    testAllTypes(memoryOperators);

    return 0;
}
<|endoftext|>


<commit_before>#ifndef LOCK_FREE_QUEUE_HPP
#define LOCK_FREE_QUEUE_HPP

#include <atomic>
#include <utility>

namespace ctl {
    /// Thread safe and lock free FIFO queue.
    /** Note: implementation is from:
        http://www.drdobbs.com/parallel/writing-lock-free-code-a-corrected-queue/210604448
    **/
    template<typename T>
    class lock_free_queue {
        struct node {
            node() : next(nullptr) {}
            template<typename U>
            node(U&& t) : data(std::forward<U>(t)), next(nullptr) {}

            T     data;
            node* next;
        };

        // Modified and read by 'procuder' only
        node* first_;
        // Modified and read by 'consumer', read by 'producer'
        std::atomic<node*> dummy_;
        // Modified and read by 'procuder', read by 'consumer'
        std::atomic<node*> last_;

    public :
        lock_free_queue() {
            // Always keep a dummy separator between head and tail
            first_ = last_ = dummy_ = new node();
        }

        ~lock_free_queue() {
            // Clear the whole queue
            while (first_ != nullptr) {
                node* temp = first_;
                first_ = temp->next;
                delete temp;
            }
        }

        lock_free_queue(const lock_free_queue& q) = delete;
        lock_free_queue& operator = (const lock_free_queue& q) = delete;

        /// Push a new element at the back of the queue.
        /** Called by the 'producer' thread only.
        **/
        template<typename U>
        void push(U&& t) {
            // Add the new item to the queue
            (*last_).next = new node(std::forward<U>(t));
            last_ = (*last_).next;

            // Clear consumed items
            while (first_ != dummy_) {
                node* temp = first_;
                first_ = temp->next;
                delete temp;
            }
        }

        /// Pop an element from the front of the queue.
        /** Called by the 'consumer' thread only.
        **/
        bool pop(T& t) {
            // Return false if queue is empty
            if (dummy_ != last_) {
                // Consume the value
                t = std::move((*dummy_).next->data);
                dummy_ = (*dummy_).next;
                return true;
            } else {
                return false;
            }
        }

        /// Compute the current number of elements in the queue.
        /** Called by the 'consumer' thread only.
            Note that the true size may actually be larger than the returned value if the
            'producer' thread pushes new elements while the size is computed.
        **/
        std::size_t size() const {
            node* tmp = dummy_.load();
            node* end = last_.load();
            std::size_t n = 0;

            while (tmp != end) {
                tmp = tmp->next;
                ++n;
            }

            return n;
        }

        /// Check if this queue is empty.
        /** Called by the 'consumer' thread only.
        **/
        bool empty() const {
            return dummy_ == last_;
        }

        /// Delete all elements from the queue.
        /** This method should not be used in concurrent situations
        **/
        void clear() {
            while (first_ != dummy_) {
                node* temp = first_;
                first_ = temp->next;
                delete temp;
            }

            first_ = dummy_.load();

            while (first_->next != nullptr) {
                node* temp = first_;
                first_ = temp->next;
                delete temp;
            }

            last_ = dummy_ = first_;
        }
    };
}

#endif
<commit_msg>Improved documentation of lock_free_queue<commit_after>#ifndef LOCK_FREE_QUEUE_HPP
#define LOCK_FREE_QUEUE_HPP

#include <atomic>
#include <utility>

namespace ctl {
    /// Thread safe and lock free FIFO queue.
    /// Single Procuder, Single Consumer (SPSC).
    /** Note: implementation is from:
        http://www.drdobbs.com/parallel/writing-lock-free-code-a-corrected-queue/210604448
    **/
    template<typename T>
    class lock_free_queue {
        struct node {
            node() : next(nullptr) {}
            template<typename U>
            node(U&& t) : data(std::forward<U>(t)), next(nullptr) {}

            T     data;
            node* next;
        };

        // Modified and read by 'procuder' only
        node* first_;
        // Modified and read by 'consumer', read by 'producer'
        std::atomic<node*> dummy_;
        // Modified and read by 'procuder', read by 'consumer'
        std::atomic<node*> last_;

    public :
        lock_free_queue() {
            // Always keep a dummy separator between head and tail
            first_ = last_ = dummy_ = new node();
        }

        ~lock_free_queue() {
            // Clear the whole queue
            while (first_ != nullptr) {
                node* temp = first_;
                first_ = temp->next;
                delete temp;
            }
        }

        lock_free_queue(const lock_free_queue& q) = delete;
        lock_free_queue& operator = (const lock_free_queue& q) = delete;

        /// Push a new element at the back of the queue.
        /** Called by the 'producer' thread only.
        **/
        template<typename U>
        void push(U&& t) {
            // Add the new item to the queue
            (*last_).next = new node(std::forward<U>(t));
            last_ = (*last_).next;

            // Clear consumed items
            while (first_ != dummy_) {
                node* temp = first_;
                first_ = temp->next;
                delete temp;
            }
        }

        /// Pop an element from the front of the queue.
        /** Called by the 'consumer' thread only.
        **/
        bool pop(T& t) {
            // Return false if queue is empty
            if (dummy_ != last_) {
                // Consume the value
                t = std::move((*dummy_).next->data);
                dummy_ = (*dummy_).next;
                return true;
            } else {
                return false;
            }
        }

        /// Compute the current number of elements in the queue.
        /** Called by the 'consumer' thread only.
            Note that the true size may actually be larger than the returned value if the
            'producer' thread pushes new elements while the size is computed.
        **/
        std::size_t size() const {
            node* tmp = dummy_.load();
            node* end = last_.load();
            std::size_t n = 0;

            while (tmp != end) {
                tmp = tmp->next;
                ++n;
            }

            return n;
        }

        /// Check if this queue is empty.
        /** Called by the 'consumer' thread only.
        **/
        bool empty() const {
            return dummy_ == last_;
        }

        /// Delete all elements from the queue.
        /** This method should not be used in concurrent situations
        **/
        void clear() {
            while (first_ != dummy_) {
                node* temp = first_;
                first_ = temp->next;
                delete temp;
            }

            first_ = dummy_.load();

            while (first_->next != nullptr) {
                node* temp = first_;
                first_ = temp->next;
                delete temp;
            }

            last_ = dummy_ = first_;
        }
    };
}

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: slideshowimpl.hxx,v $
 *
 *  $Revision: 1.18 $
 *
 *  last change: $Author: obo $ $Date: 2006-07-13 09:54:14 $
 *
 *  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 _SD_SLIDESHOWIMPL_HXX_
#define _SD_SLIDESHOWIMPL_HXX_

#ifndef _CPPUHELPER_COMPBASE2_HXX_
#include <cppuhelper/compbase2.hxx>
#endif
#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif
#ifndef COMPHELPER_INC_COMPHELPER_LISTENERNOTIFICATION_HXX
#include <comphelper/listenernotification.hxx>
#endif

#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/helper/vclunohelper.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef _COM_SUN_STAR_AWT_WINDOWEVENT_HPP_
#include <com/sun/star/awt/WindowEvent.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOWLISTENER_HPP_
#include <com/sun/star/awt/XWindowListener.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOWPEER_HPP_
#include <com/sun/star/awt/XWindowPeer.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XMODIFYLISTENER_HPP_
#include <com/sun/star/util/XModifyListener.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XPAINTLISTENER_HPP_
#include <com/sun/star/awt/XPaintListener.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XPOINTER_HPP_
#include <com/sun/star/awt/XPointer.hpp>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_XSLIDESHOW_HPP_
#include <com/sun/star/presentation/XSlideShow.hpp>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_XSLIDESHOWVIEW_HPP_
#include <com/sun/star/presentation/XSlideShowView.hpp>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_XSLIDESHOWLISTENER_HPP_
#include <com/sun/star/presentation/XSlideShowListener.hpp>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_XSHAPEEVENTLISTENER_HPP_
#include <com/sun/star/presentation/XShapeEventListener.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGESSUPPLIER_HPP_
#include <com/sun/star/drawing/XDrawPagesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_ANIMATIONS_XANIMATIONNODESUPPLIER_HPP_
#include <com/sun/star/animations/XAnimationNodeSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_CLICKACTION_HPP_
#include <com/sun/star/presentation/ClickAction.hpp>
#endif
#ifndef _COM_SUN_STAR_MEDIA_XMANAGER_HPP_
#include <com/sun/star/media/XManager.hpp>
#endif
#ifndef _COM_SUN_STAR_MEDIA_XPLAYER_HPP_
#include <com/sun/star/media/XPlayer.hpp>
#endif

#ifndef _COMPHELPER_IMPLEMENTATIONREFERENCE_HXX
#include <comphelper/implementationreference.hxx>
#endif

#ifndef _BGFX_MATRIX_B2DHOMMATRIX_HXX
#include <basegfx/matrix/b2dhommatrix.hxx>
#endif
#ifndef _BGFX_TOOLS_CANVASTOOLS_HXX
#include <basegfx/tools/canvastools.hxx>
#endif

#ifndef _SV_HELP_HXX //autogen
#include <vcl/help.hxx>
#endif

#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif

#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif

#ifndef INCLUDED_SVTOOLS_SAVEOPT_HXX
#include <svtools/saveopt.hxx>
#endif

#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif

#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif

#ifndef _SFXVIEWFRM_HXX
#include <sfx2/viewfrm.hxx>
#endif

#ifndef _SB_SBSTAR_HXX //autogen
#include <basic/sbstar.hxx>
#endif

#ifndef _SVDPAGV_HXX
#include <svx/svdpagv.hxx>
#endif

#ifndef _SVX_FMSHELL_HXX
#include <svx/fmshell.hxx>
#endif

#ifndef _SVX_SVXIDS_HRC
#include <svx/svxids.hrc>
#endif

#ifndef _SDMOD_HXX
#include "sdmod.hxx"
#endif

#ifndef _SD_CUSSHOW_HXX
#include "cusshow.hxx"
#endif

#ifndef SD_VIEW_SHELL_BASE_HXX
#include "ViewShellBase.hxx"
#endif

#ifndef SD_PRESENTATION_VIEW_SHELL_HXX
#include "PresentationViewShell.hxx"
#endif

#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif

#ifndef SD_DRAW_VIEW_HXX
#include "drawview.hxx"
#endif

#ifndef _DRAWDOC_HXX
#include "drawdoc.hxx"
#endif

#ifndef SD_SHOW_WINDOW_HXX
#include "ShowWindow.hxx"
#endif

#ifndef _SD_OPTSITEM_HXX
#include "optsitem.hxx"
#endif

#ifndef SD_FRAME_VIEW_HXX
#include "FrameView.hxx"
#endif

#ifndef SD_DRAW_DOC_SHELL_HXX
#include "DrawDocShell.hxx"
#endif

#ifndef _SD_APP_HRC_
#include "app.hrc"
#endif

#include "slideshow.hxx"

class SfxViewFrame;
class SfxRequest;

namespace sd
{
class SlideShowView;
class AnimationSlideController;
class PaneHider;

struct WrappedShapeEventImpl
{
    ::com::sun::star::presentation::ClickAction meClickAction;
    sal_Int32 mnVerb;
    ::rtl::OUString maStrBookmark;
    WrappedShapeEventImpl() : meClickAction( ::com::sun::star::presentation::ClickAction_NONE ), mnVerb( 0 ) {};
};

typedef boost::shared_ptr< WrappedShapeEventImpl > WrappedShapeEventImplPtr;
typedef std::map< ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >, WrappedShapeEventImplPtr > WrappedShapeEventImplMap;

typedef ::cppu::WeakComponentImplHelper2< ::com::sun::star::presentation::XShapeEventListener,
        ::com::sun::star::presentation::XSlideShowListener > SlideshowImpl_base;

class SlideshowImpl : public ::comphelper::OBaseMutex, public SlideshowImpl_base
{
    friend class Slideshow;
public:
    SlideshowImpl( ViewShell* pViewSh, ::sd::View* pView, SdDrawDocument* pDoc );
    ~SlideshowImpl();

    bool startShow( PresentationSettings* pPresSettings );
    bool startPreview(
        const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage >& xDrawPage,
        const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xAnimationNode,
        ::Window* pParent = 0 );

    void stopShow();

    double update();
    /** forces an async call to update in the main thread */
    void startUpdateTimer();
    void paint( const Rectangle& rRect );
    bool keyInput(const KeyEvent& rKEvt);
    void mouseButtonUp(const MouseEvent& rMEvt);

    void createSlideList( bool bAll, bool bStartWithActualSlide, const String& rPresSlide );

    void stopSound();

    void displayCurrentSlide();

    void displaySlideNumber( sal_Int32 nSlide );
    void displaySlideIndex( sal_Int32 nIndex );
    sal_Int32 getCurrentSlideNumber();
    sal_Int32 getCurrentSlideIndex();
    sal_Int32 getFirstSlideNumber();
    sal_Int32 getLastSlideNumber();
    bool isEndless();
    bool isDrawingPossible();
    inline bool isInputFreezed() const;

    void jumpToBookmark( const String& sBookmark );

    void activate();
    void deactivate();

    void hideChildWindows();
    void showChildWindows();

    void resize( const Size& rSize );

    DECL_LINK( updateHdl, Timer* );
    DECL_LINK( ReadyForNextInputHdl, Timer* );
    DECL_LINK( endPresentationHdl, void* );
    DECL_LINK( ContextMenuSelectHdl, Menu * );
    DECL_LINK( ContextMenuHdl, void* );

    // XShapeEventListener
    virtual void SAL_CALL click( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >& xShape, const ::com::sun::star::awt::MouseEvent& aOriginalEvent ) throw (::com::sun::star::uno::RuntimeException);

    // XSlideShowListener
    virtual void SAL_CALL slideEnded() throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL hyperLinkClicked( ::rtl::OUString const& hyperLink )
        throw (::com::sun::star::uno::RuntimeException);

    // XEventListener
    virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException);

    // helper
    void gotoNextEffect();
    void gotoPreviousSlide();
    void gotoNextSlide();
    void gotoFirstSlide();
    void gotoLastSlide();
    void endPresentation();
    void enablePen();

    bool pause( bool bPause );

    void receiveRequest(SfxRequest& rReq);

    /** called only by the slideshow view when the first paint event occurs.
        This actually starts the slideshow. */
    void onFirstPaint();

    ShowWindow* getShowWindow() const { return mpShowWindow; }

private:
    bool startShowImpl(
        const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aProperties );

    SfxViewFrame* getViewFrame() const;

    sal_Int32 getSlideNumberForBookmark( const rtl::OUString& rStrBookmark );

    void removeShapeEvents();
    void registerShapeEvents( sal_Int32 nSlideNumber );
    void registerShapeEvents( ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >& xShapes ) throw (::com::sun::star::uno::Exception);

    // default: disabled copy/assignment
    SlideshowImpl(const SlideshowImpl&);
    SlideshowImpl& operator=( const SlideshowImpl& );

    ::com::sun::star::uno::Reference< ::com::sun::star::presentation::XSlideShow > createSlideShow() const;

    ::com::sun::star::uno::Reference< ::com::sun::star::presentation::XSlideShow > mxShow;
    comphelper::ImplementationReference< ::sd::SlideShowView, ::com::sun::star::presentation::XSlideShowView > mxView;
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > mxModel;

    Timer maUpdateTimer;
    Timer maInputFreezeTimer;

    ::sd::View* mpView;
    ViewShell* mpViewShell;
    DrawDocShell* mpDocSh;
    SdDrawDocument* mpDoc;

    SfxItemSet*     mpNewAttr;
    ShowWindow*     mpShowWindow;
    SvtSaveOptions* mpSaveOptions;
    PushButton*     mpTimeButton;

    boost::shared_ptr< AnimationSlideController > mpSlideController;

    long            mnRestoreSlide;
    Point           maSlideOrigin;
    Point           maPopupMousePos;
    Size            maSlideSize;
    Size            maPresSize;
    AnimationMode   meAnimationMode;
    String          maCharBuffer;
    Pointer         maOldPointer;
    Pointer         maPencil;
    std::vector< ::sd::Window* > maDrawModeWindows;
    ::sd::Window*   mpOldActiveWindow;
    Link            maStarBASICGlobalErrorHdl;
    unsigned long   mnChildMask;
    bool            mbGridVisible;
    bool            mbBordVisible;
    bool            mbSlideBorderVisible;
    bool            mbSetOnlineSpelling;
    bool            mbDisposed;
    bool            mbMouseIsDrawing;
    bool            mbAutoSaveSuppressed;
    bool            mbRehearseTimings;
    bool            mbDesignMode;
    bool            mbIsPaused;
    bool            mbWasPaused;        // used to cache pause state during context menu
    bool            mbInputFreeze;

    PresentationSettings maPresSettings;

    /// used in updateHdl to prevent recursive calls
    sal_Int32       mnEntryCounter;

    sal_Int32       mnLastSlideNumber;
    WrappedShapeEventImplMap    maShapeEventMap;

    ::rtl::OUString msOnClick;
    ::rtl::OUString msBookmark;
    ::rtl::OUString msVerb;

    ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage > mxPreviewDrawPage;
    ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode > mxPreviewAnimationNode;

    ::com::sun::star::uno::Reference< ::com::sun::star::media::XPlayer > mxPlayer;
    ::com::sun::star::uno::Reference< ::com::sun::star::media::XManager > mxManager;

    ::std::auto_ptr<PaneHider> mpPaneHider;

    ULONG   mnEndShowEvent;
};

class SlideShowImplGuard
{
public:
    SlideShowImplGuard( SlideshowImpl* pImpl );
    ~SlideShowImplGuard();

private:
    SlideshowImpl* mpImpl;
};

bool SlideshowImpl::isInputFreezed() const
{
    return mbInputFreeze;
}

} // namespace ::sd

#endif
<commit_msg>INTEGRATION: CWS impress107 (1.18.62); FILE MERGED 2006/09/18 13:53:29 cl 1.18.62.1: #i69449# check for not available viewframe<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: slideshowimpl.hxx,v $
 *
 *  $Revision: 1.19 $
 *
 *  last change: $Author: kz $ $Date: 2006-10-06 10:38:07 $
 *
 *  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 _SD_SLIDESHOWIMPL_HXX_
#define _SD_SLIDESHOWIMPL_HXX_

#ifndef _CPPUHELPER_COMPBASE2_HXX_
#include <cppuhelper/compbase2.hxx>
#endif
#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif
#ifndef COMPHELPER_INC_COMPHELPER_LISTENERNOTIFICATION_HXX
#include <comphelper/listenernotification.hxx>
#endif

#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/helper/vclunohelper.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef _COM_SUN_STAR_AWT_WINDOWEVENT_HPP_
#include <com/sun/star/awt/WindowEvent.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOWLISTENER_HPP_
#include <com/sun/star/awt/XWindowListener.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOWPEER_HPP_
#include <com/sun/star/awt/XWindowPeer.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XMODIFYLISTENER_HPP_
#include <com/sun/star/util/XModifyListener.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XPAINTLISTENER_HPP_
#include <com/sun/star/awt/XPaintListener.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XPOINTER_HPP_
#include <com/sun/star/awt/XPointer.hpp>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_XSLIDESHOW_HPP_
#include <com/sun/star/presentation/XSlideShow.hpp>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_XSLIDESHOWVIEW_HPP_
#include <com/sun/star/presentation/XSlideShowView.hpp>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_XSLIDESHOWLISTENER_HPP_
#include <com/sun/star/presentation/XSlideShowListener.hpp>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_XSHAPEEVENTLISTENER_HPP_
#include <com/sun/star/presentation/XShapeEventListener.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGESSUPPLIER_HPP_
#include <com/sun/star/drawing/XDrawPagesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_ANIMATIONS_XANIMATIONNODESUPPLIER_HPP_
#include <com/sun/star/animations/XAnimationNodeSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_PRESENTATION_CLICKACTION_HPP_
#include <com/sun/star/presentation/ClickAction.hpp>
#endif
#ifndef _COM_SUN_STAR_MEDIA_XMANAGER_HPP_
#include <com/sun/star/media/XManager.hpp>
#endif
#ifndef _COM_SUN_STAR_MEDIA_XPLAYER_HPP_
#include <com/sun/star/media/XPlayer.hpp>
#endif

#ifndef _COMPHELPER_IMPLEMENTATIONREFERENCE_HXX
#include <comphelper/implementationreference.hxx>
#endif

#ifndef _BGFX_MATRIX_B2DHOMMATRIX_HXX
#include <basegfx/matrix/b2dhommatrix.hxx>
#endif
#ifndef _BGFX_TOOLS_CANVASTOOLS_HXX
#include <basegfx/tools/canvastools.hxx>
#endif

#ifndef _SV_HELP_HXX //autogen
#include <vcl/help.hxx>
#endif

#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif

#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif

#ifndef INCLUDED_SVTOOLS_SAVEOPT_HXX
#include <svtools/saveopt.hxx>
#endif

#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif

#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif

#ifndef _SFXVIEWFRM_HXX
#include <sfx2/viewfrm.hxx>
#endif

#ifndef _SB_SBSTAR_HXX //autogen
#include <basic/sbstar.hxx>
#endif

#ifndef _SVDPAGV_HXX
#include <svx/svdpagv.hxx>
#endif

#ifndef _SVX_FMSHELL_HXX
#include <svx/fmshell.hxx>
#endif

#ifndef _SVX_SVXIDS_HRC
#include <svx/svxids.hrc>
#endif

#ifndef _SDMOD_HXX
#include "sdmod.hxx"
#endif

#ifndef _SD_CUSSHOW_HXX
#include "cusshow.hxx"
#endif

#ifndef SD_VIEW_SHELL_BASE_HXX
#include "ViewShellBase.hxx"
#endif

#ifndef SD_PRESENTATION_VIEW_SHELL_HXX
#include "PresentationViewShell.hxx"
#endif

#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif

#ifndef SD_DRAW_VIEW_HXX
#include "drawview.hxx"
#endif

#ifndef _DRAWDOC_HXX
#include "drawdoc.hxx"
#endif

#ifndef SD_SHOW_WINDOW_HXX
#include "ShowWindow.hxx"
#endif

#ifndef _SD_OPTSITEM_HXX
#include "optsitem.hxx"
#endif

#ifndef SD_FRAME_VIEW_HXX
#include "FrameView.hxx"
#endif

#ifndef SD_DRAW_DOC_SHELL_HXX
#include "DrawDocShell.hxx"
#endif

#ifndef _SD_APP_HRC_
#include "app.hrc"
#endif

#include "slideshow.hxx"

class SfxViewFrame;
class SfxRequest;

namespace sd
{
class SlideShowView;
class AnimationSlideController;
class PaneHider;

struct WrappedShapeEventImpl
{
    ::com::sun::star::presentation::ClickAction meClickAction;
    sal_Int32 mnVerb;
    ::rtl::OUString maStrBookmark;
    WrappedShapeEventImpl() : meClickAction( ::com::sun::star::presentation::ClickAction_NONE ), mnVerb( 0 ) {};
};

typedef boost::shared_ptr< WrappedShapeEventImpl > WrappedShapeEventImplPtr;
typedef std::map< ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >, WrappedShapeEventImplPtr > WrappedShapeEventImplMap;

typedef ::cppu::WeakComponentImplHelper2< ::com::sun::star::presentation::XShapeEventListener,
        ::com::sun::star::presentation::XSlideShowListener > SlideshowImpl_base;

class SlideshowImpl : public ::comphelper::OBaseMutex, public SlideshowImpl_base
{
    friend class Slideshow;
public:
    SlideshowImpl( ViewShell* pViewSh, ::sd::View* pView, SdDrawDocument* pDoc );
    ~SlideshowImpl();

    bool startShow( PresentationSettings* pPresSettings );
    bool startPreview(
        const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage >& xDrawPage,
        const ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode >& xAnimationNode,
        ::Window* pParent = 0 );

    void stopShow();

    double update();
    /** forces an async call to update in the main thread */
    void startUpdateTimer();
    void paint( const Rectangle& rRect );
    bool keyInput(const KeyEvent& rKEvt);
    void mouseButtonUp(const MouseEvent& rMEvt);

    void createSlideList( bool bAll, bool bStartWithActualSlide, const String& rPresSlide );

    void stopSound();

    void displayCurrentSlide();

    void displaySlideNumber( sal_Int32 nSlide );
    void displaySlideIndex( sal_Int32 nIndex );
    sal_Int32 getCurrentSlideNumber();
    sal_Int32 getCurrentSlideIndex();
    sal_Int32 getFirstSlideNumber();
    sal_Int32 getLastSlideNumber();
    bool isEndless();
    bool isDrawingPossible();
    inline bool isInputFreezed() const;

    void jumpToBookmark( const String& sBookmark );

    void activate();
    void deactivate();

    void hideChildWindows();
    void showChildWindows();

    void resize( const Size& rSize );

    DECL_LINK( updateHdl, Timer* );
    DECL_LINK( ReadyForNextInputHdl, Timer* );
    DECL_LINK( endPresentationHdl, void* );
    DECL_LINK( ContextMenuSelectHdl, Menu * );
    DECL_LINK( ContextMenuHdl, void* );

    // XShapeEventListener
    virtual void SAL_CALL click( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >& xShape, const ::com::sun::star::awt::MouseEvent& aOriginalEvent ) throw (::com::sun::star::uno::RuntimeException);

    // XSlideShowListener
    virtual void SAL_CALL slideEnded() throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL hyperLinkClicked( ::rtl::OUString const& hyperLink )
        throw (::com::sun::star::uno::RuntimeException);

    // XEventListener
    virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException);

    // helper
    void gotoNextEffect();
    void gotoPreviousSlide();
    void gotoNextSlide();
    void gotoFirstSlide();
    void gotoLastSlide();
    void endPresentation();
    void enablePen();

    bool pause( bool bPause );

    void receiveRequest(SfxRequest& rReq);

    /** called only by the slideshow view when the first paint event occurs.
        This actually starts the slideshow. */
    void onFirstPaint();

    ShowWindow* getShowWindow() const { return mpShowWindow; }

private:
    bool startShowImpl(
        const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aProperties );

    SfxViewFrame* getViewFrame() const;
    SfxDispatcher* getDispatcher() const;
    SfxBindings* getBindings() const;

    sal_Int32 getSlideNumberForBookmark( const rtl::OUString& rStrBookmark );

    void removeShapeEvents();
    void registerShapeEvents( sal_Int32 nSlideNumber );
    void registerShapeEvents( ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >& xShapes ) throw (::com::sun::star::uno::Exception);

    // default: disabled copy/assignment
    SlideshowImpl(const SlideshowImpl&);
    SlideshowImpl& operator=( const SlideshowImpl& );

    ::com::sun::star::uno::Reference< ::com::sun::star::presentation::XSlideShow > createSlideShow() const;

    ::com::sun::star::uno::Reference< ::com::sun::star::presentation::XSlideShow > mxShow;
    comphelper::ImplementationReference< ::sd::SlideShowView, ::com::sun::star::presentation::XSlideShowView > mxView;
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > mxModel;

    Timer maUpdateTimer;
    Timer maInputFreezeTimer;

    ::sd::View* mpView;
    ViewShell* mpViewShell;
    DrawDocShell* mpDocSh;
    SdDrawDocument* mpDoc;

    SfxItemSet*     mpNewAttr;
    ShowWindow*     mpShowWindow;
    SvtSaveOptions* mpSaveOptions;
    PushButton*     mpTimeButton;

    boost::shared_ptr< AnimationSlideController > mpSlideController;

    long            mnRestoreSlide;
    Point           maSlideOrigin;
    Point           maPopupMousePos;
    Size            maSlideSize;
    Size            maPresSize;
    AnimationMode   meAnimationMode;
    String          maCharBuffer;
    Pointer         maOldPointer;
    Pointer         maPencil;
    std::vector< ::sd::Window* > maDrawModeWindows;
    ::sd::Window*   mpOldActiveWindow;
    Link            maStarBASICGlobalErrorHdl;
    unsigned long   mnChildMask;
    bool            mbGridVisible;
    bool            mbBordVisible;
    bool            mbSlideBorderVisible;
    bool            mbSetOnlineSpelling;
    bool            mbDisposed;
    bool            mbMouseIsDrawing;
    bool            mbAutoSaveSuppressed;
    bool            mbRehearseTimings;
    bool            mbDesignMode;
    bool            mbIsPaused;
    bool            mbWasPaused;        // used to cache pause state during context menu
    bool            mbInputFreeze;

    PresentationSettings maPresSettings;

    /// used in updateHdl to prevent recursive calls
    sal_Int32       mnEntryCounter;

    sal_Int32       mnLastSlideNumber;
    WrappedShapeEventImplMap    maShapeEventMap;

    ::rtl::OUString msOnClick;
    ::rtl::OUString msBookmark;
    ::rtl::OUString msVerb;

    ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage > mxPreviewDrawPage;
    ::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode > mxPreviewAnimationNode;

    ::com::sun::star::uno::Reference< ::com::sun::star::media::XPlayer > mxPlayer;
    ::com::sun::star::uno::Reference< ::com::sun::star::media::XManager > mxManager;

    ::std::auto_ptr<PaneHider> mpPaneHider;

    ULONG   mnEndShowEvent;
};

class SlideShowImplGuard
{
public:
    SlideShowImplGuard( SlideshowImpl* pImpl );
    ~SlideShowImplGuard();

private:
    SlideshowImpl* mpImpl;
};

bool SlideshowImpl::isInputFreezed() const
{
    return mbInputFreeze;
}

} // namespace ::sd

#endif
<|endoftext|>