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

#ifndef __FRAMEWORK_HELPER_OCOMPONENTENUMERATION_HXX_
#define __FRAMEWORK_HELPER_OCOMPONENTENUMERATION_HXX_

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_OMUTEXMEMBER_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif

#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XENUMERATION_HPP_
#include <com/sun/star/container/XEnumeration.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

namespace framework{

//_________________________________________________________________________________________________________________
//  exported const
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  exported definitions
//_________________________________________________________________________________________________________________

/*-************************************************************************************************************//**
    @short          implement a helper for a oneway enumeration of components
    @descr          You can step during this list only for one time! Its a snapshot.
                    Don't forget to release the reference. You are the owner of an instance of this implementation.
                    You cant use this as a baseclass. Please use it as a dynamical object for return.

    @implements     XInterface
                    XTypeProvider
                    XEventListener
                    XEnumeration

    @base           ThreadHelpBase
                    OWeakObject

    @devstatus      ready to use
    @threadsafe     yes
*//*-*************************************************************************************************************/

class OComponentEnumeration :   public css::lang::XTypeProvider     ,
                                public css::lang::XEventListener    ,
                                public css::container::XEnumeration ,
                                public ThreadHelpBase               ,
                                public ::cppu::OWeakObject
{
    //-------------------------------------------------------------------------------------------------------------
    //  public methods
    //-------------------------------------------------------------------------------------------------------------

    public:

        //---------------------------------------------------------------------------------------------------------
        //  constructor / destructor
        //---------------------------------------------------------------------------------------------------------

        /*-****************************************************************************************************//**
            @short      constructor to initialize this enumeration
            @descr      An enumeration is a list with oneway-access! You can get every member only for one time.
                        This method allow to initialize this oneway list with values.

            @seealso    -

            @param      "seqComponents" is a sequence of interfaces, which are components.
            @return     -

            @onerror    Do nothing and reset this object to default with an empty list.
        *//*-*****************************************************************************************************/

         OComponentEnumeration( const css::uno::Sequence< css::uno::Reference< css::lang::XComponent > >& seqComponents );

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

        DECLARE_XINTERFACE
        DECLARE_XTYPEPROVIDER

        //---------------------------------------------------------------------------------------------------------
        //  XEventListener
        //---------------------------------------------------------------------------------------------------------

        /*-****************************************************************************************************//**
            @short      last chance to release all references and free memory
            @descr      This method is called, if the enumeration is used completly and has no more elements.
                        Then we must destroy ouer list and release all references to other objects.

            @seealso    interface XEventListener

            @param      "aEvent" describe the source of this event.
            @return     -

            @onerror    -
        *//*-*****************************************************************************************************/

        virtual void SAL_CALL disposing( const css::lang::EventObject& aEvent ) throw( css::uno::RuntimeException );

        //---------------------------------------------------------------------------------------------------------
        //  XEnumeration
        //---------------------------------------------------------------------------------------------------------

        /*-****************************************************************************************************//**
            @short      check count of accessible elements of enumeration
            @descr      You can call this method to get information about accessible elements in future.
                        Elements you have already getted are not accessible!

            @seealso    interface XEnumeration

            @param      -
            @return     sal_True  = if more elements accessible

                        sal_False = other way

            @onerror    sal_False

                        (List is emtpy and there no accessible elements ...)
        *//*-*****************************************************************************************************/

        virtual sal_Bool SAL_CALL hasMoreElements() throw( css::uno::RuntimeException );

        /*-****************************************************************************************************//**
            @short      give the next element, if some exist
            @descr      If a call "hasMoreElements()" return true, you can get the next element of list.

            @seealso    interface XEnumeration

            @param      -
            @return     A Reference to a component, safed in an Any-structure.

            @onerror    If end of enumeration is arrived or there are no elements in list => a NoSuchElementException is thrown.
        *//*-*****************************************************************************************************/

        virtual css::uno::Any SAL_CALL nextElement() throw( css::container::NoSuchElementException  ,
                                                             css::lang::WrappedTargetException      ,
                                                            css::uno::RuntimeException              );

    //-------------------------------------------------------------------------------------------------------------
    //  protected methods
    //-------------------------------------------------------------------------------------------------------------

    protected:

        /*-****************************************************************************************************//**
            @short      standard destructor
            @descr      This method destruct an instance of this class and clear some member.
                        We make it protected, because its not supported to use this class as normal instance!
                        You must create it dynamical in memory and use a pointer.

            @seealso    -

            @param      -
            @return     -

            @onerror    -
        *//*-*****************************************************************************************************/

        virtual ~OComponentEnumeration();

        /*-****************************************************************************************************//**
            @short      reset instance to default values

            @descr      There are two ways to delete an instance of this class.

                        1) delete with destructor

                        2) dispose from parent or factory ore ...

                        This method do the same for both ways! It free used memory and release references ...

            @seealso    method dispose()
            @seealso    destructor ~TaskEnumeration()

            @param      -

            @return     -

            @onerror    -
        *//*-*****************************************************************************************************/

        virtual void impl_resetObject();

    //-------------------------------------------------------------------------------------------------------------
    //  private methods
    //-------------------------------------------------------------------------------------------------------------

    private:

    //-------------------------------------------------------------------------------------------------------------
    //  debug methods
    //  (should be private everyway!)
    //-------------------------------------------------------------------------------------------------------------

        /*-****************************************************************************************************//**
            @short      debug-method to check incoming parameter of some other mehods of this class
            @descr      The following methods are used to check parameters for other methods
                        of this class. The return value is used directly for an ASSERT(...).

            @seealso    ASSERT in implementation!

            @param      references to checking variables
            @return     sal_False on invalid parameter

                        sal_True  otherway

            @onerror    -
        *//*-*****************************************************************************************************/

    #ifdef ENABLE_ASSERTIONS

    private:

        static sal_Bool impldbg_checkParameter_OComponentEnumerationCtor    (   const   css::uno::Sequence< css::uno::Reference< css::lang::XComponent > >& seqComponents   );
        static sal_Bool impldbg_checkParameter_disposing                    (   const   css::lang::EventObject&                                             aEvent          );

    #endif  // #ifdef ENABLE_ASSERTIONS

    //-------------------------------------------------------------------------------------------------------------
    //  variables
    //  (should be private everyway!)
    //-------------------------------------------------------------------------------------------------------------

    private:

        sal_uInt32                                                              m_nPosition         ;   /// current position in enumeration
        css::uno::Sequence< css::uno::Reference< css::lang::XComponent > >      m_seqComponents     ;   /// list of current components

};      //  class OComponentEnumeration

}       //  namespace framework

#endif  //  #ifndef __FRAMEWORK_HELPER_OCOMPONENTENUMERATION_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.562); FILE MERGED 2005/09/05 13:04:48 rt 1.4.562.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ocomponentenumeration.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 00:17:04 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef __FRAMEWORK_HELPER_OCOMPONENTENUMERATION_HXX_
#define __FRAMEWORK_HELPER_OCOMPONENTENUMERATION_HXX_

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_OMUTEXMEMBER_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif

#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_
#include <com/sun/star/lang/XEventListener.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XENUMERATION_HPP_
#include <com/sun/star/container/XEnumeration.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

namespace framework{

//_________________________________________________________________________________________________________________
//  exported const
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  exported definitions
//_________________________________________________________________________________________________________________

/*-************************************************************************************************************//**
    @short          implement a helper for a oneway enumeration of components
    @descr          You can step during this list only for one time! Its a snapshot.
                    Don't forget to release the reference. You are the owner of an instance of this implementation.
                    You cant use this as a baseclass. Please use it as a dynamical object for return.

    @implements     XInterface
                    XTypeProvider
                    XEventListener
                    XEnumeration

    @base           ThreadHelpBase
                    OWeakObject

    @devstatus      ready to use
    @threadsafe     yes
*//*-*************************************************************************************************************/

class OComponentEnumeration :   public css::lang::XTypeProvider     ,
                                public css::lang::XEventListener    ,
                                public css::container::XEnumeration ,
                                public ThreadHelpBase               ,
                                public ::cppu::OWeakObject
{
    //-------------------------------------------------------------------------------------------------------------
    //  public methods
    //-------------------------------------------------------------------------------------------------------------

    public:

        //---------------------------------------------------------------------------------------------------------
        //  constructor / destructor
        //---------------------------------------------------------------------------------------------------------

        /*-****************************************************************************************************//**
            @short      constructor to initialize this enumeration
            @descr      An enumeration is a list with oneway-access! You can get every member only for one time.
                        This method allow to initialize this oneway list with values.

            @seealso    -

            @param      "seqComponents" is a sequence of interfaces, which are components.
            @return     -

            @onerror    Do nothing and reset this object to default with an empty list.
        *//*-*****************************************************************************************************/

         OComponentEnumeration( const css::uno::Sequence< css::uno::Reference< css::lang::XComponent > >& seqComponents );

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

        DECLARE_XINTERFACE
        DECLARE_XTYPEPROVIDER

        //---------------------------------------------------------------------------------------------------------
        //  XEventListener
        //---------------------------------------------------------------------------------------------------------

        /*-****************************************************************************************************//**
            @short      last chance to release all references and free memory
            @descr      This method is called, if the enumeration is used completly and has no more elements.
                        Then we must destroy ouer list and release all references to other objects.

            @seealso    interface XEventListener

            @param      "aEvent" describe the source of this event.
            @return     -

            @onerror    -
        *//*-*****************************************************************************************************/

        virtual void SAL_CALL disposing( const css::lang::EventObject& aEvent ) throw( css::uno::RuntimeException );

        //---------------------------------------------------------------------------------------------------------
        //  XEnumeration
        //---------------------------------------------------------------------------------------------------------

        /*-****************************************************************************************************//**
            @short      check count of accessible elements of enumeration
            @descr      You can call this method to get information about accessible elements in future.
                        Elements you have already getted are not accessible!

            @seealso    interface XEnumeration

            @param      -
            @return     sal_True  = if more elements accessible

                        sal_False = other way

            @onerror    sal_False

                        (List is emtpy and there no accessible elements ...)
        *//*-*****************************************************************************************************/

        virtual sal_Bool SAL_CALL hasMoreElements() throw( css::uno::RuntimeException );

        /*-****************************************************************************************************//**
            @short      give the next element, if some exist
            @descr      If a call "hasMoreElements()" return true, you can get the next element of list.

            @seealso    interface XEnumeration

            @param      -
            @return     A Reference to a component, safed in an Any-structure.

            @onerror    If end of enumeration is arrived or there are no elements in list => a NoSuchElementException is thrown.
        *//*-*****************************************************************************************************/

        virtual css::uno::Any SAL_CALL nextElement() throw( css::container::NoSuchElementException  ,
                                                             css::lang::WrappedTargetException      ,
                                                            css::uno::RuntimeException              );

    //-------------------------------------------------------------------------------------------------------------
    //  protected methods
    //-------------------------------------------------------------------------------------------------------------

    protected:

        /*-****************************************************************************************************//**
            @short      standard destructor
            @descr      This method destruct an instance of this class and clear some member.
                        We make it protected, because its not supported to use this class as normal instance!
                        You must create it dynamical in memory and use a pointer.

            @seealso    -

            @param      -
            @return     -

            @onerror    -
        *//*-*****************************************************************************************************/

        virtual ~OComponentEnumeration();

        /*-****************************************************************************************************//**
            @short      reset instance to default values

            @descr      There are two ways to delete an instance of this class.

                        1) delete with destructor

                        2) dispose from parent or factory ore ...

                        This method do the same for both ways! It free used memory and release references ...

            @seealso    method dispose()
            @seealso    destructor ~TaskEnumeration()

            @param      -

            @return     -

            @onerror    -
        *//*-*****************************************************************************************************/

        virtual void impl_resetObject();

    //-------------------------------------------------------------------------------------------------------------
    //  private methods
    //-------------------------------------------------------------------------------------------------------------

    private:

    //-------------------------------------------------------------------------------------------------------------
    //  debug methods
    //  (should be private everyway!)
    //-------------------------------------------------------------------------------------------------------------

        /*-****************************************************************************************************//**
            @short      debug-method to check incoming parameter of some other mehods of this class
            @descr      The following methods are used to check parameters for other methods
                        of this class. The return value is used directly for an ASSERT(...).

            @seealso    ASSERT in implementation!

            @param      references to checking variables
            @return     sal_False on invalid parameter

                        sal_True  otherway

            @onerror    -
        *//*-*****************************************************************************************************/

    #ifdef ENABLE_ASSERTIONS

    private:

        static sal_Bool impldbg_checkParameter_OComponentEnumerationCtor    (   const   css::uno::Sequence< css::uno::Reference< css::lang::XComponent > >& seqComponents   );
        static sal_Bool impldbg_checkParameter_disposing                    (   const   css::lang::EventObject&                                             aEvent          );

    #endif  // #ifdef ENABLE_ASSERTIONS

    //-------------------------------------------------------------------------------------------------------------
    //  variables
    //  (should be private everyway!)
    //-------------------------------------------------------------------------------------------------------------

    private:

        sal_uInt32                                                              m_nPosition         ;   /// current position in enumeration
        css::uno::Sequence< css::uno::Reference< css::lang::XComponent > >      m_seqComponents     ;   /// list of current components

};      //  class OComponentEnumeration

}       //  namespace framework

#endif  //  #ifndef __FRAMEWORK_HELPER_OCOMPONENTENUMERATION_HXX_
<|endoftext|>


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

#ifndef __FRAMEWORK_UIELEMENT_CONSTITEMCONTAINER_HXX_
#define __FRAMEWORK_UIELEMENT_CONSTITEMCONTAINER_HXX_

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_CONTAINER_XINDEXCONTAINER_HPP_
#include <com/sun/star/container/XIndexContainer.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XSINGLECOMPONENTFACTORY_HPP_
#include <com/sun/star/lang/XSingleComponentFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_XFASTPROPERTYSET_HPP_
#include <com/sun/star/beans/XFastPropertySet.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _RTL_OUSTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif

#ifndef _CPPUHELPER_PROPSHLP_HXX
#include <cppuhelper/propshlp.hxx>
#endif

#include <vector>

namespace framework
{

class RootItemContainer;
class ItemContainer;
class ConstItemContainer :  public ::com::sun::star::lang::XTypeProvider    ,
                            public com::sun::star::container::XIndexAccess  ,
                            public ::com::sun::star::lang::XUnoTunnel       ,
                            public ::com::sun::star::beans::XFastPropertySet,
                            public ::com::sun::star::beans::XPropertySet    ,
                            public ::cppu::OWeakObject
{
    friend class RootItemContainer;
    friend class ItemContainer;

    public:
        ConstItemContainer();
        ConstItemContainer( const ItemContainer& rtemContainer );
        ConstItemContainer( const RootItemContainer& rRootItemContainer, sal_Bool bFastCopy = sal_False );
        ConstItemContainer( const com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess >& rSourceContainer, sal_Bool bFastCopy = sal_False );
        virtual ~ConstItemContainer();

        //---------------------------------------------------------------------------------------------------------
        //  XInterface, XTypeProvider
        //---------------------------------------------------------------------------------------------------------
        DECLARE_XINTERFACE
        DECLARE_XTYPEPROVIDER

        // XUnoTunnel
        static const ::com::sun::star::uno::Sequence< sal_Int8 >&   GetUnoTunnelId() throw();
        static ConstItemContainer*                                  GetImplementation( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rxIFace ) throw();
        sal_Int64                                                   SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& rIdentifier ) throw(::com::sun::star::uno::RuntimeException);

        // XIndexAccess
        virtual sal_Int32 SAL_CALL getCount()
            throw (::com::sun::star::uno::RuntimeException);

        virtual ::com::sun::star::uno::Any SAL_CALL getByIndex( sal_Int32 Index )
            throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

        // XElementAccess
        virtual ::com::sun::star::uno::Type SAL_CALL getElementType()
            throw (::com::sun::star::uno::RuntimeException)
        {
            return ::getCppuType((com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >*)0);
        }

        virtual sal_Bool SAL_CALL hasElements()
            throw (::com::sun::star::uno::RuntimeException);

        // XPropertySet
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

        // XFastPropertySet
        virtual void SAL_CALL setFastPropertyValue( sal_Int32 nHandle, const ::com::sun::star::uno::Any& aValue ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Any SAL_CALL getFastPropertyValue( sal_Int32 nHandle ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    private:
        ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();
        const com::sun::star::uno::Sequence< com::sun::star::beans::Property > impl_getStaticPropertyDescriptor();
        static ::com::sun::star::uno::Reference < ::com::sun::star::beans::XPropertySetInfo > SAL_CALL createPropertySetInfo( ::cppu::IPropertyArrayHelper & rProperties ) SAL_THROW( () );

        void copyItemContainer( const std::vector< com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > >& rSourceVector );
        com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess > deepCopyContainer( const com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess >& rSubContainer );

        std::vector< com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > > m_aItemVector;
        rtl::OUString                                                                        m_aUIName;
};

}

#endif // #ifndef __FRAMEWORK_UIELEMENT_CONSTITEMCONTAINER_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.288); FILE MERGED 2005/09/05 13:05:30 rt 1.3.288.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: constitemcontainer.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 00:42:12 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef __FRAMEWORK_UIELEMENT_CONSTITEMCONTAINER_HXX_
#define __FRAMEWORK_UIELEMENT_CONSTITEMCONTAINER_HXX_

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_CONTAINER_XINDEXCONTAINER_HPP_
#include <com/sun/star/container/XIndexContainer.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XSINGLECOMPONENTFACTORY_HPP_
#include <com/sun/star/lang/XSingleComponentFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_XFASTPROPERTYSET_HPP_
#include <com/sun/star/beans/XFastPropertySet.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _RTL_OUSTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif

#ifndef _CPPUHELPER_PROPSHLP_HXX
#include <cppuhelper/propshlp.hxx>
#endif

#include <vector>

namespace framework
{

class RootItemContainer;
class ItemContainer;
class ConstItemContainer :  public ::com::sun::star::lang::XTypeProvider    ,
                            public com::sun::star::container::XIndexAccess  ,
                            public ::com::sun::star::lang::XUnoTunnel       ,
                            public ::com::sun::star::beans::XFastPropertySet,
                            public ::com::sun::star::beans::XPropertySet    ,
                            public ::cppu::OWeakObject
{
    friend class RootItemContainer;
    friend class ItemContainer;

    public:
        ConstItemContainer();
        ConstItemContainer( const ItemContainer& rtemContainer );
        ConstItemContainer( const RootItemContainer& rRootItemContainer, sal_Bool bFastCopy = sal_False );
        ConstItemContainer( const com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess >& rSourceContainer, sal_Bool bFastCopy = sal_False );
        virtual ~ConstItemContainer();

        //---------------------------------------------------------------------------------------------------------
        //  XInterface, XTypeProvider
        //---------------------------------------------------------------------------------------------------------
        DECLARE_XINTERFACE
        DECLARE_XTYPEPROVIDER

        // XUnoTunnel
        static const ::com::sun::star::uno::Sequence< sal_Int8 >&   GetUnoTunnelId() throw();
        static ConstItemContainer*                                  GetImplementation( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rxIFace ) throw();
        sal_Int64                                                   SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& rIdentifier ) throw(::com::sun::star::uno::RuntimeException);

        // XIndexAccess
        virtual sal_Int32 SAL_CALL getCount()
            throw (::com::sun::star::uno::RuntimeException);

        virtual ::com::sun::star::uno::Any SAL_CALL getByIndex( sal_Int32 Index )
            throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

        // XElementAccess
        virtual ::com::sun::star::uno::Type SAL_CALL getElementType()
            throw (::com::sun::star::uno::RuntimeException)
        {
            return ::getCppuType((com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >*)0);
        }

        virtual sal_Bool SAL_CALL hasElements()
            throw (::com::sun::star::uno::RuntimeException);

        // XPropertySet
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

        // XFastPropertySet
        virtual void SAL_CALL setFastPropertyValue( sal_Int32 nHandle, const ::com::sun::star::uno::Any& aValue ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Any SAL_CALL getFastPropertyValue( sal_Int32 nHandle ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    private:
        ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();
        const com::sun::star::uno::Sequence< com::sun::star::beans::Property > impl_getStaticPropertyDescriptor();
        static ::com::sun::star::uno::Reference < ::com::sun::star::beans::XPropertySetInfo > SAL_CALL createPropertySetInfo( ::cppu::IPropertyArrayHelper & rProperties ) SAL_THROW( () );

        void copyItemContainer( const std::vector< com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > >& rSourceVector );
        com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess > deepCopyContainer( const com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess >& rSubContainer );

        std::vector< com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > > m_aItemVector;
        rtl::OUString                                                                        m_aUIName;
};

}

#endif // #ifndef __FRAMEWORK_UIELEMENT_CONSTITEMCONTAINER_HXX_
<|endoftext|>


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

#include <iostream>
#include <fstream>
#include <exception>
#include <string>
#include <limits>
#include <cctype>
#include <CImg.h>

#include <ArgumentList.hpp>
#include <ColorMap.hpp>
#include <utils.hpp>

int main(int argc, char * argv[]) {
  unsigned int nrDMs = 0;
  unsigned int nrPeriods = 0;
  float minSNR = std::numeric_limits< float >::max();
  float maxSNR = std::numeric_limits< float >::min();
  float snrSpaceDim = 0.0f;
  float * snrSpace = 0;
  std::string outFilename;
  std::ifstream searchFile;

  isa::utils::ArgumentList args(argc, argv);
  try {
    searchFile.open(args.getSwitchArgument< std::string >("-input"));
    outFilename = args.getSwitchArgument< std::string >("-output");
    nrDMs = args.getSwitchArgument< unsigned int >("-dms");
    nrPeriods = args.getSwitchArgument< unsigned int >("-periods");
  } catch ( isa::utils::EmptyCommandLine & err ) {
    std::cerr << args.getName() << " -output ... -dms ... -periods ... input" << std::endl;
    return 1;
  } catch ( std::exception & err ) {
    std::cerr << err.what() << std::endl;
    return 1;
  }

  snrSpace = new float [nrDMs * nrPeriods];

  try {
    while ( true ) {
      searchFile.open(args.getFirst< std::string >());

      while ( ! searchFile.eof() ) {
        std::string temp;
        unsigned int splitPoint = 0;
        unsigned int DM = 0;
        unsigned int period = 0;
        float snr = 0.0f;

        std::getline(searchFile, temp);
        if ( ! std::isdigit(temp[0]) ) {
          continue;
        }
        splitPoint = temp.find(" ");
        period = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
        temp = temp.substr(splitPoint + 1);
        splitPoint = temp.find(" ");
        DM = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
        temp = temp.substr(splitPoint + 1);
        splitPoint = temp.find(" ");
        snr = isa::utils::castToType< std::string, float >(temp);

        if ( snr > maxSNR ) {
          maxSNR = snr;
        }
        if ( snr < minSNR ) {
          minSNR = snr;
        }

        snrSpace[(period * nrDMs) + DM] = snr;
      }
      searchFile.close();
    }
  } catch ( isa::utils::EmptyCommandLine & err ) {
    snrSpaceDim = maxSNR - minSNR;
  }

  cimg_library::CImg< unsigned char > searchImage(nrDMs, nrPeriods, 1, 3);
  AstroData::Color *colorMap = AstroData::getColorMap();
  for ( unsigned int period = 0; period < nrPeriods; period++ ) {
    for ( unsigned int DM = 0; DM < nrDMs; DM++ ) {
      float snr = snrSpace[(period * nrDMs) + DM];
      searchImage(DM, period, 0, 0) = (colorMap[static_cast< unsigned int >(((snr - minSNR) * 256.0f) / snrSpaceDim)]).getR();
      searchImage(DM, period, 0, 1) = (colorMap[static_cast< unsigned int >(((snr - minSNR) * 256.0f) / snrSpaceDim)]).getG();
      searchImage(DM, period, 0, 2) = (colorMap[static_cast< unsigned int >(((snr - minSNR) * 256.0f) / snrSpaceDim)]).getB();
    }
  }
  searchImage.save(outFilename.c_str());

  delete [] snrSpace;
  return 0;
}

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

#include <iostream>
#include <fstream>
#include <exception>
#include <string>
#include <limits>
#include <cctype>
#include <CImg.h>

#include <ArgumentList.hpp>
#include <ColorMap.hpp>
#include <utils.hpp>

int main(int argc, char * argv[]) {
  unsigned int nrDMs = 0;
  unsigned int nrPeriods = 0;
  float minSNR = std::numeric_limits< float >::max();
  float maxSNR = std::numeric_limits< float >::min();
  float snrSpaceDim = 0.0f;
  float * snrSpace = 0;
  std::string outFilename;
  std::ifstream searchFile;

  isa::utils::ArgumentList args(argc, argv);
  try {
    outFilename = args.getSwitchArgument< std::string >("-output");
    nrDMs = args.getSwitchArgument< unsigned int >("-dms");
    nrPeriods = args.getSwitchArgument< unsigned int >("-periods");
  } catch ( isa::utils::EmptyCommandLine & err ) {
    std::cerr << args.getName() << " -output ... -dms ... -periods ... input" << std::endl;
    return 1;
  } catch ( std::exception & err ) {
    std::cerr << err.what() << std::endl;
    return 1;
  }

  snrSpace = new float [nrDMs * nrPeriods];

  try {
    while ( true ) {
      searchFile.open(args.getFirst< std::string >());

      while ( ! searchFile.eof() ) {
        std::string temp;
        unsigned int splitPoint = 0;
        unsigned int DM = 0;
        unsigned int period = 0;
        float snr = 0.0f;

        std::getline(searchFile, temp);
        if ( ! std::isdigit(temp[0]) ) {
          continue;
        }
        splitPoint = temp.find(" ");
        period = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
        temp = temp.substr(splitPoint + 1);
        splitPoint = temp.find(" ");
        DM = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
        temp = temp.substr(splitPoint + 1);
        splitPoint = temp.find(" ");
        snr = isa::utils::castToType< std::string, float >(temp);

        if ( snr > maxSNR ) {
          maxSNR = snr;
        }
        if ( snr < minSNR ) {
          minSNR = snr;
        }

        snrSpace[(period * nrDMs) + DM] = snr;
      }
      searchFile.close();
    }
  } catch ( isa::utils::EmptyCommandLine & err ) {
    snrSpaceDim = maxSNR - minSNR;
  }

  cimg_library::CImg< unsigned char > searchImage(nrDMs, nrPeriods, 1, 3);
  AstroData::Color *colorMap = AstroData::getColorMap();
  for ( unsigned int period = 0; period < nrPeriods; period++ ) {
    for ( unsigned int DM = 0; DM < nrDMs; DM++ ) {
      float snr = snrSpace[(period * nrDMs) + DM];
      searchImage(DM, period, 0, 0) = (colorMap[static_cast< unsigned int >(((snr - minSNR) * 256.0f) / snrSpaceDim)]).getR();
      searchImage(DM, period, 0, 1) = (colorMap[static_cast< unsigned int >(((snr - minSNR) * 256.0f) / snrSpaceDim)]).getG();
      searchImage(DM, period, 0, 2) = (colorMap[static_cast< unsigned int >(((snr - minSNR) * 256.0f) / snrSpaceDim)]).getB();
    }
  }
  searchImage.save(outFilename.c_str());

  delete [] snrSpace;
  return 0;
}

<|endoftext|>


<commit_before>#include "../include/sela/player.hpp"

namespace sela
{

void Player::initializeAo()
{
    ao_initialize();
    driver = ao_default_driver_id();
}

void Player::setAoFormat(const data::WavFormatSubChunk &format)
{
    ao_format.bits = format.bitsPerSample;
    ao_format.rate = format.sampleRate;
    ao_format.channels = format.numChannels;
    ao_format.byte_format = AO_FMT_NATIVE;
    ao_format.matrix = 0;
    dev = ao_open_live(driver, &ao_format, NULL);
}

void Player::play(file::WavFile wavFile)
{
    initializeAo();
    setAoFormat(wavFile.wavChunk.formatSubChunk);
    audioPackets.reserve(wavFile.wavChunk.dataSubChunk.wavFrames.size());

    const size_t bytesPerSample = wavFile.wavChunk.formatSubChunk.bitsPerSample / 8;
    for (data::WavFrame wavFrame : wavFile.wavChunk.dataSubChunk.wavFrames)
    {
        int16_t *samples = new int16_t[wavFrame.samples.size() * wavFrame.samples[0].size()];
        size_t offset = 0;
        for (size_t i = 0; i < wavFrame.samples[0].size(); i++)
        {
            samples[offset] = (uint16_t)wavFrame.samples[0][i];
            offset++;
            samples[offset] = (uint16_t)wavFrame.samples[1][i];
            offset++;
        }
        audioPackets.push_back(data::AudioPacket((char *)samples, wavFrame.samples.size() * wavFrame.samples[0].size() * sizeof(int16_t)));
    }

    //Transform data to proper format
    for (data::AudioPacket audioPacket : audioPackets)
    {
        ao_play(dev, audioPacket.audio, audioPacket.bufferSize);
        delete[] audioPacket.audio;
    }

    destroyAo();
}

void Player::destroyAo()
{
    ao_close(dev);
    ao_shutdown();
}
} // namespace sela<commit_msg>Unused variable removed<commit_after>#include "../include/sela/player.hpp"

namespace sela
{

void Player::initializeAo()
{
    ao_initialize();
    driver = ao_default_driver_id();
}

void Player::setAoFormat(const data::WavFormatSubChunk &format)
{
    ao_format.bits = format.bitsPerSample;
    ao_format.rate = format.sampleRate;
    ao_format.channels = format.numChannels;
    ao_format.byte_format = AO_FMT_NATIVE;
    ao_format.matrix = 0;
    dev = ao_open_live(driver, &ao_format, NULL);
}

void Player::play(file::WavFile wavFile)
{
    initializeAo();
    setAoFormat(wavFile.wavChunk.formatSubChunk);
    audioPackets.reserve(wavFile.wavChunk.dataSubChunk.wavFrames.size());

    for (data::WavFrame wavFrame : wavFile.wavChunk.dataSubChunk.wavFrames)
    {
        int16_t *samples = new int16_t[wavFrame.samples.size() * wavFrame.samples[0].size()];
        size_t offset = 0;
        for (size_t i = 0; i < wavFrame.samples[0].size(); i++)
        {
            samples[offset] = (uint16_t)wavFrame.samples[0][i];
            offset++;
            samples[offset] = (uint16_t)wavFrame.samples[1][i];
            offset++;
        }
        audioPackets.push_back(data::AudioPacket((char *)samples, wavFrame.samples.size() * wavFrame.samples[0].size() * sizeof(int16_t)));
    }

    //Transform data to proper format
    for (data::AudioPacket audioPacket : audioPackets)
    {
        ao_play(dev, audioPacket.audio, audioPacket.bufferSize);
        delete[] audioPacket.audio;
    }

    destroyAo();
}

void Player::destroyAo()
{
    ao_close(dev);
    ao_shutdown();
}
} // namespace sela<|endoftext|>


<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Nathan Osman
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include <qmdnsengine/abstractserver.h>
#include <qmdnsengine/browser.h>
#include <qmdnsengine/cache.h>
#include <qmdnsengine/dns.h>
#include <qmdnsengine/mdns.h>
#include <qmdnsengine/message.h>
#include <qmdnsengine/query.h>
#include <qmdnsengine/record.h>

#include "browser_p.h"

using namespace QMdnsEngine;

BrowserPrivate::BrowserPrivate(Browser *browser, AbstractServer *server, const QByteArray &type, Cache *existingCache)
    : QObject(browser),
      q(browser),
      server(server),
      type(type),
      cache(existingCache ? existingCache : new Cache(this))
{
    connect(server, &AbstractServer::messageReceived, this, &BrowserPrivate::onMessageReceived);
    connect(cache, &Cache::shouldQuery, this, &BrowserPrivate::onShouldQuery);
    connect(cache, &Cache::recordExpired, this, &BrowserPrivate::onRecordExpired);
    connect(&queryTimer, &QTimer::timeout, this, &BrowserPrivate::onQueryTimeout);
    connect(&serviceTimer, &QTimer::timeout, this, &BrowserPrivate::onServiceTimeout);

    queryTimer.setSingleShot(true);
    serviceTimer.setSingleShot(true);

    // Immediately begin browsing for services
    onQueryTimeout();
}

// TODO: multiple SRV records not supported

bool BrowserPrivate::updateService(const QByteArray &fqName)
{
    // Split the FQDN into service name and type
    int index = fqName.indexOf('.');
    QByteArray serviceName = fqName.left(index);
    QByteArray serviceType = fqName.mid(index + 1);

    // Immediately return if a PTR record does not exist
    Record ptrRecord;
    if (!cache->lookupRecord(serviceType, PTR, ptrRecord)) {
        return false;
    }

    // If a SRV record is missing, query for it (by returning true)
    Record srvRecord;
    if (!cache->lookupRecord(fqName, SRV, srvRecord)) {
        return true;
    }

    Service service;
    service.setName(serviceName);
    service.setType(serviceType);
    service.setHostname(srvRecord.target());
    service.setPort(srvRecord.port());

    // If TXT records are available for the service, add their values
    QList<Record> txtRecords;
    if (cache->lookupRecords(fqName, TXT, txtRecords)) {
        QMap<QByteArray, QByteArray> attributes;
        foreach (Record record, txtRecords) {
            for (auto i = record.attributes().constBegin();
                    i != record.attributes().constEnd(); ++i) {
                attributes.insert(i.key(), i.value());
            }
        }
        service.setAttributes(attributes);
    }

    // If the service existed, this is an update; otherwise it is a new
    // addition; emit the appropriate signal
    if (!services.contains(fqName)) {
        emit q->serviceAdded(service);
    } else if(services.value(fqName) != service) {
        emit q->serviceUpdated(service);
    }

    services.insert(fqName, service);

    return false;
}

void BrowserPrivate::onMessageReceived(const Message &message)
{
    if (!message.isResponse()) {
        return;
    }

    // Use a set to track all services that are updated in the message - this
    // avoids extraneous signals being emitted if SRV and TXT are provided
    QSet<QByteArray> updateNames;
    foreach (Record record, message.records()) {
        bool any = type == MdnsBrowseType;
        if (record.type() == PTR && record.name() == MdnsBrowseType) {
            cache->addRecord(record);
            ptrTargets.insert(record.target());
            serviceTimer.stop();
            serviceTimer.start(100);
        } else if ((record.type() == PTR && (any || record.name() == type)) ||
                (record.type() == SRV && (any || record.name().endsWith("." + type))) ||
                (record.type() == TXT && (any || record.name().endsWith("." + type)))) {
            cache->addRecord(record);
            switch (record.type()) {
            case PTR:
                updateNames.insert(record.target());
                break;
            case SRV:
            case TXT:
                updateNames.insert(record.name());
                break;
            }
        }
    }

    // For each of the services marked to be updated, perform the update and
    // make a list of all missing SRV records
    QSet<QByteArray> queryNames;
    foreach (QByteArray name, updateNames) {
        if (updateService(name)) {
            queryNames.insert(name);
        }
    }

    // Build and send a query for all of the SRV records
    if (queryNames.count()) {
        Message queryMessage;
        foreach (QByteArray name, queryNames) {
            Query query;
            query.setName(name);
            query.setType(SRV);
            queryMessage.addQuery(query);
            query.setType(TXT);
            queryMessage.addQuery(query);
        }
        server->sendMessageToAll(queryMessage);
    }
}

void BrowserPrivate::onShouldQuery(const Record &record)
{
    // Assume that all messages in the cache are still in use (by the browser)
    // and attempt to renew them immediately

    Query query;
    query.setName(record.name());
    query.setType(record.type());
    Message message;
    message.addQuery(query);
    server->sendMessageToAll(message);
}

void BrowserPrivate::onRecordExpired(const Record &record)
{
    // If the PTR or SRV record has expired for a service, then it must be
    // removed - TXT records on the other hand, cause an update

    QByteArray serviceName;
    switch (record.type()) {
    case PTR:
        serviceName = record.target();
        break;
    case SRV:
        serviceName = record.name();
        break;
    case TXT:
        updateService(record.name());
        return;
    }
    Service service = services.value(serviceName);
    if (!service.name().isNull() && (record.type() == PTR || record.type() == SRV)) {
        emit q->serviceRemoved(service);
        services.remove(serviceName);
    }
}

void BrowserPrivate::onQueryTimeout()
{
    Query query;
    query.setName(type);
    query.setType(PTR);
    Message message;
    message.addQuery(query);

    // TODO: including too many records could cause problems

    // Include all currently valid PTR records
    QList<Record> records;
    if (cache->lookupRecords(QByteArray(), PTR, records)) {
        foreach (Record record, records) {
            message.addRecord(record);
        }
    }

    server->sendMessageToAll(message);
    queryTimer.start(60 * 1000);
}

void BrowserPrivate::onServiceTimeout()
{
    if (ptrTargets.count()) {
        Message message;
        foreach (QByteArray target, ptrTargets) {
            Query query;
            query.setName(target);
            query.setType(PTR);
            message.addQuery(query);
        }

        // TODO: cached PTR records

        server->sendMessageToAll(message);

        ptrTargets.clear();
    }
}

Browser::Browser(AbstractServer *server, const QByteArray &type, Cache *cache, QObject *parent)
    : QObject(parent),
      d(new BrowserPrivate(this, server, type, cache))
{
}
<commit_msg>Refactor service browser and include cached PTR records when querying for specific services.<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Nathan Osman
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include <qmdnsengine/abstractserver.h>
#include <qmdnsengine/browser.h>
#include <qmdnsengine/cache.h>
#include <qmdnsengine/dns.h>
#include <qmdnsengine/mdns.h>
#include <qmdnsengine/message.h>
#include <qmdnsengine/query.h>
#include <qmdnsengine/record.h>

#include "browser_p.h"

using namespace QMdnsEngine;

BrowserPrivate::BrowserPrivate(Browser *browser, AbstractServer *server, const QByteArray &type, Cache *existingCache)
    : QObject(browser),
      q(browser),
      server(server),
      type(type),
      cache(existingCache ? existingCache : new Cache(this))
{
    connect(server, &AbstractServer::messageReceived, this, &BrowserPrivate::onMessageReceived);
    connect(cache, &Cache::shouldQuery, this, &BrowserPrivate::onShouldQuery);
    connect(cache, &Cache::recordExpired, this, &BrowserPrivate::onRecordExpired);
    connect(&queryTimer, &QTimer::timeout, this, &BrowserPrivate::onQueryTimeout);
    connect(&serviceTimer, &QTimer::timeout, this, &BrowserPrivate::onServiceTimeout);

    queryTimer.setInterval(60 * 1000);
    queryTimer.setSingleShot(true);

    serviceTimer.setInterval(100);
    serviceTimer.setSingleShot(true);

    // Immediately begin browsing for services
    onQueryTimeout();
}

// TODO: multiple SRV records not supported

bool BrowserPrivate::updateService(const QByteArray &fqName)
{
    // Split the FQDN into service name and type
    int index = fqName.indexOf('.');
    QByteArray serviceName = fqName.left(index);
    QByteArray serviceType = fqName.mid(index + 1);

    // Immediately return if a PTR record does not exist
    Record ptrRecord;
    if (!cache->lookupRecord(serviceType, PTR, ptrRecord)) {
        return false;
    }

    // If a SRV record is missing, query for it (by returning true)
    Record srvRecord;
    if (!cache->lookupRecord(fqName, SRV, srvRecord)) {
        return true;
    }

    Service service;
    service.setName(serviceName);
    service.setType(serviceType);
    service.setHostname(srvRecord.target());
    service.setPort(srvRecord.port());

    // If TXT records are available for the service, add their values
    QList<Record> txtRecords;
    if (cache->lookupRecords(fqName, TXT, txtRecords)) {
        QMap<QByteArray, QByteArray> attributes;
        foreach (Record record, txtRecords) {
            for (auto i = record.attributes().constBegin();
                    i != record.attributes().constEnd(); ++i) {
                attributes.insert(i.key(), i.value());
            }
        }
        service.setAttributes(attributes);
    }

    // If the service existed, this is an update; otherwise it is a new
    // addition; emit the appropriate signal
    if (!services.contains(fqName)) {
        emit q->serviceAdded(service);
    } else if(services.value(fqName) != service) {
        emit q->serviceUpdated(service);
    }

    services.insert(fqName, service);

    return false;
}

void BrowserPrivate::onMessageReceived(const Message &message)
{
    if (!message.isResponse()) {
        return;
    }

    // Use a set to track all services that are updated in the message - this
    // avoids extraneous signals being emitted if SRV and TXT are provided
    QSet<QByteArray> updateNames;
    foreach (Record record, message.records()) {
        bool any = type == MdnsBrowseType;
        if (record.type() == PTR && record.name() == MdnsBrowseType) {
            cache->addRecord(record);
            ptrTargets.insert(record.target());
            serviceTimer.stop();
            serviceTimer.start();
        } else if ((record.type() == PTR && (any || record.name() == type)) ||
                (record.type() == SRV && (any || record.name().endsWith("." + type))) ||
                (record.type() == TXT && (any || record.name().endsWith("." + type)))) {
            cache->addRecord(record);
            switch (record.type()) {
            case PTR:
                updateNames.insert(record.target());
                break;
            case SRV:
            case TXT:
                updateNames.insert(record.name());
                break;
            }
        }
    }

    // For each of the services marked to be updated, perform the update and
    // make a list of all missing SRV records
    QSet<QByteArray> queryNames;
    foreach (QByteArray name, updateNames) {
        if (updateService(name)) {
            queryNames.insert(name);
        }
    }

    // Build and send a query for all of the SRV records
    if (queryNames.count()) {
        Message queryMessage;
        foreach (QByteArray name, queryNames) {
            Query query;
            query.setName(name);
            query.setType(SRV);
            queryMessage.addQuery(query);
            query.setType(TXT);
            queryMessage.addQuery(query);
        }
        server->sendMessageToAll(queryMessage);
    }
}

void BrowserPrivate::onShouldQuery(const Record &record)
{
    // Assume that all messages in the cache are still in use (by the browser)
    // and attempt to renew them immediately

    Query query;
    query.setName(record.name());
    query.setType(record.type());
    Message message;
    message.addQuery(query);
    server->sendMessageToAll(message);
}

void BrowserPrivate::onRecordExpired(const Record &record)
{
    // If the PTR or SRV record has expired for a service, then it must be
    // removed - TXT records on the other hand, cause an update

    QByteArray serviceName;
    switch (record.type()) {
    case PTR:
        serviceName = record.target();
        break;
    case SRV:
        serviceName = record.name();
        break;
    case TXT:
        updateService(record.name());
        return;
    default:
        return;
    }
    Service service = services.value(serviceName);
    if (!service.name().isNull()) {
        emit q->serviceRemoved(service);
        services.remove(serviceName);
    }
}

void BrowserPrivate::onQueryTimeout()
{
    Query query;
    query.setName(type);
    query.setType(PTR);
    Message message;
    message.addQuery(query);

    // TODO: including too many records could cause problems

    // Include all currently valid PTR records
    QList<Record> records;
    if (cache->lookupRecords(QByteArray(), PTR, records)) {
        foreach (Record record, records) {
            message.addRecord(record);
        }
    }

    server->sendMessageToAll(message);
    queryTimer.start();
}

void BrowserPrivate::onServiceTimeout()
{
    if (ptrTargets.count()) {
        Message message;
        foreach (QByteArray target, ptrTargets) {

            // Add a query for PTR records
            Query query;
            query.setName(target);
            query.setType(PTR);
            message.addQuery(query);

            // Include PTR records for the target that are already known
            QList<Record> records;
            if (cache->lookupRecords(target, PTR, records)) {
                foreach (Record record, records) {
                    message.addRecord(record);
                }
            }
        }

        server->sendMessageToAll(message);
        ptrTargets.clear();
    }
}

Browser::Browser(AbstractServer *server, const QByteArray &type, Cache *cache, QObject *parent)
    : QObject(parent),
      d(new BrowserPrivate(this, server, type, cache))
{
}
<|endoftext|>


<commit_before>#include "ssw_aligner.hpp"

namespace vg {

void SSWAligner::PrintAlignment(const StripedSmithWaterman::Alignment& alignment){
  cout << "===== SSW result =====" << endl;
  cout << "Best Smith-Waterman score:\t" << alignment.sw_score << endl
       << "Next-best Smith-Waterman score:\t" << alignment.sw_score_next_best << endl
       << "Reference start:\t" << alignment.ref_begin << endl
       << "Reference end:\t" << alignment.ref_end << endl
       << "Query start:\t" << alignment.query_begin << endl
       << "Query end:\t" << alignment.query_end << endl
       << "Next-best reference end:\t" << alignment.ref_end_next_best << endl
       << "Number of mismatches:\t" << alignment.mismatches << endl
       << "Cigar: " << alignment.cigar_string << endl;
  cout << "======================" << endl;
}

Alignment SSWAligner::align(const string& query, const string& ref) {
    StripedSmithWaterman::Aligner aligner(match,
                                          mismatch,
                                          gap_open,
                                          gap_extension);
    StripedSmithWaterman::Filter filter;
    StripedSmithWaterman::Alignment alignment;
    aligner.Align(query.c_str(), ref.c_str(), ref.size(), filter, &alignment);
    return ssw_to_vg(alignment, query, ref);
}

Alignment SSWAligner::ssw_to_vg(const StripedSmithWaterman::Alignment& ssw_aln,
                                const string& query, const string& ref) {

    int from_pos = ssw_aln.ref_begin;
    int to_pos = 0;

    auto& to_seq = query;
    auto& from_seq = ref;

    Alignment vg_aln;
    Path* path = vg_aln.mutable_path();

    Mapping* mapping = path->add_mapping();
    mapping->mutable_position()->set_offset(from_pos);

    for (auto& elem : vcflib::splitCigar(ssw_aln.cigar_string)) {
        int32_t length = elem.first;
        string type = elem.second;
        Edit* edit;
        //cerr << e->length << e->type << endl;
        switch (type[0]) {
        case 'M':
        case 'X':
        case 'N': {
            // do the sequences match?
            // emit a stream of "SNPs" and matches
            int h = from_pos;
            int last_start = from_pos;
            int k = to_pos;
            for ( ; h < from_pos + length; ++h, ++k) {
                //cerr << h << ":" << k << " " << from_seq[h] << " " << to_seq[k] << endl;
                if (from_seq[h] != to_seq[k]) {
                    // emit the last "match" region
                    if (h-last_start > 0) {
                        edit = mapping->add_edit();
                        edit->set_from_length(h-last_start);
                        edit->set_to_length(h-last_start);
                    }
                    // set up the SNP
                    edit = mapping->add_edit();
                    edit->set_from_length(1);
                    edit->set_to_length(1);
                    edit->set_sequence(to_seq.substr(k,1));
                    last_start = h+1;
                }
            }
            // handles the match at the end or the case of no SNP
            if (h-last_start > 0) {
                edit = mapping->add_edit();
                edit->set_from_length(h-last_start);
                edit->set_to_length(h-last_start);
            }
            to_pos += length;
            from_pos += length;
        } break;
        case 'D':
            edit = mapping->add_edit();
            edit->set_from_length(length);
            edit->set_to_length(0);
            from_pos += length;
            break;
        case 'I':
            edit = mapping->add_edit();
            edit->set_from_length(0);
            edit->set_to_length(length);
            edit->set_sequence(to_seq.substr(to_pos, length));
            to_pos += length;
            break;
        case 'S':
            // note that soft clips and insertions are semantically equivalent
            // and can only be differentiated by their position in the read
            // with soft clips coming at the start or end
            edit = mapping->add_edit();
            edit->set_from_length(0);
            edit->set_to_length(length);
            edit->set_sequence(to_seq.substr(to_pos, length));
            to_pos += length;
            break;
        default:
            cerr << "error [GSSWAligner::gssw_mapping_to_alignment] "
                 << "unsupported cigar op type " << type << endl;
            exit(1);
            break;

        }

    }

    // set identity
    vg_aln.set_identity(identity(vg_aln.path()));

    // set score
    vg_aln.set_score(ssw_aln.sw_score);

    return vg_aln;

}

}
<commit_msg>fix for '=' cigar support sign.<commit_after>#include "ssw_aligner.hpp"

namespace vg {

void SSWAligner::PrintAlignment(const StripedSmithWaterman::Alignment& alignment){
  cout << "===== SSW result =====" << endl;
  cout << "Best Smith-Waterman score:\t" << alignment.sw_score << endl
       << "Next-best Smith-Waterman score:\t" << alignment.sw_score_next_best << endl
       << "Reference start:\t" << alignment.ref_begin << endl
       << "Reference end:\t" << alignment.ref_end << endl
       << "Query start:\t" << alignment.query_begin << endl
       << "Query end:\t" << alignment.query_end << endl
       << "Next-best reference end:\t" << alignment.ref_end_next_best << endl
       << "Number of mismatches:\t" << alignment.mismatches << endl
       << "Cigar: " << alignment.cigar_string << endl;
  cout << "======================" << endl;
}

Alignment SSWAligner::align(const string& query, const string& ref) {
    StripedSmithWaterman::Aligner aligner(match,
                                          mismatch,
                                          gap_open,
                                          gap_extension);
    StripedSmithWaterman::Filter filter;
    StripedSmithWaterman::Alignment alignment;
    aligner.Align(query.c_str(), ref.c_str(), ref.size(), filter, &alignment);
    return ssw_to_vg(alignment, query, ref);
}

Alignment SSWAligner::ssw_to_vg(const StripedSmithWaterman::Alignment& ssw_aln,
                                const string& query, const string& ref) {

    int from_pos = ssw_aln.ref_begin;
    int to_pos = 0;

    auto& to_seq = query;
    auto& from_seq = ref;

    Alignment vg_aln;
    Path* path = vg_aln.mutable_path();

    Mapping* mapping = path->add_mapping();
    mapping->mutable_position()->set_offset(from_pos);

    for (auto& elem : vcflib::splitCigar(ssw_aln.cigar_string)) {
        int32_t length = elem.first;
        string type = elem.second;
        Edit* edit;
        //cerr << e->length << e->type << endl;
        switch (type[0]) {
	case '=':
        case 'M':
        case 'X':
        case 'N': {
            // do the sequences match?
            // emit a stream of "SNPs" and matches
            int h = from_pos;
            int last_start = from_pos;
            int k = to_pos;
            for ( ; h < from_pos + length; ++h, ++k) {
                //cerr << h << ":" << k << " " << from_seq[h] << " " << to_seq[k] << endl;
                if (from_seq[h] != to_seq[k]) {
                    // emit the last "match" region
                    if (h-last_start > 0) {
                        edit = mapping->add_edit();
                        edit->set_from_length(h-last_start);
                        edit->set_to_length(h-last_start);
                    }
                    // set up the SNP
                    edit = mapping->add_edit();
                    edit->set_from_length(1);
                    edit->set_to_length(1);
                    edit->set_sequence(to_seq.substr(k,1));
                    last_start = h+1;
                }
            }
            // handles the match at the end or the case of no SNP
            if (h-last_start > 0) {
                edit = mapping->add_edit();
                edit->set_from_length(h-last_start);
                edit->set_to_length(h-last_start);
            }
            to_pos += length;
            from_pos += length;
        } break;
        case 'D':
            edit = mapping->add_edit();
            edit->set_from_length(length);
            edit->set_to_length(0);
            from_pos += length;
            break;
        case 'I':
            edit = mapping->add_edit();
            edit->set_from_length(0);
            edit->set_to_length(length);
            edit->set_sequence(to_seq.substr(to_pos, length));
            to_pos += length;
            break;
        case 'S':
            // note that soft clips and insertions are semantically equivalent
            // and can only be differentiated by their position in the read
            // with soft clips coming at the start or end
            edit = mapping->add_edit();
            edit->set_from_length(0);
            edit->set_to_length(length);
            edit->set_sequence(to_seq.substr(to_pos, length));
            to_pos += length;
            break;
        default:
            cerr << "error [GSSWAligner::gssw_mapping_to_alignment] "
                 << "unsupported cigar op type " << type << endl;
            exit(1);
            break;

        }

    }

    // set identity
    vg_aln.set_identity(identity(vg_aln.path()));

    // set score
    vg_aln.set_score(ssw_aln.sw_score);

    return vg_aln;

}

}
<|endoftext|>


<commit_before>#include "Robot.hpp"
#include <iostream>
#include <smurf/Smurf.hpp>
#include <envire_core/items/Transform.hpp>
#include <base/Time.hpp>

void envire::envire_smurf::Robot::welcome()
{
    std::cout << "You successfully compiled and executed the envire_smurf Project. Welcome!" << std::endl;
}

void envire::envire_smurf::Robot::loadFromSmurf(envire::core::TransformGraph &graph, const std::string& path)
{
  // We want to be able to verify that every frame defined is connected through
  //some tranformation. That's why all the frames are included first
    smurf::Robot robot;
    robot.loadFromSmurf(path);
    // Frames
    std::vector<smurf::Frame *> frames= robot.getFrames();
    std::cout << "Iterate over the frames:" << std::endl;
    for(std::vector<smurf::Frame *>::iterator it = frames.begin(); it != frames.end(); ++it) {
        base::Time time = base::Time::now();
        base::TransformWithCovariance tf_cov;
        envire::core::Transform envire_tf(time, tf_cov);
        std::cout << "Include the following frame in the graph: " << (*it)->getName() << std::endl;
        // Make sure this method works
        //graph.addFrame(frame->getName());
        //
        // By now we need: objects in that frame and type: link, joint (with
        // type) and sensor. This information goes in the config map of the
        // envire item
        //
        // Add an Item ConfigMap with this information to the frame
        //
        // Fill configMap with the node information and add it to the frame
    }
    // Static Transformations: All transformations are considered static initially
    std::vector<smurf::StaticTransformation *> staticTfs= robot.getStaticTransforms();
    std::cout << " Static transformations " << std::endl;
    for(std::vector<smurf::StaticTransformation *>::iterator it = staticTfs.begin(); it != staticTfs.end(); ++it) {
        smurf::Frame source = (*it) -> getSourceFrame();
        envire::core::FrameId sourceId = source.getName();
        smurf::Frame target = (*it) -> getTargetFrame();
        envire::core::FrameId targetId = target.getName();
        Eigen::Affine3d tf_smurf = (*it) -> getTransformation();
        std::cout << "Transformation from " << sourceId <<" to " << targetId << " is " << tf_smurf.matrix() << std::endl;
        base::Time time = base::Time::now();
        base::TransformWithCovariance tf_cov(tf_smurf);
        envire::core::Transform envire_tf(time, tf_cov);
        graph.addTransform(sourceId, targetId, envire_tf);
    }
}
<commit_msg>visuals and collison of link are in the graph now<commit_after>#include "Robot.hpp"
#include <iostream>
#include <smurf/Smurf.hpp>
#include <envire_core/items/Transform.hpp>
#include <base/Time.hpp>
#include <envire_core/items/Item.hpp>

void envire::envire_smurf::Robot::welcome()
{
    std::cout << "You successfully compiled and executed the envire_smurf Project. Welcome!" << std::endl;
}

void envire::envire_smurf::Robot::loadFromSmurf(envire::core::TransformGraph &graph, const std::string& path)
{
  // We want to be able to verify that every frame defined is connected through
  //some tranformation. That's why all the frames are included first
    smurf::Robot robot;
    robot.loadFromSmurf(path);
    // Frames
    std::vector<smurf::Frame *> frames= robot.getFrames();
    std::cout << "Iterate over the frames:" << std::endl;
    for(std::vector<smurf::Frame *>::iterator it = frames.begin(); it != frames.end(); ++it) {
//        base::Time time = base::Time::now();
//        base::TransformWithCovariance tf_cov;
//        envire::core::Transform envire_tf(time, tf_cov);
//        std::cout << "Include the following frame in the graph: " << (*it)->getName() << std::endl;
        // Make sure this method works
        //graph.addFrame(frame->getName());
        //
        // By now we need: objects in that frame and type: link, joint (with
        // type) and sensor. This information goes in the config map of the
        // envire item
        //
        // Add an Item ConfigMap with this information to the frame
        //
        // Fill configMap with the node information and add it to the frame

        std::string frame_id = (*it)->getName();
        graph.addFrame(frame_id);

//////////////////////////////////////////////adding smurf collisions//////////////////////////////////////
        std::vector<smurf::Collidable> frame_collisons= (*it)->getCollisionObjects();
        boost::shared_ptr<envire::core::Item<std::vector<smurf::Collidable> > >collisons_itemPtr (new  envire::core::Item<std::vector<smurf::Collidable> > );
        collisons_itemPtr-> setData(frame_collisons);
        graph.addItemToFrame(frame_id, collisons_itemPtr);
//////////////////////////////////////////////adding smurf visuals//////////////////////////////////////
        std::vector<smurf::Visual> frame_visuals= (*it)->getgetVisuals();
        boost::shared_ptr<envire::core::Item<std::vector<smurf::Visual> > >visuals_itemPtr (new  envire::core::Item<std::vector<smurf::Visual> > );
        visuals_itemPtr-> setData(frame_visuals);
        graph.addItemToFrame(frame_id, visuals_itemPtr);

    }
    // Static Transformations: All transformations are considered static initially
    std::vector<smurf::StaticTransformation *> staticTfs= robot.getStaticTransforms();
    std::cout << " Static transformations " << std::endl;
    for(std::vector<smurf::StaticTransformation *>::iterator it = staticTfs.begin(); it != staticTfs.end(); ++it) {
        smurf::Frame source = (*it) -> getSourceFrame();
        envire::core::FrameId sourceId = source.getName();
        smurf::Frame target = (*it) -> getTargetFrame();
        envire::core::FrameId targetId = target.getName();
        Eigen::Affine3d tf_smurf = (*it) -> getTransformation();
        std::cout << "Transformation from " << sourceId <<" to " << targetId << " is " << tf_smurf.matrix() << std::endl;
        base::Time time = base::Time::now();
        base::TransformWithCovariance tf_cov(tf_smurf);
        envire::core::Transform envire_tf(time, tf_cov);
        graph.addTransform(sourceId, targetId, envire_tf);
    }
}
<|endoftext|>