<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 "modulepcr.hxx"
#include "pcrcommon.hxx"
#include "inspectormodelbase.hxx"

#include <com/sun/star/ucb/AlreadyInitializedException.hpp>
#include <com/sun/star/lang/IllegalArgumentException.hpp>

#include <cppuhelper/implbase3.hxx>

#include <comphelper/broadcasthelper.hxx>
#include <comphelper/uno3.hxx>

//........................................................................
namespace pcr
{
//........................................................................

    using ::com::sun::star::inspection::XObjectInspectorModel;
    using ::com::sun::star::lang::XInitialization;
    using ::com::sun::star::lang::XServiceInfo;
    using ::com::sun::star::uno::Reference;
    using ::com::sun::star::uno::XComponentContext;
    using ::com::sun::star::uno::RuntimeException;
    using ::com::sun::star::uno::Sequence;
    using ::com::sun::star::uno::Any;
    using ::com::sun::star::inspection::PropertyCategoryDescriptor;
    using ::com::sun::star::uno::Exception;
    using ::com::sun::star::uno::XInterface;
    using ::com::sun::star::lang::IllegalArgumentException;
    using ::com::sun::star::ucb::AlreadyInitializedException;
    using ::com::sun::star::beans::XPropertySetInfo;
    using ::com::sun::star::uno::makeAny;

    //====================================================================
    //= ObjectInspectorModel
    //====================================================================
    class ObjectInspectorModel : public ImplInspectorModel
    {
    private:
        Sequence< Any >             m_aFactories;

    public:
        ObjectInspectorModel();

        // XObjectInspectorModel
        virtual Sequence< Any > SAL_CALL getHandlerFactories() throw (RuntimeException);
        virtual Sequence< PropertyCategoryDescriptor > SAL_CALL describeCategories(  ) throw (RuntimeException);
        virtual ::sal_Int32 SAL_CALL getPropertyOrderIndex( const OUString& PropertyName ) throw (RuntimeException);

        // XInitialization
        virtual void SAL_CALL initialize( const Sequence< Any >& aArguments ) throw (Exception, RuntimeException);

        // XServiceInfo
        virtual OUString SAL_CALL getImplementationName(  ) throw (RuntimeException);
        virtual Sequence< OUString > SAL_CALL getSupportedServiceNames(  ) throw (RuntimeException);

        // XServiceInfo - static versions
        static OUString getImplementationName_static(  ) throw(RuntimeException);
        static Sequence< OUString > getSupportedServiceNames_static(  ) throw(RuntimeException);
        static Reference< XInterface > SAL_CALL
                        Create(const Reference< XComponentContext >&);

    protected:
        void    createDefault();
        void    createWithHandlerFactories( const Sequence< Any >& _rFactories );
        void    createWithHandlerFactoriesAndHelpSection( const Sequence< Any >& _rFactories, sal_Int32 _nMinHelpTextLines, sal_Int32 _nMaxHelpTextLines );

    private:
        /** checks a given condition to be <TRUE/>, and throws an IllegalArgumentException if not
        */
        void    impl_verifyArgument_throw( bool _bCondition, sal_Int16 _nArgumentPosition );
    };

    //====================================================================
    //= ObjectInspectorModel
    //====================================================================
    ObjectInspectorModel::ObjectInspectorModel()
        :ImplInspectorModel()
    {
    }

    //--------------------------------------------------------------------
    Sequence< Any > SAL_CALL ObjectInspectorModel::getHandlerFactories() throw (RuntimeException)
    {
        return m_aFactories;
    }

    //--------------------------------------------------------------------
    Sequence< PropertyCategoryDescriptor > SAL_CALL ObjectInspectorModel::describeCategories(  ) throw (RuntimeException)
    {
        // no category info provided by this default implementation
        return Sequence< PropertyCategoryDescriptor >( );
    }

    //--------------------------------------------------------------------
    ::sal_Int32 SAL_CALL ObjectInspectorModel::getPropertyOrderIndex( const OUString& /*PropertyName*/ ) throw (RuntimeException)
    {
        // no ordering provided by this default implementation
        return 0;
    }

    //--------------------------------------------------------------------
    void SAL_CALL ObjectInspectorModel::initialize( const Sequence< Any >& _arguments ) throw (Exception, RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex );
        if ( m_aFactories.getLength() )
            throw AlreadyInitializedException();

        StlSyntaxSequence< Any > arguments( _arguments );
        if ( arguments.empty() )
        {   // constructor: "createDefault()"
            createDefault();
            return;
        }

        Sequence< Any > factories;
        impl_verifyArgument_throw( arguments[0] >>= factories, 1 );

        if ( arguments.size() == 1 )
        {   // constructor: "createWithHandlerFactories( any[] )"
            createWithHandlerFactories( factories );
            return;
        }

        sal_Int32 nMinHelpTextLines( 0 ), nMaxHelpTextLines( 0 );
        if ( arguments.size() == 3 )
        {   // constructor: "createWithHandlerFactoriesAndHelpSection( any[], long, long )"
            impl_verifyArgument_throw( arguments[1] >>= nMinHelpTextLines, 2 );
            impl_verifyArgument_throw( arguments[2] >>= nMaxHelpTextLines, 3 );
            createWithHandlerFactoriesAndHelpSection( factories, nMinHelpTextLines, nMaxHelpTextLines );
            return;
        }

        impl_verifyArgument_throw( false, 2 );
    }

    //--------------------------------------------------------------------
    OUString SAL_CALL ObjectInspectorModel::getImplementationName(  ) throw (RuntimeException)
    {
        return getImplementationName_static();
    }

    //--------------------------------------------------------------------
    Sequence< OUString > SAL_CALL ObjectInspectorModel::getSupportedServiceNames(  ) throw (RuntimeException)
    {
        return getSupportedServiceNames_static();
    }

    //--------------------------------------------------------------------
    OUString ObjectInspectorModel::getImplementationName_static(  ) throw(RuntimeException)
    {
        return OUString( "org.openoffice.comp.extensions.ObjectInspectorModel" );
    }

    //--------------------------------------------------------------------
    Sequence< OUString > ObjectInspectorModel::getSupportedServiceNames_static(  ) throw(RuntimeException)
    {
        OUString sService( "com.sun.star.inspection.ObjectInspectorModel" );
        return Sequence< OUString >( &sService, 1 );
    }

    //--------------------------------------------------------------------
    Reference< XInterface > SAL_CALL ObjectInspectorModel::Create(const Reference< XComponentContext >& _rxContext )
    {
        return *( new ObjectInspectorModel() );
    }

    //--------------------------------------------------------------------
    void ObjectInspectorModel::createDefault()
    {
        m_aFactories.realloc( 1 );
        m_aFactories[0] <<= OUString( "com.sun.star.inspection.GenericPropertyHandler" );
    }

    //--------------------------------------------------------------------
    void ObjectInspectorModel::createWithHandlerFactories( const Sequence< Any >& _rFactories )
    {
        impl_verifyArgument_throw( _rFactories.getLength() > 0, 1 );
        m_aFactories = _rFactories;
    }

    //--------------------------------------------------------------------
    void ObjectInspectorModel::createWithHandlerFactoriesAndHelpSection( const Sequence< Any >& _rFactories, sal_Int32 _nMinHelpTextLines, sal_Int32 _nMaxHelpTextLines )
    {
        impl_verifyArgument_throw( _rFactories.getLength() > 0, 1 );
        impl_verifyArgument_throw( _nMinHelpTextLines >= 1, 2 );
        impl_verifyArgument_throw( _nMaxHelpTextLines >= 1, 3 );
        impl_verifyArgument_throw( _nMinHelpTextLines <= _nMaxHelpTextLines, 2 );

        m_aFactories = _rFactories;
        enableHelpSectionProperties( _nMinHelpTextLines, _nMaxHelpTextLines );
    }

    //--------------------------------------------------------------------
    void ObjectInspectorModel::impl_verifyArgument_throw( bool _bCondition, sal_Int16 _nArgumentPosition )
    {
        if ( !_bCondition )
            throw IllegalArgumentException( OUString(), *this, _nArgumentPosition );
    }

//........................................................................
} // namespace pcr
//........................................................................

//------------------------------------------------------------------------
extern "C" void SAL_CALL createRegistryInfo_ObjectInspectorModel()
{
    ::pcr::OAutoRegistration< ::pcr::ObjectInspectorModel > aObjectInspectorModelRegistration;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>WaE: unused parameter '_rxContext'<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 "modulepcr.hxx"
#include "pcrcommon.hxx"
#include "inspectormodelbase.hxx"

#include <com/sun/star/ucb/AlreadyInitializedException.hpp>
#include <com/sun/star/lang/IllegalArgumentException.hpp>

#include <cppuhelper/implbase3.hxx>

#include <comphelper/broadcasthelper.hxx>
#include <comphelper/uno3.hxx>

//........................................................................
namespace pcr
{
//........................................................................

    using ::com::sun::star::inspection::XObjectInspectorModel;
    using ::com::sun::star::lang::XInitialization;
    using ::com::sun::star::lang::XServiceInfo;
    using ::com::sun::star::uno::Reference;
    using ::com::sun::star::uno::XComponentContext;
    using ::com::sun::star::uno::RuntimeException;
    using ::com::sun::star::uno::Sequence;
    using ::com::sun::star::uno::Any;
    using ::com::sun::star::inspection::PropertyCategoryDescriptor;
    using ::com::sun::star::uno::Exception;
    using ::com::sun::star::uno::XInterface;
    using ::com::sun::star::lang::IllegalArgumentException;
    using ::com::sun::star::ucb::AlreadyInitializedException;
    using ::com::sun::star::beans::XPropertySetInfo;
    using ::com::sun::star::uno::makeAny;

    //====================================================================
    //= ObjectInspectorModel
    //====================================================================
    class ObjectInspectorModel : public ImplInspectorModel
    {
    private:
        Sequence< Any >             m_aFactories;

    public:
        ObjectInspectorModel();

        // XObjectInspectorModel
        virtual Sequence< Any > SAL_CALL getHandlerFactories() throw (RuntimeException);
        virtual Sequence< PropertyCategoryDescriptor > SAL_CALL describeCategories(  ) throw (RuntimeException);
        virtual ::sal_Int32 SAL_CALL getPropertyOrderIndex( const OUString& PropertyName ) throw (RuntimeException);

        // XInitialization
        virtual void SAL_CALL initialize( const Sequence< Any >& aArguments ) throw (Exception, RuntimeException);

        // XServiceInfo
        virtual OUString SAL_CALL getImplementationName(  ) throw (RuntimeException);
        virtual Sequence< OUString > SAL_CALL getSupportedServiceNames(  ) throw (RuntimeException);

        // XServiceInfo - static versions
        static OUString getImplementationName_static(  ) throw(RuntimeException);
        static Sequence< OUString > getSupportedServiceNames_static(  ) throw(RuntimeException);
        static Reference< XInterface > SAL_CALL
                        Create(const Reference< XComponentContext >&);

    protected:
        void    createDefault();
        void    createWithHandlerFactories( const Sequence< Any >& _rFactories );
        void    createWithHandlerFactoriesAndHelpSection( const Sequence< Any >& _rFactories, sal_Int32 _nMinHelpTextLines, sal_Int32 _nMaxHelpTextLines );

    private:
        /** checks a given condition to be <TRUE/>, and throws an IllegalArgumentException if not
        */
        void    impl_verifyArgument_throw( bool _bCondition, sal_Int16 _nArgumentPosition );
    };

    //====================================================================
    //= ObjectInspectorModel
    //====================================================================
    ObjectInspectorModel::ObjectInspectorModel()
        :ImplInspectorModel()
    {
    }

    //--------------------------------------------------------------------
    Sequence< Any > SAL_CALL ObjectInspectorModel::getHandlerFactories() throw (RuntimeException)
    {
        return m_aFactories;
    }

    //--------------------------------------------------------------------
    Sequence< PropertyCategoryDescriptor > SAL_CALL ObjectInspectorModel::describeCategories(  ) throw (RuntimeException)
    {
        // no category info provided by this default implementation
        return Sequence< PropertyCategoryDescriptor >( );
    }

    //--------------------------------------------------------------------
    ::sal_Int32 SAL_CALL ObjectInspectorModel::getPropertyOrderIndex( const OUString& /*PropertyName*/ ) throw (RuntimeException)
    {
        // no ordering provided by this default implementation
        return 0;
    }

    //--------------------------------------------------------------------
    void SAL_CALL ObjectInspectorModel::initialize( const Sequence< Any >& _arguments ) throw (Exception, RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex );
        if ( m_aFactories.getLength() )
            throw AlreadyInitializedException();

        StlSyntaxSequence< Any > arguments( _arguments );
        if ( arguments.empty() )
        {   // constructor: "createDefault()"
            createDefault();
            return;
        }

        Sequence< Any > factories;
        impl_verifyArgument_throw( arguments[0] >>= factories, 1 );

        if ( arguments.size() == 1 )
        {   // constructor: "createWithHandlerFactories( any[] )"
            createWithHandlerFactories( factories );
            return;
        }

        sal_Int32 nMinHelpTextLines( 0 ), nMaxHelpTextLines( 0 );
        if ( arguments.size() == 3 )
        {   // constructor: "createWithHandlerFactoriesAndHelpSection( any[], long, long )"
            impl_verifyArgument_throw( arguments[1] >>= nMinHelpTextLines, 2 );
            impl_verifyArgument_throw( arguments[2] >>= nMaxHelpTextLines, 3 );
            createWithHandlerFactoriesAndHelpSection( factories, nMinHelpTextLines, nMaxHelpTextLines );
            return;
        }

        impl_verifyArgument_throw( false, 2 );
    }

    //--------------------------------------------------------------------
    OUString SAL_CALL ObjectInspectorModel::getImplementationName(  ) throw (RuntimeException)
    {
        return getImplementationName_static();
    }

    //--------------------------------------------------------------------
    Sequence< OUString > SAL_CALL ObjectInspectorModel::getSupportedServiceNames(  ) throw (RuntimeException)
    {
        return getSupportedServiceNames_static();
    }

    //--------------------------------------------------------------------
    OUString ObjectInspectorModel::getImplementationName_static(  ) throw(RuntimeException)
    {
        return OUString( "org.openoffice.comp.extensions.ObjectInspectorModel" );
    }

    //--------------------------------------------------------------------
    Sequence< OUString > ObjectInspectorModel::getSupportedServiceNames_static(  ) throw(RuntimeException)
    {
        OUString sService( "com.sun.star.inspection.ObjectInspectorModel" );
        return Sequence< OUString >( &sService, 1 );
    }

    //--------------------------------------------------------------------
    Reference< XInterface > SAL_CALL ObjectInspectorModel::Create(const Reference< XComponentContext >& /* _rxContext */ )
    {
        return *( new ObjectInspectorModel() );
    }

    //--------------------------------------------------------------------
    void ObjectInspectorModel::createDefault()
    {
        m_aFactories.realloc( 1 );
        m_aFactories[0] <<= OUString( "com.sun.star.inspection.GenericPropertyHandler" );
    }

    //--------------------------------------------------------------------
    void ObjectInspectorModel::createWithHandlerFactories( const Sequence< Any >& _rFactories )
    {
        impl_verifyArgument_throw( _rFactories.getLength() > 0, 1 );
        m_aFactories = _rFactories;
    }

    //--------------------------------------------------------------------
    void ObjectInspectorModel::createWithHandlerFactoriesAndHelpSection( const Sequence< Any >& _rFactories, sal_Int32 _nMinHelpTextLines, sal_Int32 _nMaxHelpTextLines )
    {
        impl_verifyArgument_throw( _rFactories.getLength() > 0, 1 );
        impl_verifyArgument_throw( _nMinHelpTextLines >= 1, 2 );
        impl_verifyArgument_throw( _nMaxHelpTextLines >= 1, 3 );
        impl_verifyArgument_throw( _nMinHelpTextLines <= _nMaxHelpTextLines, 2 );

        m_aFactories = _rFactories;
        enableHelpSectionProperties( _nMinHelpTextLines, _nMaxHelpTextLines );
    }

    //--------------------------------------------------------------------
    void ObjectInspectorModel::impl_verifyArgument_throw( bool _bCondition, sal_Int16 _nArgumentPosition )
    {
        if ( !_bCondition )
            throw IllegalArgumentException( OUString(), *this, _nArgumentPosition );
    }

//........................................................................
} // namespace pcr
//........................................................................

//------------------------------------------------------------------------
extern "C" void SAL_CALL createRegistryInfo_ObjectInspectorModel()
{
    ::pcr::OAutoRegistration< ::pcr::ObjectInspectorModel > aObjectInspectorModelRegistration;
}

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


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: updatecheckconfig.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: ihi $ $Date: 2008-01-14 15:05:43 $
 *
 *  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 _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif

#ifndef _COM_SUN_STAR_BEANS_NAMEDVALUE_HPP_
#include <com/sun/star/beans/NamedValue.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif

#ifndef _COM_SUN_STAR_UTIL_XCHANGESBATCH_HPP_
#include <com/sun/star/util/XChangesBatch.hpp>
#endif

#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif

#include "updatecheckconfiglistener.hxx"
#include "updateinfo.hxx"

/* Interface to acess configuration data read-only */
struct IByNameAccess
{
    virtual ::com::sun::star::uno::Any getValue(const sal_Char * pName) = 0;
};

/* This helper class provides by name access to a sequence of named values */
class NamedValueByNameAccess : public IByNameAccess
{
    const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& m_rValues;

public:
    NamedValueByNameAccess(
        const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& rValues) :
        m_rValues(rValues) {} ;

    virtual ~NamedValueByNameAccess();

    virtual ::com::sun::star::uno::Any getValue(const sal_Char * pName);
};

/* This class encapsulates the configuration item actually used for storing the state
 * the update check is actually in.
 */
class UpdateCheckROModel
{
public:
    UpdateCheckROModel(IByNameAccess& aNameAccess) : m_aNameAccess(aNameAccess) {};

    bool isAutoCheckEnabled() const;
    bool isAutoDownloadEnabled() const;
    bool isDownloadPaused() const;
    rtl::OUString getLocalFileName() const;
    sal_Int64 getDownloadSize() const;

    rtl::OUString getUpdateEntryVersion() const;
    void getUpdateEntry(UpdateInfo& rInfo) const;

private:

    rtl::OUString getStringValue(const sal_Char *) const;

    IByNameAccess& m_aNameAccess;
};

/* This class implements the non published UNO service com.sun.star.setup.UpdateCheckConfig,
 * which primary use is to be able to track changes done in the Toos -> Options page of this
 * component, as this is not supported by the OOo configuration for extendable groups.
 */

class UpdateCheckConfig : public ::cppu::WeakImplHelper3<
    ::com::sun::star::container::XNameReplace,
    ::com::sun::star::util::XChangesBatch,
    ::com::sun::star::lang::XServiceInfo >
{
    UpdateCheckConfig(const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer >& xContainer,
                      const ::rtl::Reference< UpdateCheckConfigListener >& rListener );

    virtual ~UpdateCheckConfig();

public:

    static ::com::sun::star::uno::Sequence< rtl::OUString > getServiceNames();
    static rtl::OUString getImplName();

    static ::rtl::Reference< UpdateCheckConfig > get(
        const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& xContext,
        const ::rtl::Reference< UpdateCheckConfigListener >& rListener = ::rtl::Reference< UpdateCheckConfigListener >());

    // Should really implement ROModel ..
    bool isAutoCheckEnabled() const;
    bool isAutoDownloadEnabled() const;
    rtl::OUString getUpdateEntryVersion() const;

    /* Updates the timestamp of last check, but does not commit the change
     * as either clearUpdateFound() or setUpdateFound() are expected to get
     * called next.
     */
    void updateLastChecked();

    /* Returns the date of the last successful check in seconds since 1970 */
    sal_Int64 getLastChecked() const;

    /* Returns configured check interval in seconds */
    sal_Int64 getCheckInterval() const;

    /* Reset values of previously remembered update
     */
    void clearUpdateFound();

    /* Stores the specified data of an available update
     */
    void storeUpdateFound(const UpdateInfo& rInfo, const rtl::OUString& aCurrentBuild);

    // Returns the local file name of a started download
    rtl::OUString getLocalFileName() const;

    // Returns the local file name of a started download
    rtl::OUString getDownloadDestination() const;

    // stores the local file name of a just started download
    void storeLocalFileName(const rtl::OUString& rFileName, sal_Int64 nFileSize);

    // Removes the local file name of a download
    void clearLocalFileName();

    // Stores the bool value for manually paused downloads
    void storeDownloadPaused(bool paused);

    // Returns the directory that acts as the user's desktop
    static rtl::OUString getDesktopDirectory();

    // Returns a directory accessible for all users
    static rtl::OUString getAllUsersDirectory();

    // store and retrieve information about extensions
    void storeExtensionVersion( const rtl::OUString& rExtensionName,
                                const rtl::OUString& rVersion );
    bool checkExtensionVersion( const rtl::OUString& rExtensionName,
                                const rtl::OUString& rVersion );

    // XElementAccess
    virtual ::com::sun::star::uno::Type SAL_CALL getElementType(  )
        throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL hasElements(  )
        throw (::com::sun::star::uno::RuntimeException);

    // XNameAccess
    virtual ::com::sun::star::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName )
        throw (::com::sun::star::container::NoSuchElementException,
               ::com::sun::star::lang::WrappedTargetException,
               ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames(  )
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName )
        throw (::com::sun::star::uno::RuntimeException);

    // XNameReplace
    virtual void SAL_CALL replaceByName( const ::rtl::OUString& aName, const ::com::sun::star::uno::Any& aElement )
        throw (::com::sun::star::lang::IllegalArgumentException,
               ::com::sun::star::container::NoSuchElementException,
               ::com::sun::star::lang::WrappedTargetException,
               ::com::sun::star::uno::RuntimeException);

    // XChangesBatch
    virtual void SAL_CALL commitChanges(  )
        throw (::com::sun::star::lang::WrappedTargetException,
               ::com::sun::star::uno::RuntimeException);
    virtual ::sal_Bool SAL_CALL hasPendingChanges(  )
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::util::ElementChange > SAL_CALL getPendingChanges(  )
        throw (::com::sun::star::uno::RuntimeException);

    // XServiceInfo
    virtual rtl::OUString SAL_CALL getImplementationName()
        throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService(rtl::OUString const & serviceName)
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames()
        throw (::com::sun::star::uno::RuntimeException);

private:

    static rtl::OUString getSubVersion( const rtl::OUString& rVersion, sal_Int32 *nIndex );
    static bool isVersionGreater( const rtl::OUString& rVersion1, const rtl::OUString& rVersion2 );

    const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer > m_xContainer;
    const ::rtl::Reference< UpdateCheckConfigListener > m_rListener;
};

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

template <typename T>
T getValue( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& rNamedValues, const sal_Char * pszName )
    throw (::com::sun::star::uno::RuntimeException)
{
    for( sal_Int32 n=0; n < rNamedValues.getLength(); n++ )
    {
        // Unfortunatly gcc-3.3 does not like Any.get<T>();
        if( rNamedValues[n].Name.equalsAscii( pszName ) )
        {
            T value = T();
            if( ! (rNamedValues[n].Value >>= value) )
                throw ::com::sun::star::uno::RuntimeException(
                    ::rtl::OUString(
                        cppu_Any_extraction_failure_msg(
                            &rNamedValues[n].Value,
                            ::cppu::getTypeFavourUnsigned(&value).getTypeLibType() ),
                            SAL_NO_ACQUIRE ),
                    ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >() );

            return value;
        }
    }

    return T();
}
<commit_msg>INTEGRATION: CWS changefileheader (1.7.48); FILE MERGED 2008/04/01 15:15:24 thb 1.7.48.3: #i85898# Stripping all external header guards 2008/04/01 12:29:58 thb 1.7.48.2: #i85898# Stripping all external header guards 2008/03/31 12:32:15 rt 1.7.48.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: updatecheckconfig.hxx,v $
 * $Revision: 1.8 $
 *
 * 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.
 *
 ************************************************************************/

#include <cppuhelper/implbase3.hxx>
#include <com/sun/star/beans/NamedValue.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/util/XChangesBatch.hpp>
#include <rtl/ref.hxx>

#include "updatecheckconfiglistener.hxx"
#include "updateinfo.hxx"

/* Interface to acess configuration data read-only */
struct IByNameAccess
{
    virtual ::com::sun::star::uno::Any getValue(const sal_Char * pName) = 0;
};

/* This helper class provides by name access to a sequence of named values */
class NamedValueByNameAccess : public IByNameAccess
{
    const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& m_rValues;

public:
    NamedValueByNameAccess(
        const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& rValues) :
        m_rValues(rValues) {} ;

    virtual ~NamedValueByNameAccess();

    virtual ::com::sun::star::uno::Any getValue(const sal_Char * pName);
};

/* This class encapsulates the configuration item actually used for storing the state
 * the update check is actually in.
 */
class UpdateCheckROModel
{
public:
    UpdateCheckROModel(IByNameAccess& aNameAccess) : m_aNameAccess(aNameAccess) {};

    bool isAutoCheckEnabled() const;
    bool isAutoDownloadEnabled() const;
    bool isDownloadPaused() const;
    rtl::OUString getLocalFileName() const;
    sal_Int64 getDownloadSize() const;

    rtl::OUString getUpdateEntryVersion() const;
    void getUpdateEntry(UpdateInfo& rInfo) const;

private:

    rtl::OUString getStringValue(const sal_Char *) const;

    IByNameAccess& m_aNameAccess;
};

/* This class implements the non published UNO service com.sun.star.setup.UpdateCheckConfig,
 * which primary use is to be able to track changes done in the Toos -> Options page of this
 * component, as this is not supported by the OOo configuration for extendable groups.
 */

class UpdateCheckConfig : public ::cppu::WeakImplHelper3<
    ::com::sun::star::container::XNameReplace,
    ::com::sun::star::util::XChangesBatch,
    ::com::sun::star::lang::XServiceInfo >
{
    UpdateCheckConfig(const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer >& xContainer,
                      const ::rtl::Reference< UpdateCheckConfigListener >& rListener );

    virtual ~UpdateCheckConfig();

public:

    static ::com::sun::star::uno::Sequence< rtl::OUString > getServiceNames();
    static rtl::OUString getImplName();

    static ::rtl::Reference< UpdateCheckConfig > get(
        const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& xContext,
        const ::rtl::Reference< UpdateCheckConfigListener >& rListener = ::rtl::Reference< UpdateCheckConfigListener >());

    // Should really implement ROModel ..
    bool isAutoCheckEnabled() const;
    bool isAutoDownloadEnabled() const;
    rtl::OUString getUpdateEntryVersion() const;

    /* Updates the timestamp of last check, but does not commit the change
     * as either clearUpdateFound() or setUpdateFound() are expected to get
     * called next.
     */
    void updateLastChecked();

    /* Returns the date of the last successful check in seconds since 1970 */
    sal_Int64 getLastChecked() const;

    /* Returns configured check interval in seconds */
    sal_Int64 getCheckInterval() const;

    /* Reset values of previously remembered update
     */
    void clearUpdateFound();

    /* Stores the specified data of an available update
     */
    void storeUpdateFound(const UpdateInfo& rInfo, const rtl::OUString& aCurrentBuild);

    // Returns the local file name of a started download
    rtl::OUString getLocalFileName() const;

    // Returns the local file name of a started download
    rtl::OUString getDownloadDestination() const;

    // stores the local file name of a just started download
    void storeLocalFileName(const rtl::OUString& rFileName, sal_Int64 nFileSize);

    // Removes the local file name of a download
    void clearLocalFileName();

    // Stores the bool value for manually paused downloads
    void storeDownloadPaused(bool paused);

    // Returns the directory that acts as the user's desktop
    static rtl::OUString getDesktopDirectory();

    // Returns a directory accessible for all users
    static rtl::OUString getAllUsersDirectory();

    // store and retrieve information about extensions
    void storeExtensionVersion( const rtl::OUString& rExtensionName,
                                const rtl::OUString& rVersion );
    bool checkExtensionVersion( const rtl::OUString& rExtensionName,
                                const rtl::OUString& rVersion );

    // XElementAccess
    virtual ::com::sun::star::uno::Type SAL_CALL getElementType(  )
        throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL hasElements(  )
        throw (::com::sun::star::uno::RuntimeException);

    // XNameAccess
    virtual ::com::sun::star::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName )
        throw (::com::sun::star::container::NoSuchElementException,
               ::com::sun::star::lang::WrappedTargetException,
               ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames(  )
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName )
        throw (::com::sun::star::uno::RuntimeException);

    // XNameReplace
    virtual void SAL_CALL replaceByName( const ::rtl::OUString& aName, const ::com::sun::star::uno::Any& aElement )
        throw (::com::sun::star::lang::IllegalArgumentException,
               ::com::sun::star::container::NoSuchElementException,
               ::com::sun::star::lang::WrappedTargetException,
               ::com::sun::star::uno::RuntimeException);

    // XChangesBatch
    virtual void SAL_CALL commitChanges(  )
        throw (::com::sun::star::lang::WrappedTargetException,
               ::com::sun::star::uno::RuntimeException);
    virtual ::sal_Bool SAL_CALL hasPendingChanges(  )
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::util::ElementChange > SAL_CALL getPendingChanges(  )
        throw (::com::sun::star::uno::RuntimeException);

    // XServiceInfo
    virtual rtl::OUString SAL_CALL getImplementationName()
        throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService(rtl::OUString const & serviceName)
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames()
        throw (::com::sun::star::uno::RuntimeException);

private:

    static rtl::OUString getSubVersion( const rtl::OUString& rVersion, sal_Int32 *nIndex );
    static bool isVersionGreater( const rtl::OUString& rVersion1, const rtl::OUString& rVersion2 );

    const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer > m_xContainer;
    const ::rtl::Reference< UpdateCheckConfigListener > m_rListener;
};

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

template <typename T>
T getValue( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& rNamedValues, const sal_Char * pszName )
    throw (::com::sun::star::uno::RuntimeException)
{
    for( sal_Int32 n=0; n < rNamedValues.getLength(); n++ )
    {
        // Unfortunatly gcc-3.3 does not like Any.get<T>();
        if( rNamedValues[n].Name.equalsAscii( pszName ) )
        {
            T value = T();
            if( ! (rNamedValues[n].Value >>= value) )
                throw ::com::sun::star::uno::RuntimeException(
                    ::rtl::OUString(
                        cppu_Any_extraction_failure_msg(
                            &rNamedValues[n].Value,
                            ::cppu::getTypeFavourUnsigned(&value).getTypeLibType() ),
                            SAL_NO_ACQUIRE ),
                    ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >() );

            return value;
        }
    }

    return T();
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <iostream>
#include <chrono>
#include <random>

#define ETL_COUNTERS
#define ETL_COUNTERS_VERBOSE

#include "etl/etl.hpp"

typedef std::chrono::high_resolution_clock timer_clock;
typedef std::chrono::milliseconds milliseconds;

float fake = 0;

/*
 *
 * Current values are (alloc/gpu_to_cpu/cpu_to_gpu):
 * Simple: 3 / 2 / 0 (Optimal!)
 * Basic: 50 / 30 / 10
 * Sub: 960 / 640 / 160
 */

void simple(){
    etl::dyn_matrix<float, 2> A(4096, 4096);
    etl::dyn_matrix<float, 2> B(4096, 4096);
    etl::dyn_matrix<float, 2> C(4096, 4096);

    A = etl::normal_generator<float>(1.0, 0.0);
    B = etl::normal_generator<float>(1.0, 0.0);
    C = etl::normal_generator<float>(1.0, 0.0);

    etl::reset_counters();

    std::cout << "Simple" << std::endl;

    for (size_t i = 0; i < 10; ++i) {
        C = A * B;
        fake += etl::mean(C);
    }

    etl::dump_counters();
}

void basic(){
    etl::dyn_matrix<float, 2> A(4096, 4096);
    etl::dyn_matrix<float, 2> B(4096, 4096);
    etl::dyn_matrix<float, 2> C(4096, 4096);
    etl::dyn_matrix<float, 2> D(4096, 4096);

    A = etl::normal_generator<float>(1.0, 0.0);
    B = etl::normal_generator<float>(1.0, 0.0);
    C = etl::normal_generator<float>(1.0, 0.0);
    D = etl::normal_generator<float>(1.0, 0.0);

    etl::reset_counters();

    std::cout << "Basic" << std::endl;

    for (size_t i = 0; i < 10; ++i) {
        C = A * B * B;
        D = A * trans(A);
        D *= 1.1;
        D += C;
        fake += etl::mean(D);
    }
    etl::dump_counters();
}

void sub(){
    etl::dyn_matrix<float, 3> A(16, 2048, 2048);
    etl::dyn_matrix<float, 3> B(16, 2048, 2048);
    etl::dyn_matrix<float, 3> C(16, 2048, 2048);
    etl::dyn_matrix<float, 3> D(16, 2048, 2048);

    A = etl::normal_generator<float>(1.0, 0.0);
    B = etl::normal_generator<float>(1.0, 0.0);
    C = etl::normal_generator<float>(1.0, 0.0);
    D = etl::normal_generator<float>(1.0, 0.0);

    etl::reset_counters();

    std::cout << "Sub" << std::endl;

    for (size_t i = 0; i < 10; ++i) {
        for (size_t k = 0; k < 16; ++k) {
            C(k) = A(k) * B(k) * B(k);
            D(k) += C(k);
            D(k) *= 1.1;
            fake += etl::mean(D(k));
        }
    }

    etl::dump_counters();
}

int main(){
    auto start_time = timer_clock::now();

    simple();
    basic();
    sub();

    auto end_time = timer_clock::now();
    auto duration = std::chrono::duration_cast<milliseconds>(end_time - start_time);

    std::cout << "duration: " << duration.count() << "ms" << std::endl;

    return (int) fake;
}
<commit_msg>Fix the status<commit_after>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <iostream>
#include <chrono>
#include <random>

#define ETL_COUNTERS
#define ETL_COUNTERS_VERBOSE

#include "etl/etl.hpp"

typedef std::chrono::high_resolution_clock timer_clock;
typedef std::chrono::milliseconds milliseconds;

float fake = 0;

/*
 *
 * Current values are (alloc/gpu_to_cpu/cpu_to_gpu):
 * Simple: 3 / 0 / 2 (Optimal!)
 * Basic: 50 / 30 / 10
 * Sub: 960 / 640 / 160
 */

void simple(){
    etl::dyn_matrix<float, 2> A(4096, 4096);
    etl::dyn_matrix<float, 2> B(4096, 4096);
    etl::dyn_matrix<float, 2> C(4096, 4096);

    A = etl::normal_generator<float>(1.0, 0.0);
    B = etl::normal_generator<float>(1.0, 0.0);
    C = etl::normal_generator<float>(1.0, 0.0);

    etl::reset_counters();

    std::cout << "Simple" << std::endl;

    for (size_t i = 0; i < 10; ++i) {
        C = A * B;
        fake += etl::mean(C);
    }

    etl::dump_counters();
}

void basic(){
    etl::dyn_matrix<float, 2> A(4096, 4096);
    etl::dyn_matrix<float, 2> B(4096, 4096);
    etl::dyn_matrix<float, 2> C(4096, 4096);
    etl::dyn_matrix<float, 2> D(4096, 4096);

    A = etl::normal_generator<float>(1.0, 0.0);
    B = etl::normal_generator<float>(1.0, 0.0);
    C = etl::normal_generator<float>(1.0, 0.0);
    D = etl::normal_generator<float>(1.0, 0.0);

    etl::reset_counters();

    std::cout << "Basic" << std::endl;

    for (size_t i = 0; i < 10; ++i) {
        C = A * B * B;
        D = A * trans(A);
        D *= 1.1;
        D += C;
        fake += etl::mean(D);
    }
    etl::dump_counters();
}

void sub(){
    etl::dyn_matrix<float, 3> A(16, 2048, 2048);
    etl::dyn_matrix<float, 3> B(16, 2048, 2048);
    etl::dyn_matrix<float, 3> C(16, 2048, 2048);
    etl::dyn_matrix<float, 3> D(16, 2048, 2048);

    A = etl::normal_generator<float>(1.0, 0.0);
    B = etl::normal_generator<float>(1.0, 0.0);
    C = etl::normal_generator<float>(1.0, 0.0);
    D = etl::normal_generator<float>(1.0, 0.0);

    etl::reset_counters();

    std::cout << "Sub" << std::endl;

    for (size_t i = 0; i < 10; ++i) {
        for (size_t k = 0; k < 16; ++k) {
            C(k) = A(k) * B(k) * B(k);
            D(k) += C(k);
            D(k) *= 1.1;
            fake += etl::mean(D(k));
        }
    }

    etl::dump_counters();
}

int main(){
    auto start_time = timer_clock::now();

    simple();
    basic();
    sub();

    auto end_time = timer_clock::now();
    auto duration = std::chrono::duration_cast<milliseconds>(end_time - start_time);

    std::cout << "duration: " << duration.count() << "ms" << std::endl;

    return (int) fake;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2018, Arm Limited and affiliates.
 * SPDX-License-Identifier: Apache-2.0
 *
 * 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.
 */

#if !defined(MBED_CONF_NSAPI_PRESENT)
#error [NOT_SUPPORTED] A json configuration file is needed. Skipping this build.
#endif

#ifndef MBED_CONF_APP_CELLULAR_SIM_PIN
#error [NOT_SUPPORTED] SIM pin code is needed. Skipping this build.
#endif

#include "greentea-client/test_env.h"
#include "unity.h"
#include "utest.h"

#include "mbed.h"

#include "CellularLog.h"
#include "CellularDevice.h"
#include "Semaphore.h"
#include "../../cellular_tests_common.h"

static CellularDevice *device;
static rtos::Semaphore semaphore;

const int TIME_OUT_DEVICE_READY = 5 * 60 * 1000; // 5 minutes
const int TIME_OUT_REGISTER = 10 * 60 * 1000; // 10 minutes

enum CurrentOp {
    OP_DEVICE_READY,
    OP_SIM_READY,
    OP_REGISTER,
    OP_ATTACH
};
static CurrentOp op;

static void create_device()
{
    device = CellularDevice::get_default_instance();
    TEST_ASSERT(device != NULL);
}

static void open_close_interfaces()
{
    CellularNetwork *nw = device->open_network();
    TEST_ASSERT(nw != NULL);
    device->close_network();

    CellularInformation *info = device->open_information();
    TEST_ASSERT(info != NULL);
    device->close_information();

    CellularSMS *sms = device->open_sms();
    TEST_ASSERT(sms != NULL);
    device->close_sms();

    CellularContext *ctx = device->create_context();
    TEST_ASSERT(ctx != NULL);
    TEST_ASSERT(device->get_context_list() == ctx);
    device->delete_context(ctx);
}

static void other_methods()
{
    // test first without any open interfaces
    device->set_timeout(5000);
    device->modem_debug_on(true);
    device->modem_debug_on(false);

    CellularNetwork *nw = device->open_network();
    TEST_ASSERT(nw != NULL);

    // then test with open interface which is called
    device->set_timeout(5000);
    device->modem_debug_on(true);
    device->modem_debug_on(false);

    TEST_ASSERT(device->get_queue() != NULL);
    TEST_ASSERT(device->hard_power_on() == NSAPI_ERROR_OK);
    TEST_ASSERT(device->soft_power_on() == NSAPI_ERROR_OK);
#ifdef TARGET_UBLOX_C030_U201
    wait(10);
#else
    wait(5);
#endif
    TEST_ASSERT_EQUAL_INT(device->init(), NSAPI_ERROR_OK);
}

static void shutdown()
{
    TEST_ASSERT(device->shutdown() == NSAPI_ERROR_OK);
    TEST_ASSERT(device->soft_power_off() == NSAPI_ERROR_OK);
    TEST_ASSERT(device->hard_power_off() == NSAPI_ERROR_OK);
}

static void callback_func(nsapi_event_t ev, intptr_t ptr)
{
    if (ev >= NSAPI_EVENT_CELLULAR_STATUS_BASE && ev <= NSAPI_EVENT_CELLULAR_STATUS_END) {
        cell_callback_data_t *ptr_data = (cell_callback_data_t *)ptr;
        cellular_connection_status_t cell_ev = (cellular_connection_status_t)ev;
        if (cell_ev == CellularDeviceReady && ptr_data->error == NSAPI_ERROR_OK && op == OP_DEVICE_READY) {
            TEST_ASSERT_EQUAL_INT(semaphore.release(), osOK);
        } else if (cell_ev == CellularSIMStatusChanged && ptr_data->error == NSAPI_ERROR_OK &&
                   ptr_data->status_data == CellularDevice::SimStateReady && op == OP_SIM_READY) {
            TEST_ASSERT_EQUAL_INT(semaphore.release(), osOK);
        } else if (cell_ev == CellularRegistrationStatusChanged &&
                   (ptr_data->status_data == CellularNetwork::RegisteredHomeNetwork ||
                    ptr_data->status_data == CellularNetwork::RegisteredRoaming ||
                    ptr_data->status_data == CellularNetwork::AlreadyRegistered) &&
                   ptr_data->error == NSAPI_ERROR_OK &&
                   op == OP_REGISTER) {
            TEST_ASSERT_EQUAL_INT(semaphore.release(), osOK);
        } else if (cell_ev == CellularAttachNetwork  && ptr_data->status_data == CellularNetwork::Attached &&
                   ptr_data->error == NSAPI_ERROR_OK && op == OP_ATTACH) {
            TEST_ASSERT_EQUAL_INT(semaphore.release(), osOK);
        }
    }
}

static void init_to_device_ready_state()
{
    device = CellularDevice::get_default_instance();
    TEST_ASSERT(device != NULL);

#ifdef MBED_CONF_APP_CELLULAR_SIM_PIN
    device->set_sim_pin(MBED_CONF_APP_CELLULAR_SIM_PIN);
#endif
#ifdef MBED_CONF_APP_CELLULAR_PLMN
    device->set_plmn(MBED_CONF_APP_CELLULAR_PLMN);
#endif
    device->attach(&callback_func);

    op = OP_DEVICE_READY;
    TEST_ASSERT_EQUAL_INT(NSAPI_ERROR_OK, device->hard_power_on());
    TEST_ASSERT_EQUAL_INT(NSAPI_ERROR_OK, device->soft_power_on());
    TEST_ASSERT_EQUAL_INT(NSAPI_ERROR_OK, device->init());
    TEST_ASSERT_EQUAL_INT(NSAPI_ERROR_OK, device->set_device_ready());

    int sema_err = semaphore.wait(TIME_OUT_DEVICE_READY);
    TEST_ASSERT_EQUAL_INT(1, sema_err);
}

static void continue_to_sim_ready_state()
{
    op = OP_SIM_READY;
    TEST_ASSERT_EQUAL_INT(NSAPI_ERROR_OK, device->set_sim_ready());

    int sema_err = semaphore.wait(TIME_OUT_DEVICE_READY);
    TEST_ASSERT_EQUAL_INT(1, sema_err);
}

static void continue_to_register_state()
{
    op = OP_REGISTER;
    TEST_ASSERT_EQUAL_INT(NSAPI_ERROR_OK, device->register_to_network());

    int sema_err = semaphore.wait(TIME_OUT_REGISTER); // cellular network searching may take several minutes
    TEST_ASSERT_EQUAL_INT(1, sema_err);
}

static void continue_to_attach_state()
{
    op = OP_ATTACH;
    TEST_ASSERT_EQUAL_INT(NSAPI_ERROR_OK, device->attach_to_network());

    int sema_err = semaphore.wait(TIME_OUT_REGISTER); // cellular network attach may take several minutes
    TEST_ASSERT_EQUAL_INT(1, sema_err);
}

using namespace utest::v1;

static utest::v1::status_t greentea_failure_handler(const Case *const source, const failure_t reason)
{
#if MBED_CONF_MBED_TRACE_ENABLE
    trace_close();
#endif
    greentea_case_failure_abort_handler(source, reason);
    return STATUS_ABORT;
}

static Case cases[] = {
    Case("CellularDevice create device", create_device, greentea_failure_handler),
    Case("CellularDevice Open and close interfaces", open_close_interfaces, greentea_failure_handler),
    Case("CellularDevice other methods", other_methods, greentea_failure_handler),
    Case("CellularDevice init to device ready", init_to_device_ready_state, greentea_failure_handler),
    Case("CellularDevice sim ready", continue_to_sim_ready_state, greentea_failure_handler),
    Case("CellularDevice register", continue_to_register_state, greentea_failure_handler),
    Case("CellularDevice attach", continue_to_attach_state, greentea_failure_handler),
    Case("CellularDevice shutdown", shutdown, greentea_failure_handler),
};

static utest::v1::status_t test_setup(const size_t number_of_cases)
{
    GREENTEA_SETUP(10 * 60, "default_auto");
    return verbose_test_setup_handler(number_of_cases);
}

static Specification specification(test_setup, cases);

int main()
{
#if MBED_CONF_MBED_TRACE_ENABLE
    trace_open();
#endif

    int ret = Harness::run(specification);
#if MBED_CONF_MBED_TRACE_ENABLE
    trace_close();
#endif
    return ret;
}

<commit_msg>wait increased for all cases<commit_after>/*
 * Copyright (c) 2018, Arm Limited and affiliates.
 * SPDX-License-Identifier: Apache-2.0
 *
 * 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.
 */

#if !defined(MBED_CONF_NSAPI_PRESENT)
#error [NOT_SUPPORTED] A json configuration file is needed. Skipping this build.
#endif

#ifndef MBED_CONF_APP_CELLULAR_SIM_PIN
#error [NOT_SUPPORTED] SIM pin code is needed. Skipping this build.
#endif

#include "greentea-client/test_env.h"
#include "unity.h"
#include "utest.h"

#include "mbed.h"

#include "CellularLog.h"
#include "CellularDevice.h"
#include "Semaphore.h"
#include "../../cellular_tests_common.h"

static CellularDevice *device;
static rtos::Semaphore semaphore;

const int TIME_OUT_DEVICE_READY = 5 * 60 * 1000; // 5 minutes
const int TIME_OUT_REGISTER = 10 * 60 * 1000; // 10 minutes

enum CurrentOp {
    OP_DEVICE_READY,
    OP_SIM_READY,
    OP_REGISTER,
    OP_ATTACH
};
static CurrentOp op;

static void create_device()
{
    device = CellularDevice::get_default_instance();
    TEST_ASSERT(device != NULL);
}

static void open_close_interfaces()
{
    CellularNetwork *nw = device->open_network();
    TEST_ASSERT(nw != NULL);
    device->close_network();

    CellularInformation *info = device->open_information();
    TEST_ASSERT(info != NULL);
    device->close_information();

    CellularSMS *sms = device->open_sms();
    TEST_ASSERT(sms != NULL);
    device->close_sms();

    CellularContext *ctx = device->create_context();
    TEST_ASSERT(ctx != NULL);
    TEST_ASSERT(device->get_context_list() == ctx);
    device->delete_context(ctx);
}

static void other_methods()
{
    // test first without any open interfaces
    device->set_timeout(5000);
    device->modem_debug_on(true);
    device->modem_debug_on(false);

    CellularNetwork *nw = device->open_network();
    TEST_ASSERT(nw != NULL);

    // then test with open interface which is called
    device->set_timeout(5000);
    device->modem_debug_on(true);
    device->modem_debug_on(false);

    TEST_ASSERT(device->get_queue() != NULL);
    TEST_ASSERT(device->hard_power_on() == NSAPI_ERROR_OK);
    TEST_ASSERT(device->soft_power_on() == NSAPI_ERROR_OK);
    wait(10);
    TEST_ASSERT_EQUAL_INT(device->init(), NSAPI_ERROR_OK);
}

static void shutdown()
{
    TEST_ASSERT(device->shutdown() == NSAPI_ERROR_OK);
    TEST_ASSERT(device->soft_power_off() == NSAPI_ERROR_OK);
    TEST_ASSERT(device->hard_power_off() == NSAPI_ERROR_OK);
}

static void callback_func(nsapi_event_t ev, intptr_t ptr)
{
    if (ev >= NSAPI_EVENT_CELLULAR_STATUS_BASE && ev <= NSAPI_EVENT_CELLULAR_STATUS_END) {
        cell_callback_data_t *ptr_data = (cell_callback_data_t *)ptr;
        cellular_connection_status_t cell_ev = (cellular_connection_status_t)ev;
        if (cell_ev == CellularDeviceReady && ptr_data->error == NSAPI_ERROR_OK && op == OP_DEVICE_READY) {
            TEST_ASSERT_EQUAL_INT(semaphore.release(), osOK);
        } else if (cell_ev == CellularSIMStatusChanged && ptr_data->error == NSAPI_ERROR_OK &&
                   ptr_data->status_data == CellularDevice::SimStateReady && op == OP_SIM_READY) {
            TEST_ASSERT_EQUAL_INT(semaphore.release(), osOK);
        } else if (cell_ev == CellularRegistrationStatusChanged &&
                   (ptr_data->status_data == CellularNetwork::RegisteredHomeNetwork ||
                    ptr_data->status_data == CellularNetwork::RegisteredRoaming ||
                    ptr_data->status_data == CellularNetwork::AlreadyRegistered) &&
                   ptr_data->error == NSAPI_ERROR_OK &&
                   op == OP_REGISTER) {
            TEST_ASSERT_EQUAL_INT(semaphore.release(), osOK);
        } else if (cell_ev == CellularAttachNetwork  && ptr_data->status_data == CellularNetwork::Attached &&
                   ptr_data->error == NSAPI_ERROR_OK && op == OP_ATTACH) {
            TEST_ASSERT_EQUAL_INT(semaphore.release(), osOK);
        }
    }
}

static void init_to_device_ready_state()
{
    device = CellularDevice::get_default_instance();
    TEST_ASSERT(device != NULL);

#ifdef MBED_CONF_APP_CELLULAR_SIM_PIN
    device->set_sim_pin(MBED_CONF_APP_CELLULAR_SIM_PIN);
#endif
#ifdef MBED_CONF_APP_CELLULAR_PLMN
    device->set_plmn(MBED_CONF_APP_CELLULAR_PLMN);
#endif
    device->attach(&callback_func);

    op = OP_DEVICE_READY;
    TEST_ASSERT_EQUAL_INT(NSAPI_ERROR_OK, device->hard_power_on());
    TEST_ASSERT_EQUAL_INT(NSAPI_ERROR_OK, device->soft_power_on());
    TEST_ASSERT_EQUAL_INT(NSAPI_ERROR_OK, device->init());
    TEST_ASSERT_EQUAL_INT(NSAPI_ERROR_OK, device->set_device_ready());

    int sema_err = semaphore.wait(TIME_OUT_DEVICE_READY);
    TEST_ASSERT_EQUAL_INT(1, sema_err);
}

static void continue_to_sim_ready_state()
{
    op = OP_SIM_READY;
    TEST_ASSERT_EQUAL_INT(NSAPI_ERROR_OK, device->set_sim_ready());

    int sema_err = semaphore.wait(TIME_OUT_DEVICE_READY);
    TEST_ASSERT_EQUAL_INT(1, sema_err);
}

static void continue_to_register_state()
{
    op = OP_REGISTER;
    TEST_ASSERT_EQUAL_INT(NSAPI_ERROR_OK, device->register_to_network());

    int sema_err = semaphore.wait(TIME_OUT_REGISTER); // cellular network searching may take several minutes
    TEST_ASSERT_EQUAL_INT(1, sema_err);
}

static void continue_to_attach_state()
{
    op = OP_ATTACH;
    TEST_ASSERT_EQUAL_INT(NSAPI_ERROR_OK, device->attach_to_network());

    int sema_err = semaphore.wait(TIME_OUT_REGISTER); // cellular network attach may take several minutes
    TEST_ASSERT_EQUAL_INT(1, sema_err);
}

using namespace utest::v1;

static utest::v1::status_t greentea_failure_handler(const Case *const source, const failure_t reason)
{
#if MBED_CONF_MBED_TRACE_ENABLE
    trace_close();
#endif
    greentea_case_failure_abort_handler(source, reason);
    return STATUS_ABORT;
}

static Case cases[] = {
    Case("CellularDevice create device", create_device, greentea_failure_handler),
    Case("CellularDevice Open and close interfaces", open_close_interfaces, greentea_failure_handler),
    Case("CellularDevice other methods", other_methods, greentea_failure_handler),
    Case("CellularDevice init to device ready", init_to_device_ready_state, greentea_failure_handler),
    Case("CellularDevice sim ready", continue_to_sim_ready_state, greentea_failure_handler),
    Case("CellularDevice register", continue_to_register_state, greentea_failure_handler),
    Case("CellularDevice attach", continue_to_attach_state, greentea_failure_handler),
    Case("CellularDevice shutdown", shutdown, greentea_failure_handler),
};

static utest::v1::status_t test_setup(const size_t number_of_cases)
{
    GREENTEA_SETUP(10 * 60, "default_auto");
    return verbose_test_setup_handler(number_of_cases);
}

static Specification specification(test_setup, cases);

int main()
{
#if MBED_CONF_MBED_TRACE_ENABLE
    trace_open();
#endif

    int ret = Harness::run(specification);
#if MBED_CONF_MBED_TRACE_ENABLE
    trace_close();
#endif
    return ret;
}

<|endoftext|>


<commit_before>#include "file.h"
#include <allegro5/allegro_primitives.h>
#include <allegro5/allegro_native_dialog.h>
#include <iostream>
#include <sinxml/sinxml.h>
#include <map>

File::File(ALLEGRO_FONT* ifont)
:platforms(NULL),
bitmaps(NULL),
sprites(NULL),
font(ifont),
open(false)
{
	w = al_get_text_width(font, "File") + 4;
	h = al_get_font_line_height(font) + 4;
	inputbox.Set_font(font);
	inputbox.Set_text("filename");
	savebutton.Set_font(font);
	savebutton.Set_text("Save");
	loadbutton.Set_font(font);
	loadbutton.Set_text("Load");
	datapath = al_create_path("data/");
}

File::~File()
{
}

void File::Draw()
{
	ALLEGRO_COLOR color = al_map_rgb_f(1, 1, 1);
	ALLEGRO_COLOR back_color = al_map_rgb_f(1, .9, .9);
	al_draw_rectangle(x, y, x+w, y+h, back_color, 0);
	al_draw_text(font, color, x+w/2, y+2, ALLEGRO_ALIGN_CENTRE, "File");
	if(open)
	{
		inputbox.Draw();
		savebutton.Draw();
		loadbutton.Draw();
	}
}

void File::Event(ALLEGRO_EVENT& event)
{
	if(event.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP)
	{
		if(event.mouse.button == 1)
		{
		}
	}
	inputbox.Event(event);
	savebutton.Event(event);
	loadbutton.Event(event);
	if(savebutton.Get_active())
	{
		savebutton.Set_active(false);

		if(!al_ustr_equal(inputbox.Get_text(), al_ustr_empty_string()))
		{
			std::cout<<"Save"<<std::endl;
			sinxml::Document doc("1.0");
			sinxml::Element* map = new sinxml::Element("map");
			doc.Set_root(map);

			//Platforms
			for(Platforms::iterator i = platforms->begin(); i != platforms->end(); ++i)
			{
				sinxml::Element* platform = new sinxml::Element("platform");
				map->Add_child(platform);
				Vertices& vertices = (*i)->Get_vertices();
				for(Vertices::iterator i = vertices.begin(); i != vertices.end(); ++i)
				{
					sinxml::Element* vertex = new sinxml::Element("vertex");
					platform->Add_child(vertex);
					vertex->Add_child(new sinxml::Element("x", sinxml::tostring(i->x)));
					vertex->Add_child(new sinxml::Element("y", sinxml::tostring(i->y)));
				}
			}

			//Bitmaps
			typedef std::map<Bitmap*, int> Bmpmap;
			Bmpmap bmpmap;
			int id = 0;
			for(Bitmaps::iterator i = bitmaps->begin(); i!= bitmaps->end(); ++i)
			{
				sinxml::Element* bitmap = new sinxml::Element("bitmap");
				map->Add_child(bitmap);
				sinxml::Element* filename = new sinxml::Element("filename", (*i)->Get_filename());
				bitmap->Add_child(filename);
				sinxml::Element* eid = new sinxml::Element("id", sinxml::tostring(id));
				bitmap->Add_child(eid);
				bmpmap[*i] = id;
				++id;
			}

			for(Sprites::iterator i = sprites->begin(); i != sprites->end(); ++i)
			{
				sinxml::Element* sprite = new sinxml::Element("sprite");
				map->Add_child(sprite);
				sinxml::Element* id = new sinxml::Element("id", sinxml::tostring(bmpmap[(*i)->Get_bitmap()]));
				sprite->Add_child(id);
				Vector2 p = (*i)->Get_position();
				sinxml::Element* x = new sinxml::Element("x", sinxml::tostring(p.x));
				sprite->Add_child(x);
				sinxml::Element* y = new sinxml::Element("y", sinxml::tostring(p.y));
				sprite->Add_child(y);
			}

			doc.Save_file(al_cstr(inputbox.Get_text()));
		}
	}
	if(loadbutton.Get_active())
	{
		loadbutton.Set_active(false);

/*		if(!al_ustr_equal(inputbox.Get_text(), al_ustr_empty_string()))
		{
			std::cout<<"Load"<<std::endl;
			Load(al_cstr(inputbox.Get_text()));
		}
*/
		ALLEGRO_FILECHOOSER *filechooser = al_create_native_file_dialog(datapath, "Load", "*.*", ALLEGRO_FILECHOOSER_FILE_MUST_EXIST);
		al_show_native_file_dialog(NULL, filechooser);
		int nf = al_get_native_file_dialog_count(filechooser);
		for(int i = 0; i<nf; ++i)
		{
			const ALLEGRO_PATH *path = al_get_native_file_dialog_path(filechooser, i);

			ALLEGRO_PATH *relpath = Get_relative_path(path);
			if(!relpath)
				continue;

			const char *p = al_path_cstr(relpath, '/');
			Load(p);
			al_destroy_native_file_dialog(filechooser);
		}
	}
}

void File::Load(const char* filename)
{
	inputbox.Set_text(filename);
	for(Platforms::iterator i = platforms->begin(); i!=platforms->end(); ++i)
	{
		delete *i;
	}
	platforms->clear();
	bitmaps->clear();
	sprites->clear();

	typedef std::map<int, Bitmap*> Idbmpmap;
	Idbmpmap idbmpmap;

	sinxml::Document doc("1.0");
	if(!doc.Load_file(filename))
		return;
	sinxml::Children& mapchildren = doc.Get_root()->Get_children();
	for(sinxml::Children::iterator i = mapchildren.begin(); i != mapchildren.end(); ++i)
	{
		if((*i)->Get_name() == "platform")
		{
			Platform* platform = new Platform;
			sinxml::Children& platformchildren = (*i)->Get_children();
			for(sinxml::Children::iterator j = platformchildren.begin(); j != platformchildren.end(); ++j)
			{
				float x = sinxml::fromstring<float>((*j)->Get_child("x")->Get_value());
				float y = sinxml::fromstring<float>((*j)->Get_child("y")->Get_value());
				platform->Add_collision_vertex(Vector2(x, y));
			}
			platforms->push_back(platform);
		}
		if((*i)->Get_name() == "bitmap")
		{
			std::string filename = (*i)->Get_child("filename")->Get_value();
			int id = sinxml::fromstring<int>((*i)->Get_child("id")->Get_value());

			Bitmap* bitmap = new Bitmap(filename);
			bitmaps->push_back(bitmap);
			idbmpmap[id] = bitmap;
		}
	}
	for(sinxml::Children::iterator i = mapchildren.begin(); i != mapchildren.end(); ++i)
	{
		if((*i)->Get_name() == "sprite")
		{
			int id = sinxml::fromstring<int>((*i)->Get_child("id")->Get_value());
			float x = sinxml::fromstring<float>((*i)->Get_child("x")->Get_value());
			float y = sinxml::fromstring<float>((*i)->Get_child("y")->Get_value());
			Sprite* sprite = new Sprite(idbmpmap[id]);
			sprite->Set_position(Vector2(x, y));
			sprites->push_back(sprite);
		}
	}
}

void File::Open()
{
/*	ALLEGRO_DISPLAY *display;
	al_set_new_display_flags(ALLEGRO_WINDOWED);
	display = al_create_display(800, 600);

	ALLEGRO_FILECHOOSER* filechooser = al_create_native_file_dialog(NULL, "Save", "*.*", 0);
	al_show_native_file_dialog(display, filechooser);
	al_destroy_native_file_dialog(filechooser);
*/
	inputbox.Set_position(x, y+h);
	inputbox.Set_size(100, h);
	savebutton.Set_position(x, y+h*2);
	savebutton.Set_size(50, h);
	loadbutton.Set_position(x+50, y+h*2);
	loadbutton.Set_size(50, h);
	h = h*3;
	w = 100;
	resized = true;
	open = true;
}

void File::Close()
{
	h/=3;
	resized = true;
	open = false;
}
<commit_msg>Woops, destroying filechooser at the wrong place and missed destroying path<commit_after>#include "file.h"
#include <allegro5/allegro_primitives.h>
#include <allegro5/allegro_native_dialog.h>
#include <iostream>
#include <sinxml/sinxml.h>
#include <map>

File::File(ALLEGRO_FONT* ifont)
:platforms(NULL),
bitmaps(NULL),
sprites(NULL),
font(ifont),
open(false)
{
	w = al_get_text_width(font, "File") + 4;
	h = al_get_font_line_height(font) + 4;
	inputbox.Set_font(font);
	inputbox.Set_text("filename");
	savebutton.Set_font(font);
	savebutton.Set_text("Save");
	loadbutton.Set_font(font);
	loadbutton.Set_text("Load");
	datapath = al_create_path("data/");
}

File::~File()
{
}

void File::Draw()
{
	ALLEGRO_COLOR color = al_map_rgb_f(1, 1, 1);
	ALLEGRO_COLOR back_color = al_map_rgb_f(1, .9, .9);
	al_draw_rectangle(x, y, x+w, y+h, back_color, 0);
	al_draw_text(font, color, x+w/2, y+2, ALLEGRO_ALIGN_CENTRE, "File");
	if(open)
	{
		inputbox.Draw();
		savebutton.Draw();
		loadbutton.Draw();
	}
}

void File::Event(ALLEGRO_EVENT& event)
{
	if(event.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP)
	{
		if(event.mouse.button == 1)
		{
		}
	}
	inputbox.Event(event);
	savebutton.Event(event);
	loadbutton.Event(event);
	if(savebutton.Get_active())
	{
		savebutton.Set_active(false);

		if(!al_ustr_equal(inputbox.Get_text(), al_ustr_empty_string()))
		{
			std::cout<<"Save"<<std::endl;
			sinxml::Document doc("1.0");
			sinxml::Element* map = new sinxml::Element("map");
			doc.Set_root(map);

			//Platforms
			for(Platforms::iterator i = platforms->begin(); i != platforms->end(); ++i)
			{
				sinxml::Element* platform = new sinxml::Element("platform");
				map->Add_child(platform);
				Vertices& vertices = (*i)->Get_vertices();
				for(Vertices::iterator i = vertices.begin(); i != vertices.end(); ++i)
				{
					sinxml::Element* vertex = new sinxml::Element("vertex");
					platform->Add_child(vertex);
					vertex->Add_child(new sinxml::Element("x", sinxml::tostring(i->x)));
					vertex->Add_child(new sinxml::Element("y", sinxml::tostring(i->y)));
				}
			}

			//Bitmaps
			typedef std::map<Bitmap*, int> Bmpmap;
			Bmpmap bmpmap;
			int id = 0;
			for(Bitmaps::iterator i = bitmaps->begin(); i!= bitmaps->end(); ++i)
			{
				sinxml::Element* bitmap = new sinxml::Element("bitmap");
				map->Add_child(bitmap);
				sinxml::Element* filename = new sinxml::Element("filename", (*i)->Get_filename());
				bitmap->Add_child(filename);
				sinxml::Element* eid = new sinxml::Element("id", sinxml::tostring(id));
				bitmap->Add_child(eid);
				bmpmap[*i] = id;
				++id;
			}

			for(Sprites::iterator i = sprites->begin(); i != sprites->end(); ++i)
			{
				sinxml::Element* sprite = new sinxml::Element("sprite");
				map->Add_child(sprite);
				sinxml::Element* id = new sinxml::Element("id", sinxml::tostring(bmpmap[(*i)->Get_bitmap()]));
				sprite->Add_child(id);
				Vector2 p = (*i)->Get_position();
				sinxml::Element* x = new sinxml::Element("x", sinxml::tostring(p.x));
				sprite->Add_child(x);
				sinxml::Element* y = new sinxml::Element("y", sinxml::tostring(p.y));
				sprite->Add_child(y);
			}

			doc.Save_file(al_cstr(inputbox.Get_text()));
		}
	}
	if(loadbutton.Get_active())
	{
		loadbutton.Set_active(false);

/*		if(!al_ustr_equal(inputbox.Get_text(), al_ustr_empty_string()))
		{
			std::cout<<"Load"<<std::endl;
			Load(al_cstr(inputbox.Get_text()));
		}
*/
		ALLEGRO_FILECHOOSER *filechooser = al_create_native_file_dialog(datapath, "Load", "*.*", ALLEGRO_FILECHOOSER_FILE_MUST_EXIST);
		al_show_native_file_dialog(NULL, filechooser);
		int nf = al_get_native_file_dialog_count(filechooser);
		for(int i = 0; i<nf; ++i)
		{
			const ALLEGRO_PATH *path = al_get_native_file_dialog_path(filechooser, i);

			ALLEGRO_PATH *relpath = Get_relative_path(path);
			if(!relpath)
				continue;

			const char *p = al_path_cstr(relpath, '/');
			Load(p);
			al_destroy_path(relpath);
		}
		al_destroy_native_file_dialog(filechooser);
	}
}

void File::Load(const char* filename)
{
	inputbox.Set_text(filename);
	for(Platforms::iterator i = platforms->begin(); i!=platforms->end(); ++i)
	{
		delete *i;
	}
	platforms->clear();
	bitmaps->clear();
	sprites->clear();

	typedef std::map<int, Bitmap*> Idbmpmap;
	Idbmpmap idbmpmap;

	sinxml::Document doc("1.0");
	if(!doc.Load_file(filename))
		return;
	sinxml::Children& mapchildren = doc.Get_root()->Get_children();
	for(sinxml::Children::iterator i = mapchildren.begin(); i != mapchildren.end(); ++i)
	{
		if((*i)->Get_name() == "platform")
		{
			Platform* platform = new Platform;
			sinxml::Children& platformchildren = (*i)->Get_children();
			for(sinxml::Children::iterator j = platformchildren.begin(); j != platformchildren.end(); ++j)
			{
				float x = sinxml::fromstring<float>((*j)->Get_child("x")->Get_value());
				float y = sinxml::fromstring<float>((*j)->Get_child("y")->Get_value());
				platform->Add_collision_vertex(Vector2(x, y));
			}
			platforms->push_back(platform);
		}
		if((*i)->Get_name() == "bitmap")
		{
			std::string filename = (*i)->Get_child("filename")->Get_value();
			int id = sinxml::fromstring<int>((*i)->Get_child("id")->Get_value());

			Bitmap* bitmap = new Bitmap(filename);
			bitmaps->push_back(bitmap);
			idbmpmap[id] = bitmap;
		}
	}
	for(sinxml::Children::iterator i = mapchildren.begin(); i != mapchildren.end(); ++i)
	{
		if((*i)->Get_name() == "sprite")
		{
			int id = sinxml::fromstring<int>((*i)->Get_child("id")->Get_value());
			float x = sinxml::fromstring<float>((*i)->Get_child("x")->Get_value());
			float y = sinxml::fromstring<float>((*i)->Get_child("y")->Get_value());
			Sprite* sprite = new Sprite(idbmpmap[id]);
			sprite->Set_position(Vector2(x, y));
			sprites->push_back(sprite);
		}
	}
}

void File::Open()
{
/*	ALLEGRO_DISPLAY *display;
	al_set_new_display_flags(ALLEGRO_WINDOWED);
	display = al_create_display(800, 600);

	ALLEGRO_FILECHOOSER* filechooser = al_create_native_file_dialog(NULL, "Save", "*.*", 0);
	al_show_native_file_dialog(display, filechooser);
	al_destroy_native_file_dialog(filechooser);
*/
	inputbox.Set_position(x, y+h);
	inputbox.Set_size(100, h);
	savebutton.Set_position(x, y+h*2);
	savebutton.Set_size(50, h);
	loadbutton.Set_position(x+50, y+h*2);
	loadbutton.Set_size(50, h);
	h = h*3;
	w = 100;
	resized = true;
	open = true;
}

void File::Close()
{
	h/=3;
	resized = true;
	open = false;
}
<|endoftext|>


<commit_before>void AddTask_dNdPtpp_TPCITS(Int_t cutMode =222 , char *particleMode ="default", char* eventTrigger="kINT7"){

  TString stEventTrigger(eventTrigger);
  TString stParticleMode(particleMode);

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {Error("AddTask_dNdPtpp_TPCITS", "No analysis manager found.");return 0;}

  Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);

  // Switch off all AliInfo (too much output!!!)
  AliLog::SetGlobalLogLevel(AliLog::kError);
  mgr->SetDebugLevel(0);

  /// Create event cuts
  Float_t zvWindow = 30. ;

  AlidNdPtEventCuts *evtCuts = new AlidNdPtEventCuts("AlidNdPtEventCuts","Event cuts");
  evtCuts->SetZvRange(-zvWindow,zvWindow);
  evtCuts->SetMeanXYZv(0.0,0.0,0.0);
  evtCuts->SetSigmaMeanXYZv(1.0,1.0,10.0);
  evtCuts->SetTriggerRequired(kTRUE);

  // Create geom. acceptance cuts

  Float_t etaWindow = 1. ;
  Float_t ptMin = 0.10;

  AlidNdPtAcceptanceCuts *accCuts = new AlidNdPtAcceptanceCuts("AlidNdPtAcceptanceCuts","Geom. acceptance cuts");
  accCuts->SetEtaRange(-etaWindow,etaWindow);
  accCuts->SetPtRange(ptMin,1.e10);

  gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/SPECTRA/ChargedHadrons/dNdPt/macros/CreatedNdPtTrackCuts.C");
  AliESDtrackCuts* esdTrackCuts = CreatedNdPtTrackCuts(cutMode,hasMC);
  if (!esdTrackCuts) { printf("ERROR: esdTrackCuts could not be created\n"); return; }
  esdTrackCuts->SetHistogramsOn(kTRUE);

  // Create task
  AlidNdPtTask *task = new AlidNdPtTask("AlidNdPtTask");
  task->SetUseMCInfo(hasMC);

  // trigger selection: MB
  if(stEventTrigger.Contains("kINT7")) task->SelectCollisionCandidates(AliVEvent::kINT7);
  else if(stEventTrigger.Contains("kMB")) task->SelectCollisionCandidates(AliVEvent::kMB);

  // Create cut analysis object
  AlidNdPtAnalysis *fdNdPtAnalysispp = new AlidNdPtAnalysis("dNdPtAnalysis","dN/dPt Analysis");
  fdNdPtAnalysispp->SetEventCuts(evtCuts);
  fdNdPtAnalysispp->SetAcceptanceCuts(accCuts);
  fdNdPtAnalysispp->SetTrackCuts(esdTrackCuts);
  fdNdPtAnalysispp->SetAnalysisMode(AlidNdPtHelper::kTPCITS);
  if(stEventTrigger.Contains("kINT7")) fdNdPtAnalysispp->SetTriggerMask(AliVEvent::kINT7);
  else if(stEventTrigger.Contains("kMB")) fdNdPtAnalysispp->SetTriggerMask(AliVEvent::kMB);

  // SetParticleMode
  if(stParticleMode.Contains("Pion")){fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kMCPion);}
  else if (stParticleMode.Contains("Proton")){fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kMCProton);}
  else if (stParticleMode.Contains("Kaon")){fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kMCKaon);}
  else if (stParticleMode.Contains("RemainingRest")){fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kMCRemainingRest);}
  else if (stParticleMode.Contains("Rest")){fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kMCRest);}
  else if (stParticleMode.Contains("Lambda")){fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kMCLambda);}
  else if (stParticleMode.Contains("SigmaPlus")){fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kMCSigmaPlus);}
  else if (stParticleMode.Contains("SigmaMinus")){fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kMCSigmaMinus);}
  else if (stParticleMode.Contains("XiMinus")){fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kMCXiMinus);}
  else if (stParticleMode.Contains("OmegaMinus")){fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kMCOmegaMinus);}
  else if (stParticleMode.Contains("Plus")){fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kPlus);}
  else if (stParticleMode.Contains("Minus")){fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kMinus);}
  else if (stParticleMode.Contains("Electron")){fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kMCElectron);}
  else if (stParticleMode.Contains("Muon")){fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kMCMuon);}
  else if (stParticleMode.Contains("InclWoSigma")) {fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kInclWoSimga);}
  else{fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kAllPart);}
  // Change binning
  const Int_t ptNbins = 81;
  Double_t bins[82] = {0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0, 3.2, 3.4, 3.6, 3.8, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 18.0, 20.0, 22.0, 24.0, 26.0, 28.0, 30.0, 32.0, 34.0, 36.0, 40.0, 45.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0, 110.0, 120.0, 130.0, 140.0, 150.0, 160.0, 180.0, 200.0};
  Double_t* binsPt = new Double_t[82];
  for (int i=0; i<82; i++) {binsPt[i] = bins[i];}
  fdNdPtAnalysispp->SetBinsPt(ptNbins, binsPt);
  fdNdPtAnalysispp->SetBinsPtCorr(ptNbins, binsPt);
  fdNdPtAnalysispp->SetUseMCInfo(hasMC);
  fdNdPtAnalysispp->SetHistogramsOn(hasMC);

  task->AddAnalysisObject( fdNdPtAnalysispp );

  // Add task
  mgr->AddTask(task);

  // Create containers for input
  AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
  mgr->ConnectInput(task, 0, cinput);

  TString stContainerName;
  stContainerName = Form("dNdPt_pp_%d",cutMode);
  if(!stParticleMode.Contains("default")) {
    stContainerName = stContainerName + "_" +stParticleMode;
  }

  AliAnalysisDataContainer *coutput = mgr->CreateContainer(stContainerName,TList::Class(),AliAnalysisManager::kOutputContainer, mgr->GetCommonFileName());

  mgr->ConnectOutput(task, 1, coutput);
}

<commit_msg>IsPythia flag and BG rejection<commit_after>void AddTask_dNdPtpp_TPCITS(Int_t cutMode =222 , char *particleMode ="default", char* eventTrigger="kINT7"){

  TString stEventTrigger(eventTrigger);
  TString stParticleMode(particleMode);

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {Error("AddTask_dNdPtpp_TPCITS", "No analysis manager found.");return 0;}

  Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);

  // Switch off all AliInfo (too much output!!!)
  AliLog::SetGlobalLogLevel(AliLog::kError);
  mgr->SetDebugLevel(0);

  /// Create event cuts
  Float_t zvWindow = 30. ;

  AlidNdPtEventCuts *evtCuts = new AlidNdPtEventCuts("AlidNdPtEventCuts","Event cuts");
  evtCuts->SetZvRange(-zvWindow,zvWindow);
  evtCuts->SetMeanXYZv(0.0,0.0,0.0);
  evtCuts->SetSigmaMeanXYZv(1.0,1.0,10.0);
  evtCuts->SetTriggerRequired(kTRUE);

  // Create geom. acceptance cuts

  Float_t etaWindow = 1. ;
  Float_t ptMin = 0.10;

  AlidNdPtAcceptanceCuts *accCuts = new AlidNdPtAcceptanceCuts("AlidNdPtAcceptanceCuts","Geom. acceptance cuts");
  accCuts->SetEtaRange(-etaWindow,etaWindow);
  accCuts->SetPtRange(ptMin,1.e10);

  gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/SPECTRA/ChargedHadrons/dNdPt/macros/CreatedNdPtTrackCuts.C");
  AliESDtrackCuts* esdTrackCuts = CreatedNdPtTrackCuts(cutMode,hasMC);
  if (!esdTrackCuts) { printf("ERROR: esdTrackCuts could not be created\n"); return; }
  esdTrackCuts->SetHistogramsOn(kTRUE);

  // Create task
  AlidNdPtTask *task = new AlidNdPtTask("AlidNdPtTask");
  task->SetUseMCInfo(hasMC);

  // trigger selection: MB
  if(stEventTrigger.Contains("kINT7")) task->SelectCollisionCandidates(AliVEvent::kINT7);
  else if(stEventTrigger.Contains("kMB")) task->SelectCollisionCandidates(AliVEvent::kMB);

  // Create cut analysis object
  AlidNdPtAnalysis *fdNdPtAnalysispp = new AlidNdPtAnalysis("dNdPtAnalysis","dN/dPt Analysis");
  fdNdPtAnalysispp->SetEventCuts(evtCuts);
  fdNdPtAnalysispp->SetAcceptanceCuts(accCuts);
  fdNdPtAnalysispp->SetTrackCuts(esdTrackCuts);
  fdNdPtAnalysispp->SetAnalysisMode(AlidNdPtHelper::kTPCITS);
  if(stEventTrigger.Contains("kINT7")) fdNdPtAnalysispp->SetTriggerMask(AliVEvent::kINT7);
  else if(stEventTrigger.Contains("kMB")) fdNdPtAnalysispp->SetTriggerMask(AliVEvent::kMB);
  //fdNdPtAnalysispp->SetUseSPDClusterVsTrackletRejection(kTRUE);
  //fdNdPtAnalysispp->SetRequireCompleteDAQ(kTRUE);
  //fdNdPtAnalysispp->SetUseTOFBunchCrossing(kFALSE);
  if(hasMC)
  {
    fdNdPtAnalysispp->SetUseMCInfo(kTRUE);
    fdNdPtAnalysispp->SetHistogramsOn(kTRUE);
    fdNdPtAnalysispp->SetIsPythia(kTRUE);
    //fdNdPtAnalysis->SetHistogramsOn(kFALSE);
  }

  // SetParticleMode
  if(stParticleMode.Contains("Pion")){fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kMCPion);}
  else if (stParticleMode.Contains("Proton")){fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kMCProton);}
  else if (stParticleMode.Contains("Kaon")){fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kMCKaon);}
  else if (stParticleMode.Contains("RemainingRest")){fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kMCRemainingRest);}
  else if (stParticleMode.Contains("Rest")){fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kMCRest);}
  else if (stParticleMode.Contains("Lambda")){fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kMCLambda);}
  else if (stParticleMode.Contains("SigmaPlus")){fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kMCSigmaPlus);}
  else if (stParticleMode.Contains("SigmaMinus")){fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kMCSigmaMinus);}
  else if (stParticleMode.Contains("XiMinus")){fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kMCXiMinus);}
  else if (stParticleMode.Contains("OmegaMinus")){fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kMCOmegaMinus);}
  else if (stParticleMode.Contains("Plus")){fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kPlus);}
  else if (stParticleMode.Contains("Minus")){fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kMinus);}
  else if (stParticleMode.Contains("Electron")){fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kMCElectron);}
  else if (stParticleMode.Contains("Muon")){fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kMCMuon);}
  else if (stParticleMode.Contains("InclWoSigma")) {fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kInclWoSimga);}
  else{fdNdPtAnalysispp->SetParticleMode(AlidNdPtHelper::kAllPart);}
  // Change binning
  const Int_t ptNbins = 81;
  Double_t bins[82] = {0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0, 3.2, 3.4, 3.6, 3.8, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 18.0, 20.0, 22.0, 24.0, 26.0, 28.0, 30.0, 32.0, 34.0, 36.0, 40.0, 45.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0, 110.0, 120.0, 130.0, 140.0, 150.0, 160.0, 180.0, 200.0};
  Double_t* binsPt = new Double_t[82];
  for (int i=0; i<82; i++) {binsPt[i] = bins[i];}
  fdNdPtAnalysispp->SetBinsPt(ptNbins, binsPt);
  fdNdPtAnalysispp->SetBinsPtCorr(ptNbins, binsPt);
  fdNdPtAnalysispp->SetUseMCInfo(hasMC);
  fdNdPtAnalysispp->SetHistogramsOn(hasMC);

  task->AddAnalysisObject( fdNdPtAnalysispp );

  // Add task
  mgr->AddTask(task);

  // Create containers for input
  AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
  mgr->ConnectInput(task, 0, cinput);

  TString stContainerName;
  stContainerName = Form("dNdPt_pp_%d",cutMode);
  if(!stParticleMode.Contains("default")) {
    stContainerName = stContainerName + "_" +stParticleMode;
  }

  AliAnalysisDataContainer *coutput = mgr->CreateContainer(stContainerName,TList::Class(),AliAnalysisManager::kOutputContainer, mgr->GetCommonFileName());

  mgr->ConnectOutput(task, 1, coutput);
}

<|endoftext|>