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

#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _UCBHELPER_MACROS_HXX
#include <ucbhelper/macros.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_
#include <com/sun/star/uno/XInterface.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_
#include <com/sun/star/io/XSeekable.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XTRUNCATE_HPP_
#include <com/sun/star/io/XTruncate.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_
#include <com/sun/star/io/XStream.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENTPROVIDER_HPP_
#include <com/sun/star/ucb/XContentProvider.hpp>
#endif

namespace fileaccess {

    // forward:
    class shell;
    class XInputStreamForStream;
    class XOutputStreamForStream;

    class XStream_impl
        : public cppu::OWeakObject,
          public com::sun::star::lang::XTypeProvider,
          public com::sun::star::lang::XServiceInfo,
          public com::sun::star::io::XStream,
          public com::sun::star::io::XSeekable,
          public com::sun::star::io::XInputStream,
          public com::sun::star::io::XOutputStream,
          public com::sun::star::io::XTruncate
    {
        friend class XInputStreamForStream;
        friend class XOutputStreamForStream;

    public:

        XStream_impl( shell* pMyShell,const rtl::OUString& aUncPath );

        /**
         *  Returns an error code as given by filerror.hxx
         */

        sal_Int32 SAL_CALL CtorSuccess();
        sal_Int32 SAL_CALL getMinorError();

        virtual ~XStream_impl();

        // OWeakObject

        virtual com::sun::star::uno::Any SAL_CALL
        queryInterface(
            const com::sun::star::uno::Type& rType )
            throw( com::sun::star::uno::RuntimeException);

        virtual void SAL_CALL
        acquire(
            void )
            throw();

        virtual void SAL_CALL
        release(
            void )
            throw();

        // XTypeProvider

        XTYPEPROVIDER_DECL()

        // XServiceInfo
        virtual rtl::OUString SAL_CALL
        getImplementationName()
            throw( com::sun::star::uno::RuntimeException);

        virtual sal_Bool SAL_CALL
        supportsService( const rtl::OUString& ServiceName )
            throw( com::sun::star::uno::RuntimeException);

        virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL
        getSupportedServiceNames()
            throw( com::sun::star::uno::RuntimeException );

        // XStream

        virtual com::sun::star::uno::Reference< com::sun::star::io::XInputStream > SAL_CALL
        getInputStream(  )
            throw( com::sun::star::uno::RuntimeException );

        virtual com::sun::star::uno::Reference< com::sun::star::io::XOutputStream > SAL_CALL
        getOutputStream(  )
            throw( com::sun::star::uno::RuntimeException );

        // XTruncate

        virtual void SAL_CALL truncate( void )
            throw( com::sun::star::io::IOException,
                   com::sun::star::uno::RuntimeException );

        // XInputStream

        sal_Int32 SAL_CALL
        readBytes(
            com::sun::star::uno::Sequence< sal_Int8 >& aData,
            sal_Int32 nBytesToRead )
            throw( com::sun::star::io::NotConnectedException,
                   com::sun::star::io::BufferSizeExceededException,
                   com::sun::star::io::IOException,
                   com::sun::star::uno::RuntimeException);

        sal_Int32 SAL_CALL
        readSomeBytes(
            com::sun::star::uno::Sequence< sal_Int8 >& aData,
            sal_Int32 nMaxBytesToRead )
            throw( com::sun::star::io::NotConnectedException,
                   com::sun::star::io::BufferSizeExceededException,
                   com::sun::star::io::IOException,
                   com::sun::star::uno::RuntimeException);

        void SAL_CALL
        skipBytes(
            sal_Int32 nBytesToSkip )
            throw( com::sun::star::io::NotConnectedException,
                   com::sun::star::io::BufferSizeExceededException,
                   com::sun::star::io::IOException,
                   com::sun::star::uno::RuntimeException );

        sal_Int32 SAL_CALL
        available(
            void )
            throw( com::sun::star::io::NotConnectedException,
                   com::sun::star::io::IOException,
                   com::sun::star::uno::RuntimeException );

        void SAL_CALL
        closeInput(
            void )
            throw( com::sun::star::io::NotConnectedException,
                   com::sun::star::io::IOException,
                   com::sun::star::uno::RuntimeException );

        // XSeekable

        void SAL_CALL
        seek(
            sal_Int64 location )
            throw( com::sun::star::lang::IllegalArgumentException,
                   com::sun::star::io::IOException,
                   com::sun::star::uno::RuntimeException );

        sal_Int64 SAL_CALL
        getPosition(
            void )
            throw( com::sun::star::io::IOException,
                   com::sun::star::uno::RuntimeException );

        sal_Int64 SAL_CALL
        getLength(
            void )
            throw( com::sun::star::io::IOException,
                   com::sun::star::uno::RuntimeException );

        // XOutputStream

        void SAL_CALL
        writeBytes( const com::sun::star::uno::Sequence< sal_Int8 >& aData )
            throw( com::sun::star::io::NotConnectedException,
                   com::sun::star::io::BufferSizeExceededException,
                   com::sun::star::io::IOException,
                   com::sun::star::uno::RuntimeException);

        void SAL_CALL
        flush()
            throw( com::sun::star::io::NotConnectedException,
                   com::sun::star::io::BufferSizeExceededException,
                   com::sun::star::io::IOException,
                   com::sun::star::uno::RuntimeException);

        void SAL_CALL
        closeOutput(
            void )
            throw( com::sun::star::io::NotConnectedException,
                   com::sun::star::io::IOException,
                   com::sun::star::uno::RuntimeException );

    private:

        osl::Mutex   m_aMutex;
        bool         m_bInputStreamCalled,m_bOutputStreamCalled;

        shell*       m_pMyShell;
        com::sun::star::uno::Reference< com::sun::star::ucb::XContentProvider > m_xProvider;
        sal_Bool     m_nIsOpen;
        osl::File    m_aFile;

        sal_Int32                                          m_nErrorCode;
        sal_Int32                                          m_nMinorErrorCode;

        // Implementation methods

        void SAL_CALL
        closeStream(
            void )
            throw( com::sun::star::io::NotConnectedException,
                   com::sun::star::io::IOException,
                   com::sun::star::uno::RuntimeException );

    };

}  // end namespace XStream_impl

#endif
<commit_msg>INTEGRATION: CWS sb27 (1.7.8); FILE MERGED 2004/12/03 15:17:24 sb 1.7.8.1: #i38298# Use XJob.execute as a hack replacement for the expensive, recent implementation of fileaccess::XStream_impl::flush.<commit_after> /*************************************************************************
 *
 *  $RCSfile: filstr.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2004-12-07 10:52:52 $
 *
 *  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 _FILSTR_HXX_
#define _FILSTR_HXX_

#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _UCBHELPER_MACROS_HXX
#include <ucbhelper/macros.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_
#include <com/sun/star/uno/XInterface.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_
#include <com/sun/star/io/XSeekable.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XTRUNCATE_HPP_
#include <com/sun/star/io/XTruncate.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_
#include <com/sun/star/io/XStream.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENTPROVIDER_HPP_
#include <com/sun/star/ucb/XContentProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XJOB_HPP_ //HACK see #i38298#
#include "com/sun/star/task/XJob.hpp"
#endif

namespace fileaccess {

    // forward:
    class shell;
    class XInputStreamForStream;
    class XOutputStreamForStream;

    class XStream_impl
        : public cppu::OWeakObject,
          public com::sun::star::lang::XTypeProvider,
          public com::sun::star::lang::XServiceInfo,
          public com::sun::star::io::XStream,
          public com::sun::star::io::XSeekable,
          public com::sun::star::io::XInputStream,
          public com::sun::star::io::XOutputStream,
          public com::sun::star::io::XTruncate,
          public com::sun::star::task::XJob //HACK see #i38298#
    {
        friend class XInputStreamForStream;
        friend class XOutputStreamForStream;

    public:

        XStream_impl( shell* pMyShell,const rtl::OUString& aUncPath );

        /**
         *  Returns an error code as given by filerror.hxx
         */

        sal_Int32 SAL_CALL CtorSuccess();
        sal_Int32 SAL_CALL getMinorError();

        virtual ~XStream_impl();

        // OWeakObject

        virtual com::sun::star::uno::Any SAL_CALL
        queryInterface(
            const com::sun::star::uno::Type& rType )
            throw( com::sun::star::uno::RuntimeException);

        virtual void SAL_CALL
        acquire(
            void )
            throw();

        virtual void SAL_CALL
        release(
            void )
            throw();

        // XTypeProvider

        XTYPEPROVIDER_DECL()

        // XServiceInfo
        virtual rtl::OUString SAL_CALL
        getImplementationName()
            throw( com::sun::star::uno::RuntimeException);

        virtual sal_Bool SAL_CALL
        supportsService( const rtl::OUString& ServiceName )
            throw( com::sun::star::uno::RuntimeException);

        virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL
        getSupportedServiceNames()
            throw( com::sun::star::uno::RuntimeException );

        // XStream

        virtual com::sun::star::uno::Reference< com::sun::star::io::XInputStream > SAL_CALL
        getInputStream(  )
            throw( com::sun::star::uno::RuntimeException );

        virtual com::sun::star::uno::Reference< com::sun::star::io::XOutputStream > SAL_CALL
        getOutputStream(  )
            throw( com::sun::star::uno::RuntimeException );

        // XTruncate

        virtual void SAL_CALL truncate( void )
            throw( com::sun::star::io::IOException,
                   com::sun::star::uno::RuntimeException );

        // XInputStream

        sal_Int32 SAL_CALL
        readBytes(
            com::sun::star::uno::Sequence< sal_Int8 >& aData,
            sal_Int32 nBytesToRead )
            throw( com::sun::star::io::NotConnectedException,
                   com::sun::star::io::BufferSizeExceededException,
                   com::sun::star::io::IOException,
                   com::sun::star::uno::RuntimeException);

        sal_Int32 SAL_CALL
        readSomeBytes(
            com::sun::star::uno::Sequence< sal_Int8 >& aData,
            sal_Int32 nMaxBytesToRead )
            throw( com::sun::star::io::NotConnectedException,
                   com::sun::star::io::BufferSizeExceededException,
                   com::sun::star::io::IOException,
                   com::sun::star::uno::RuntimeException);

        void SAL_CALL
        skipBytes(
            sal_Int32 nBytesToSkip )
            throw( com::sun::star::io::NotConnectedException,
                   com::sun::star::io::BufferSizeExceededException,
                   com::sun::star::io::IOException,
                   com::sun::star::uno::RuntimeException );

        sal_Int32 SAL_CALL
        available(
            void )
            throw( com::sun::star::io::NotConnectedException,
                   com::sun::star::io::IOException,
                   com::sun::star::uno::RuntimeException );

        void SAL_CALL
        closeInput(
            void )
            throw( com::sun::star::io::NotConnectedException,
                   com::sun::star::io::IOException,
                   com::sun::star::uno::RuntimeException );

        // XSeekable

        void SAL_CALL
        seek(
            sal_Int64 location )
            throw( com::sun::star::lang::IllegalArgumentException,
                   com::sun::star::io::IOException,
                   com::sun::star::uno::RuntimeException );

        sal_Int64 SAL_CALL
        getPosition(
            void )
            throw( com::sun::star::io::IOException,
                   com::sun::star::uno::RuntimeException );

        sal_Int64 SAL_CALL
        getLength(
            void )
            throw( com::sun::star::io::IOException,
                   com::sun::star::uno::RuntimeException );

        // XOutputStream

        void SAL_CALL
        writeBytes( const com::sun::star::uno::Sequence< sal_Int8 >& aData )
            throw( com::sun::star::io::NotConnectedException,
                   com::sun::star::io::BufferSizeExceededException,
                   com::sun::star::io::IOException,
                   com::sun::star::uno::RuntimeException);

        void SAL_CALL
        flush()
            throw( com::sun::star::io::NotConnectedException,
                   com::sun::star::io::BufferSizeExceededException,
                   com::sun::star::io::IOException,
                   com::sun::star::uno::RuntimeException);

        void SAL_CALL
        closeOutput(
            void )
            throw( com::sun::star::io::NotConnectedException,
                   com::sun::star::io::IOException,
                   com::sun::star::uno::RuntimeException );

        //HACK see #i38298#
        virtual com::sun::star::uno::Any SAL_CALL execute(
            com::sun::star::uno::Sequence< com::sun::star::beans::NamedValue >
            const &)
            throw (
                com::sun::star::lang::IllegalArgumentException,
                com::sun::star::uno::Exception,
                com::sun::star::uno::RuntimeException);

    private:

        osl::Mutex   m_aMutex;
        bool         m_bInputStreamCalled,m_bOutputStreamCalled;

        shell*       m_pMyShell;
        com::sun::star::uno::Reference< com::sun::star::ucb::XContentProvider > m_xProvider;
        sal_Bool     m_nIsOpen;
        osl::File    m_aFile;

        sal_Int32                                          m_nErrorCode;
        sal_Int32                                          m_nMinorErrorCode;

        // Implementation methods

        void SAL_CALL
        closeStream(
            void )
            throw( com::sun::star::io::NotConnectedException,
                   com::sun::star::io::IOException,
                   com::sun::star::uno::RuntimeException );

    };

}  // end namespace XStream_impl

#endif
<|endoftext|>


<commit_before>#ifndef LIB_VECTOR2D_HPP
#define LIB_VECTOR2D_HPP

namespace lib
{
	template <typename T>
	class vector2d
	{
	public:

		vector2d() : x{}, y{} {}
		vector2d(T X, T Y) : x{ X }, y{ Y } {}

		template <typename U>
		explicit vector2d(const vector2d<U>& vector) : x{ static_cast<T>(vector.x) }, y{ static_cast<T>(vector.y) } {}

		vector2d operator-() { return vector2d{-x,-y} }
		vector2d &operator+=(const vector2d &right)
		{
			x += right.x;
			y += right.y;
			return *this;
		}

		vector2d &operator-=(const vector2d &right)
		{
			x -= right.x;
			y -= right.y;
			return *this;
		}

		vector2d &operator*=(const vector2d &right)
		{
			x *= right.x;
			y *= right.y;
			return *this;
		}

		vector2d &operator/=(const vector2d &right)
		{
			x /= right.x;
			y /= right.y;
			return *this;
		}

		vector2d &operator*=(const T &right)
		{
			x *= right;
			y *= right;
			return *this;
		}

		vector2d &operator/=(const T &right)
		{
			x /= right;
			y /= right;
			return *this;
		}

		vector2d operator+(const vector2d &right) const
		{
			return (vector2d{ *this } += right);
		}

		vector2d operator-(const vector2d &right) const
		{
			return (vector2d{ *this } -= right);
		}

		vector2d operator*(const vector2d &right) const
		{
			return (vector2d{ *this } *= right);
		}
		vector2d operator/(const vector2d &right) const
		{
			return (vector2d{ *this } /= right);
		}

		vector2d operator*(const T &right) const
		{
			return (vector2d{ *this } *= right);
		}

		vector2d operator/(const T &right) const
		{
			return (vector2d{ *this } /= right);
		}

		bool operator ==(const vector2d &right) const
		{
			return (x == right.x && y == right.y);
		}

		bool operator !=(const vector2d &right) const
		{
			return !(*this == right);
		}

		T x;
		T y;
	};

	using vector2du32 = vector2d<u32>;
	using vector2ds32 = vector2d<s32>;
	using vector2df = vector2d<f32>;
	using vector2du8 = vector2d<u8>;
	using vector2ds8 = vector2d<s8>;

}

#endif
<commit_msg>Move and copy added<commit_after>#ifndef LIB_VECTOR2D_HPP
#define LIB_VECTOR2D_HPP

namespace lib
{
	template <typename T>
	class vector2d
	{
	public:

		vector2d() : x{}, y{} {}
		vector2d(T X, T Y) : x{ X }, y{ Y } {}
		vector2d(const vector2d<T> &) = default;
		vector2d(vector2d &&v) : x{ std::move(v.x) }, y{ std::move(v.y) } {}
		vector2d &operator=(const vector2d<T> &) = default;
		vector2d &operator=(vector2d<T> &&v) { x = std::move(v.x); y = std::move(v.y); return *this; }

		template <typename U>
		explicit vector2d(const vector2d<U>& vector) : x{ static_cast<T>(vector.x) }, y{ static_cast<T>(vector.y) } {}

		vector2d operator-() { return vector2d{-x,-y} }
		vector2d &operator+=(const vector2d &right)
		{
			x += right.x;
			y += right.y;
			return *this;
		}

		vector2d &operator-=(const vector2d &right)
		{
			x -= right.x;
			y -= right.y;
			return *this;
		}

		vector2d &operator*=(const vector2d &right)
		{
			x *= right.x;
			y *= right.y;
			return *this;
		}

		vector2d &operator/=(const vector2d &right)
		{
			x /= right.x;
			y /= right.y;
			return *this;
		}

		vector2d &operator*=(const T &right)
		{
			x *= right;
			y *= right;
			return *this;
		}

		vector2d &operator/=(const T &right)
		{
			x /= right;
			y /= right;
			return *this;
		}

		vector2d operator+(const vector2d &right) const
		{
			return (vector2d{ *this } += right);
		}

		vector2d operator-(const vector2d &right) const
		{
			return (vector2d{ *this } -= right);
		}

		vector2d operator*(const vector2d &right) const
		{
			return (vector2d{ *this } *= right);
		}
		vector2d operator/(const vector2d &right) const
		{
			return (vector2d{ *this } /= right);
		}

		vector2d operator*(const T &right) const
		{
			return (vector2d{ *this } *= right);
		}

		vector2d operator/(const T &right) const
		{
			return (vector2d{ *this } /= right);
		}

		bool operator ==(const vector2d &right) const
		{
			return (x == right.x && y == right.y);
		}

		bool operator !=(const vector2d &right) const
		{
			return !(*this == right);
		}

		T x;
		T y;
	};

	using vector2du32 = vector2d<u32>;
	using vector2ds32 = vector2d<s32>;
	using vector2df = vector2d<f32>;
	using vector2du8 = vector2d<u8>;
	using vector2ds8 = vector2d<s8>;

}

#endif
<|endoftext|>


<commit_before>#include <QtTest/QtTest>
#include <iostream>

#define MD_PRINT_TREE_MAX_NODES 2 // set a define before the include
#include <TreeDS/tree>

using namespace md;

class DebugTest : public QObject {

    Q_OBJECT

    private slots:
    void test() {
        nary_tree<char> t {
            n('a')(
                n('b'),
                n('c')(
                    n('d'),
                    n('e'),
                    n('f'),
                    n('g'),
                    n('h'),
                    n('i'),
                    n('j'),
                    n('k'),
                    n('l')),
                n('m'),
                n('n'))};
        std::cout << t << std::endl;
    }
};

QTEST_MAIN(DebugTest);
#include "DebugTest.moc"
<commit_msg>Fix previous commit<commit_after><|endoftext|>


<commit_before>/*
**
** Author(s):
**  - Cedric GESTES <gestes@aldebaran-robotics.com>
**
** Copyright (C) 2013 Aldebaran Robotics
*/

#include "pyservicedirectory.hpp"
#include <qimessaging/servicedirectory.hpp>
#include <boost/python.hpp>
#include "pyfuture.hpp"
#include "gil.hpp"
qiLogCategory("qimpy");

namespace qi {
  namespace py {

    class PyServiceDirectory : public qi::ServiceDirectory
    {
    public:
      //return a future, or None (and throw in case of error)
      boost::python::object listen(const std::string &url, bool _async=false) {
        GILScopedUnlock _unlock;
        return toPyFutureAsync(ServiceDirectory::listen(url), _async);
      }

      //override because python do not know qi::Url
      boost::python::list endpoints() const {
        boost::python::list ret;
        std::vector<qi::Url>     eps = ServiceDirectory::endpoints();
        for (unsigned int i = 0; i < eps.size(); ++i) {
          ret.append(eps.at(i).str());
        }
        return ret;
      }

    };

    void export_pyservicedirectory() {
      boost::python::class_<PyServiceDirectory>("ServiceDirectory")
          .def("listen", &PyServiceDirectory::listen, (boost::python::arg("url"), boost::python::arg("_async") = false))
          .def("setIdentity", &PyServiceDirectory::setIdentity)
          .def("close", &PyServiceDirectory::close)
          .def("endpoints", &PyServiceDirectory::endpoints);
    }

  }
}
<commit_msg>python: servicedirectory: unlock only the needed section<commit_after>/*
**
** Author(s):
**  - Cedric GESTES <gestes@aldebaran-robotics.com>
**
** Copyright (C) 2013 Aldebaran Robotics
*/

#include "pyservicedirectory.hpp"
#include <qimessaging/servicedirectory.hpp>
#include <boost/python.hpp>
#include "pyfuture.hpp"
#include "gil.hpp"
qiLogCategory("qimpy");

namespace qi {
  namespace py {

    class PyServiceDirectory : public qi::ServiceDirectory
    {
    public:
      //return a future, or None (and throw in case of error)
      boost::python::object listen(const std::string &url, bool _async=false) {
        qi::Future<void> fut;
        {
          GILScopedUnlock _unlock;
          fut = ServiceDirectory::listen(url);
        }
        return toPyFutureAsync(fut, _async);
      }

      //override because python do not know qi::Url
      boost::python::list endpoints() const {
        boost::python::list ret;
        std::vector<qi::Url>     eps = ServiceDirectory::endpoints();
        for (unsigned int i = 0; i < eps.size(); ++i) {
          ret.append(eps.at(i).str());
        }
        return ret;
      }

    };

    void export_pyservicedirectory() {
      boost::python::class_<PyServiceDirectory>("ServiceDirectory")
          .def("listen", &PyServiceDirectory::listen, (boost::python::arg("url"), boost::python::arg("_async") = false))
          .def("setIdentity", &PyServiceDirectory::setIdentity)
          .def("close", &PyServiceDirectory::close)
          .def("endpoints", &PyServiceDirectory::endpoints);
    }

  }
}
<|endoftext|>


<commit_before>/*=========================================================================

  Library:   CTK

  Copyright (c) 2010  Kitware Inc.

  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.commontk.org/LICENSE

  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.

=========================================================================*/

// Qt includes
#include <QDebug>

// CTK includes
#include "ctkDynamicSpacer.h"

// -----------------------------------------------------------------------------
class ctkDynamicSpacerPrivate : public ctkPrivate<ctkDynamicSpacer>
{
  CTK_DECLARE_PUBLIC(ctkDynamicSpacer);
public:
  ctkDynamicSpacerPrivate();
  void init();

  bool        Enable;
  QSizePolicy ActiveSizePolicy;
  QSizePolicy InactiveSizePolicy;
};

// -----------------------------------------------------------------------------
ctkDynamicSpacerPrivate::ctkDynamicSpacerPrivate()
{
  this->Enable = false;
}

// -----------------------------------------------------------------------------
void ctkDynamicSpacerPrivate::init()
{
  CTK_P(ctkDynamicSpacer);
  this->ActiveSizePolicy = p->sizePolicy();
  this->InactiveSizePolicy = p->sizePolicy();
}

// -----------------------------------------------------------------------------
ctkDynamicSpacer::ctkDynamicSpacer(QWidget *_parent)
  :QWidget(_parent)
{
  CTK_INIT_PRIVATE(ctkDynamicSpacer);
  ctk_d()->init();
}

// -----------------------------------------------------------------------------
ctkDynamicSpacer::~ctkDynamicSpacer()
{
}

// -----------------------------------------------------------------------------
QSizePolicy ctkDynamicSpacer::activeSizePolicy() const
{
  CTK_D(const ctkDynamicSpacer);
  return d->ActiveSizePolicy;
}

// -----------------------------------------------------------------------------
void ctkDynamicSpacer::setActiveSizePolicy(QSizePolicy newActiveSizePolicy)
{
  CTK_D(ctkDynamicSpacer);
  d->ActiveSizePolicy = newActiveSizePolicy;
  if (d->Enable)
    {
    this->setSizePolicy(d->ActiveSizePolicy);
    }
}

// -----------------------------------------------------------------------------
QSizePolicy ctkDynamicSpacer::inactiveSizePolicy() const
{
  CTK_D(const ctkDynamicSpacer);
  return d->InactiveSizePolicy;
}

// -----------------------------------------------------------------------------
void ctkDynamicSpacer::setInactiveSizePolicy(QSizePolicy newInactiveSizePolicy)
{
  CTK_D(ctkDynamicSpacer);
  d->InactiveSizePolicy = newInactiveSizePolicy;
  if (!d->Enable)
    {
    this->setSizePolicy(d->InactiveSizePolicy);
    }
}

// -----------------------------------------------------------------------------
bool ctkDynamicSpacer::isActivated()const
{
  CTK_D(const ctkDynamicSpacer);
  return d->Enable;
}

// -----------------------------------------------------------------------------
void ctkDynamicSpacer::activate(bool enableSizePolicy)
{
  CTK_D(ctkDynamicSpacer);
  qDebug() << "Activate " << enableSizePolicy << (enableSizePolicy ? "Active" : "Inactive") << "size policy";
  d->Enable = enableSizePolicy;
  this->setSizePolicy(
    d->Enable ? d->ActiveSizePolicy : d->InactiveSizePolicy);
}
<commit_msg>STYLE: Remove useless debug output in ctkDynamicSpacer.<commit_after>/*=========================================================================

  Library:   CTK

  Copyright (c) 2010  Kitware Inc.

  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.commontk.org/LICENSE

  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.

=========================================================================*/

// Qt includes
#include <QDebug>

// CTK includes
#include "ctkDynamicSpacer.h"

// -----------------------------------------------------------------------------
class ctkDynamicSpacerPrivate : public ctkPrivate<ctkDynamicSpacer>
{
  CTK_DECLARE_PUBLIC(ctkDynamicSpacer);
public:
  ctkDynamicSpacerPrivate();
  void init();

  bool        Enable;
  QSizePolicy ActiveSizePolicy;
  QSizePolicy InactiveSizePolicy;
};

// -----------------------------------------------------------------------------
ctkDynamicSpacerPrivate::ctkDynamicSpacerPrivate()
{
  this->Enable = false;
}

// -----------------------------------------------------------------------------
void ctkDynamicSpacerPrivate::init()
{
  CTK_P(ctkDynamicSpacer);
  this->ActiveSizePolicy = p->sizePolicy();
  this->InactiveSizePolicy = p->sizePolicy();
}

// -----------------------------------------------------------------------------
ctkDynamicSpacer::ctkDynamicSpacer(QWidget *_parent)
  :QWidget(_parent)
{
  CTK_INIT_PRIVATE(ctkDynamicSpacer);
  ctk_d()->init();
}

// -----------------------------------------------------------------------------
ctkDynamicSpacer::~ctkDynamicSpacer()
{
}

// -----------------------------------------------------------------------------
QSizePolicy ctkDynamicSpacer::activeSizePolicy() const
{
  CTK_D(const ctkDynamicSpacer);
  return d->ActiveSizePolicy;
}

// -----------------------------------------------------------------------------
void ctkDynamicSpacer::setActiveSizePolicy(QSizePolicy newActiveSizePolicy)
{
  CTK_D(ctkDynamicSpacer);
  d->ActiveSizePolicy = newActiveSizePolicy;
  if (d->Enable)
    {
    this->setSizePolicy(d->ActiveSizePolicy);
    }
}

// -----------------------------------------------------------------------------
QSizePolicy ctkDynamicSpacer::inactiveSizePolicy() const
{
  CTK_D(const ctkDynamicSpacer);
  return d->InactiveSizePolicy;
}

// -----------------------------------------------------------------------------
void ctkDynamicSpacer::setInactiveSizePolicy(QSizePolicy newInactiveSizePolicy)
{
  CTK_D(ctkDynamicSpacer);
  d->InactiveSizePolicy = newInactiveSizePolicy;
  if (!d->Enable)
    {
    this->setSizePolicy(d->InactiveSizePolicy);
    }
}

// -----------------------------------------------------------------------------
bool ctkDynamicSpacer::isActivated()const
{
  CTK_D(const ctkDynamicSpacer);
  return d->Enable;
}

// -----------------------------------------------------------------------------
void ctkDynamicSpacer::activate(bool enableSizePolicy)
{
  CTK_D(ctkDynamicSpacer);
  d->Enable = enableSizePolicy;
  this->setSizePolicy(
    d->Enable ? d->ActiveSizePolicy : d->InactiveSizePolicy);
}
<|endoftext|>


<commit_before>#include "Benchmark.h"
#include "Logging.h"
#include "Itoa.h"

BENCHMARK(ItoaSprintf, n)
{
    char buf[20];
    u32toa_sprintf(n, buf);

    uint32_t r = 0;
    BENCHMARK_SUSPEND
    {
        r = atoi(buf);
    }
    CHECK(r == n);
}

BENCHMARK_RELATIVE(ItoaItoa, n)
{
    char buf[20];
    _itoa(n, buf, 10);

    uint32_t r = 0;
    BENCHMARK_SUSPEND
    {
        r = atoi(buf);
    }
    CHECK(r == n);
}

BENCHMARK_RELATIVE(ItoaMwilson, n)
{
    char buf[20];
    u32toa_mwilson(buf, n);

    uint32_t r = 0;
    BENCHMARK_SUSPEND
    {
        r = atoi(buf);
    }
    CHECK(r == n);
}

BENCHMARK_RELATIVE(ItoaNaive, n)
{
    char buf[20];
    u32toa_naive(n, buf);

    uint32_t r = 0;
    BENCHMARK_SUSPEND
    {
        r = atoi(buf);
    }
    CHECK(r == n);
}

BENCHMARK_RELATIVE(ItoaCount, n)
{
    char buf[20];
    u32toa_count(n, buf);

    uint32_t r = 0;
    BENCHMARK_SUSPEND
    {
        r = atoi(buf);
    }
    CHECK(r == n);
}

BENCHMARK_RELATIVE(ItoaLut, n)
{
    char buf[20];
    u32toa_lut(n, buf);

    uint32_t r = 0;
    BENCHMARK_SUSPEND
    {
        r = atoi(buf);
    }
    CHECK(r == n);
}
<commit_msg>itoa() not available under g++<commit_after>#include "Benchmark.h"
#include "Logging.h"
#include "Itoa.h"

BENCHMARK(ItoaSprintf, n)
{
    char buf[20];
    u32toa_sprintf(n, buf);

    uint32_t r = 0;
    BENCHMARK_SUSPEND
    {
        r = atoi(buf);
    }
    CHECK(r == n);
}

#ifdef _MSC_VER
BENCHMARK_RELATIVE(ItoaItoa, n)
{
    char buf[20];
    _itoa(n, buf, 10);

    uint32_t r = 0;
    BENCHMARK_SUSPEND
    {
        r = atoi(buf);
    }
    CHECK(r == n);
}
#endif

BENCHMARK_RELATIVE(ItoaMwilson, n)
{
    char buf[20];
    u32toa_mwilson(buf, n);

    uint32_t r = 0;
    BENCHMARK_SUSPEND
    {
        r = atoi(buf);
    }
    CHECK(r == n);
}

BENCHMARK_RELATIVE(ItoaNaive, n)
{
    char buf[20];
    u32toa_naive(n, buf);

    uint32_t r = 0;
    BENCHMARK_SUSPEND
    {
        r = atoi(buf);
    }
    CHECK(r == n);
}

BENCHMARK_RELATIVE(ItoaCount, n)
{
    char buf[20];
    u32toa_count(n, buf);

    uint32_t r = 0;
    BENCHMARK_SUSPEND
    {
        r = atoi(buf);
    }
    CHECK(r == n);
}

BENCHMARK_RELATIVE(ItoaLut, n)
{
    char buf[20];
    u32toa_lut(n, buf);

    uint32_t r = 0;
    BENCHMARK_SUSPEND
    {
        r = atoi(buf);
    }
    CHECK(r == n);
}
<|endoftext|>


<commit_before>// this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-

// -- BEGIN LICENSE BLOCK ----------------------------------------------
// Copyright 2019 FZI Forschungszentrum Informatik
//
// 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.
// -- END LICENSE BLOCK ------------------------------------------------

//----------------------------------------------------------------------
/*!\file
 *
 * \author  Felix Exner exner@fzi.de
 * \date    2019-10-21
 *
 */
//----------------------------------------------------------------------

#include <ur_robot_driver/ros/dashboard_client_ros.h>

namespace ur_driver
{
DashboardClientROS::DashboardClientROS(const ros::NodeHandle& nh, const std::string& robot_ip)
  : nh_(nh), client_(robot_ip)
{
  connect();

  // Service to release the brakes. If the robot is currently powered off, it will get powered on on the fly.
  // brake_release_service_ = create_dashboard_trigger_srv("brake_release", "brake release\n", "Brake releasing");
  brake_release_service_ = create_dashboard_trigger_srv("brake_release", "brake release\n", "Brake releasing");

  // If this service is called the operational mode can again be changed from PolyScope, and the user password is
  // enabled.
  clear_operational_mode_service_ = create_dashboard_trigger_srv("clear_operational_mode", "clear operational mode\n",
                                                                 "No longer controlling the operational mode\\. "
                                                                 "Current "
                                                                 "operational mode: "
                                                                 "'(MANUAL|AUTOMATIC)'\\.");

  // Close a (non-safety) popup on the teach pendant.
  close_popup_service_ = create_dashboard_trigger_srv("close_popup", "close popup\n", "closing popup");

  // Close a safety popup on the teach pendant.
  close_safety_popup_service_ =
      create_dashboard_trigger_srv("close_safety_popup", "close safety popup\n", "closing safety popup");

  // Pause a running program.
  pause_service_ = create_dashboard_trigger_srv("pause", "pause\n", "Pausing program");

  // Start execution of a previously loaded program
  play_service_ = create_dashboard_trigger_srv("play", "play\n", "Starting program");

  // Power off the robot motors
  power_off_service_ = create_dashboard_trigger_srv("power_off", "power off\n", "Powering off");

  // Power on the robot motors. To fully start the robot, call 'brake_release' afterwards.
  power_on_service_ = create_dashboard_trigger_srv("power_on", "power on\n", "Powering on");

  // Used when robot gets a safety fault or violation to restart the safety. After safety has been rebooted the robot
  // will be in Power Off. NOTE: You should always ensure it is okay to restart the system. It is highly recommended to
  // check the error log before using this command (either via PolyScope or e.g. ssh connection).
  restart_safety_service_ = create_dashboard_trigger_srv("restart_safety", "restart safety\n", "Restarting safety");

  // Shutdown the robot controller
  shutdown_service_ = create_dashboard_trigger_srv("shutdown", "shutdown\n", "Shutting down");

  // Stop program execution on the robot
  stop_service_ = create_dashboard_trigger_srv("stop", "stop\n", "Stopped");

  // Dismiss a protective stop to continue robot movements. NOTE: It is the responsibility of the user to ensure the
  // cause of the protective stop is resolved before calling this service.
  unlock_protective_stop_service_ =
      create_dashboard_trigger_srv("unlock_protective_stop", "unlock protective stop\n", "Protective stop releasing");

  // Query whether there is currently a program running
  running_service_ = nh_.advertiseService("program_running", &DashboardClientROS::handleRunningQuery, this);

  // Load a robot installation from a file
  get_loaded_program_service_ =
      nh_.advertiseService<ur_dashboard_msgs::GetLoadedProgram::Request, ur_dashboard_msgs::GetLoadedProgram::Response>(
          "get_loaded_program",
          [&](ur_dashboard_msgs::GetLoadedProgram::Request& req, ur_dashboard_msgs::GetLoadedProgram::Response& resp) {
            resp.answer = this->client_.sendAndReceive("get loaded program\n");
            std::smatch match;
            std::regex expected("Loaded program: (.+)");
            resp.success = std::regex_match(resp.answer, match, expected);
            if (resp.success)
            {
              resp.program_name = match[1];
            }
            return true;
          });

  // Load a robot installation from a file
  load_installation_service_ =
      nh_.advertiseService<ur_dashboard_msgs::Load::Request, ur_dashboard_msgs::Load::Response>(
          "load_installation", [&](ur_dashboard_msgs::Load::Request& req, ur_dashboard_msgs::Load::Response& resp) {
            resp.answer = this->client_.sendAndReceive("load installation " + req.filename + "\n");
            resp.success = std::regex_match(resp.answer, std::regex("Loading installation: .+"));
            return true;
          });

  // Load a robot program from a file
  load_program_service_ = nh_.advertiseService<ur_dashboard_msgs::Load::Request, ur_dashboard_msgs::Load::Response>(
      "load_program", [&](ur_dashboard_msgs::Load::Request& req, ur_dashboard_msgs::Load::Response& resp) {
        resp.answer = this->client_.sendAndReceive("load " + req.filename + "\n");
        resp.success = std::regex_match(resp.answer, std::regex("Loading program: .+"));
        return true;
      });

  // Query whether the current program is saved
  is_program_saved_service_ = nh_.advertiseService("program_saved", &DashboardClientROS::handleSavedQuery, this);

  // Service to show a popup on the UR Teach pendant.
  popup_service_ = nh_.advertiseService<ur_dashboard_msgs::Popup::Request, ur_dashboard_msgs::Popup::Response>(
      "popup", [&](ur_dashboard_msgs::Popup::Request& req, ur_dashboard_msgs::Popup::Response& resp) {
        resp.answer = this->client_.sendAndReceive("popup " + req.message + "\n");
        resp.success = std::regex_match(resp.answer, std::regex("showing popup"));

        return true;
      });

  // Service to query the current program state
  popup_service_ =
      nh_.advertiseService<ur_dashboard_msgs::GetProgramState::Request, ur_dashboard_msgs::GetProgramState::Response>(
          "program_state",
          [&](ur_dashboard_msgs::GetProgramState::Request& req, ur_dashboard_msgs::GetProgramState::Response& resp) {
            resp.answer = this->client_.sendAndReceive("programState\n");
            std::smatch match;
            std::regex expected("(STOPPED|PLAYING|PAUSED) (.+)");
            resp.success = std::regex_match(resp.answer, match, expected);
            if (resp.success)
            {
              resp.state.state = match[1];
              resp.program_name = match[2];
            }
            return true;
          });

  // Service to query the current safety mode
  safety_mode_service_ = nh_.advertiseService("get_safety_mode", &DashboardClientROS::handleSafetyModeQuery, this);

  // Service to query the current robot mode
  robot_mode_service_ = nh_.advertiseService("get_robot_mode", &DashboardClientROS::handleRobotModeQuery, this);

  // Service to add a message to the robot's log
  add_to_log_service_ =
      nh_.advertiseService<ur_dashboard_msgs::AddToLog::Request, ur_dashboard_msgs::AddToLog::Response>(
          "add_to_log", [&](ur_dashboard_msgs::AddToLog::Request& req, ur_dashboard_msgs::AddToLog::Response& resp) {
            resp.answer = this->client_.sendAndReceive("addToLog " + req.message + "\n");
            resp.success = std::regex_match(resp.answer, std::regex("(Added log message|No log message to add)"));

            return true;
          });

  // General purpose service to send arbitrary messages to the dashboard server
  running_service_ =
      nh_.advertiseService<ur_dashboard_msgs::RawRequest::Request, ur_dashboard_msgs::RawRequest::Response>(
          "raw_request",
          [&](ur_dashboard_msgs::RawRequest::Request& req, ur_dashboard_msgs::RawRequest::Response& resp) {
            resp.answer = this->client_.sendAndReceive(req.query + "\n");
            return true;
          });

  // Service to reconnect to the dashboard server
  reconnect_service_ = nh_.advertiseService<std_srvs::Trigger::Request, std_srvs::Trigger::Response>(
      "connect", [&](std_srvs::Trigger::Request& req, std_srvs::Trigger::Response& resp) {
        resp.success = connect();
        return true;
      });

  // Disconnect from the dashboard service.
  quit_service_ = nh_.advertiseService<std_srvs::Trigger::Request, std_srvs::Trigger::Response>(
      "quit", [&](std_srvs::Trigger::Request& req, std_srvs::Trigger::Response& resp) {
        resp.message = this->client_.sendAndReceive("quit\n");
        resp.success = std::regex_match(resp.message, std::regex("Disconnected"));
        client_.disconnect();
        return true;
      });
}

bool DashboardClientROS::handleRunningQuery(ur_dashboard_msgs::IsProgramRunning::Request& req,
                                            ur_dashboard_msgs::IsProgramRunning::Response& resp)
{
  resp.answer = this->client_.sendAndReceive("running\n");
  std::regex expected("Program running: (true|false)");
  std::smatch match;
  resp.success = std::regex_match(resp.answer, match, expected);

  if (resp.success)
  {
    resp.program_running = (match[1] == "true");
  }

  return true;
}

bool DashboardClientROS::handleSavedQuery(ur_dashboard_msgs::IsProgramSaved::Request& req,
                                          ur_dashboard_msgs::IsProgramSaved::Response& resp)
{
  resp.answer = this->client_.sendAndReceive("isProgramSaved\n");
  std::regex expected("(true|false) ([^\\s]+)");
  std::smatch match;
  resp.success = std::regex_match(resp.answer, match, expected);

  if (resp.success)
  {
    resp.program_saved = (match[1] == "true");
    resp.program_name = match[2];
  }

  return true;
}

bool DashboardClientROS::handleSafetyModeQuery(ur_dashboard_msgs::GetSafetyMode::Request& req,
                                               ur_dashboard_msgs::GetSafetyMode::Response& resp)
{
  resp.answer = this->client_.sendAndReceive("safetymode\n");
  std::smatch match;
  std::regex expected("Safetymode: (.+)");
  resp.success = std::regex_match(resp.answer, match, expected);
  if (resp.success)
  {
    if (match[1] == "NORMAL")
    {
      resp.safety_mode.mode = ur_dashboard_msgs::SafetyMode::NORMAL;
    }
    else if (match[1] == "REDUCED")
    {
      resp.safety_mode.mode = ur_dashboard_msgs::SafetyMode::REDUCED;
    }
    else if (match[1] == "PROTECTIVE_STOP")
    {
      resp.safety_mode.mode = ur_dashboard_msgs::SafetyMode::PROTECTIVE_STOP;
    }
    else if (match[1] == "RECOVERY")
    {
      resp.safety_mode.mode = ur_dashboard_msgs::SafetyMode::RECOVERY;
    }
    else if (match[1] == "SAFEGUARD_STOP")
    {
      resp.safety_mode.mode = ur_dashboard_msgs::SafetyMode::SAFEGUARD_STOP;
    }
    else if (match[1] == "SYSTEM_EMERGENCY_STOP")
    {
      resp.safety_mode.mode = ur_dashboard_msgs::SafetyMode::SYSTEM_EMERGENCY_STOP;
    }
    else if (match[1] == "ROBOT_EMERGENCY_STOP")
    {
      resp.safety_mode.mode = ur_dashboard_msgs::SafetyMode::ROBOT_EMERGENCY_STOP;
    }
    else if (match[1] == "VIOLATION")
    {
      resp.safety_mode.mode = ur_dashboard_msgs::SafetyMode::VIOLATION;
    }
    else if (match[1] == "FAULT")
    {
      resp.safety_mode.mode = ur_dashboard_msgs::SafetyMode::FAULT;
    }
    // The following are only available in SafetyStatus from 5.5 on
    // else if (match[1] == "AUTOMATIC_MODE_SAFEGUARD_STOP")
    //{
    // resp.safety_mode.mode = ur_dashboard_msgs::SafetyMode::AUTOMATIC_MODE_SAFEGUARD_STOP;
    //}
    // else if (match[1] == "SYSTEM_THREE_POSITION_ENABLING_STOP")
    //{
    // resp.safety_mode.mode = ur_dashboard_msgs::SafetyMode::SYSTEM_THREE_POSITION_ENABLING_STOP;
    //}
  }
  return true;
}

bool DashboardClientROS::handleRobotModeQuery(ur_dashboard_msgs::GetRobotMode::Request& req,
                                              ur_dashboard_msgs::GetRobotMode::Response& resp)
{
  resp.answer = this->client_.sendAndReceive("robotmode\n");
  std::smatch match;
  std::regex expected("Robotmode: (.+)");
  resp.success = std::regex_match(resp.answer, match, expected);
  if (resp.success)
  {
    if (match[1] == "NO_CONTROLLER")
    {
      resp.robot_mode.mode = ur_dashboard_msgs::RobotMode::NO_CONTROLLER;
    }
    else if (match[1] == "DISCONNECTED")
    {
      resp.robot_mode.mode = ur_dashboard_msgs::RobotMode::DISCONNECTED;
    }
    else if (match[1] == "CONFIRM_SAFETY")
    {
      resp.robot_mode.mode = ur_dashboard_msgs::RobotMode::CONFIRM_SAFETY;
    }
    else if (match[1] == "BOOTING")
    {
      resp.robot_mode.mode = ur_dashboard_msgs::RobotMode::BOOTING;
    }
    else if (match[1] == "POWER_OFF")
    {
      resp.robot_mode.mode = ur_dashboard_msgs::RobotMode::POWER_OFF;
    }
    else if (match[1] == "POWER_ON")
    {
      resp.robot_mode.mode = ur_dashboard_msgs::RobotMode::POWER_ON;
    }
    else if (match[1] == "IDLE")
    {
      resp.robot_mode.mode = ur_dashboard_msgs::RobotMode::IDLE;
    }
    else if (match[1] == "BACKDRIVE")
    {
      resp.robot_mode.mode = ur_dashboard_msgs::RobotMode::BACKDRIVE;
    }
    else if (match[1] == "RUNNING")
    {
      resp.robot_mode.mode = ur_dashboard_msgs::RobotMode::RUNNING;
    }
    else if (match[1] == "UPDATING_FIRMWARE")
    {
      resp.robot_mode.mode = ur_dashboard_msgs::RobotMode::UPDATING_FIRMWARE;
    }
  }
  return true;
}

bool DashboardClientROS::connect()
{
  timeval tv;
  // Timeout after which a call to the dashboard server will be considered failure if no answer has
  // been received.
  tv.tv_sec = nh_.param("receive_timeout", 1);
  tv.tv_usec = 0;
  client_.setReceiveTimeout(tv);
  return client_.connect();
}
}  // namespace ur_driver
<commit_msg>fixed duplicated service advertisements (#75)<commit_after>// this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-

// -- BEGIN LICENSE BLOCK ----------------------------------------------
// Copyright 2019 FZI Forschungszentrum Informatik
//
// 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.
// -- END LICENSE BLOCK ------------------------------------------------

//----------------------------------------------------------------------
/*!\file
 *
 * \author  Felix Exner exner@fzi.de
 * \date    2019-10-21
 *
 */
//----------------------------------------------------------------------

#include <ur_robot_driver/ros/dashboard_client_ros.h>

namespace ur_driver
{
DashboardClientROS::DashboardClientROS(const ros::NodeHandle& nh, const std::string& robot_ip)
  : nh_(nh), client_(robot_ip)
{
  connect();

  // Service to release the brakes. If the robot is currently powered off, it will get powered on on the fly.
  brake_release_service_ = create_dashboard_trigger_srv("brake_release", "brake release\n", "Brake releasing");

  // If this service is called the operational mode can again be changed from PolyScope, and the user password is
  // enabled.
  clear_operational_mode_service_ = create_dashboard_trigger_srv("clear_operational_mode", "clear operational mode\n",
                                                                 "No longer controlling the operational mode\\. "
                                                                 "Current "
                                                                 "operational mode: "
                                                                 "'(MANUAL|AUTOMATIC)'\\.");

  // Close a (non-safety) popup on the teach pendant.
  close_popup_service_ = create_dashboard_trigger_srv("close_popup", "close popup\n", "closing popup");

  // Close a safety popup on the teach pendant.
  close_safety_popup_service_ =
      create_dashboard_trigger_srv("close_safety_popup", "close safety popup\n", "closing safety popup");

  // Pause a running program.
  pause_service_ = create_dashboard_trigger_srv("pause", "pause\n", "Pausing program");

  // Start execution of a previously loaded program
  play_service_ = create_dashboard_trigger_srv("play", "play\n", "Starting program");

  // Power off the robot motors
  power_off_service_ = create_dashboard_trigger_srv("power_off", "power off\n", "Powering off");

  // Power on the robot motors. To fully start the robot, call 'brake_release' afterwards.
  power_on_service_ = create_dashboard_trigger_srv("power_on", "power on\n", "Powering on");

  // Used when robot gets a safety fault or violation to restart the safety. After safety has been rebooted the robot
  // will be in Power Off. NOTE: You should always ensure it is okay to restart the system. It is highly recommended to
  // check the error log before using this command (either via PolyScope or e.g. ssh connection).
  restart_safety_service_ = create_dashboard_trigger_srv("restart_safety", "restart safety\n", "Restarting safety");

  // Shutdown the robot controller
  shutdown_service_ = create_dashboard_trigger_srv("shutdown", "shutdown\n", "Shutting down");

  // Stop program execution on the robot
  stop_service_ = create_dashboard_trigger_srv("stop", "stop\n", "Stopped");

  // Dismiss a protective stop to continue robot movements. NOTE: It is the responsibility of the user to ensure the
  // cause of the protective stop is resolved before calling this service.
  unlock_protective_stop_service_ =
      create_dashboard_trigger_srv("unlock_protective_stop", "unlock protective stop\n", "Protective stop releasing");

  // Query whether there is currently a program running
  running_service_ = nh_.advertiseService("program_running", &DashboardClientROS::handleRunningQuery, this);

  // Load a robot installation from a file
  get_loaded_program_service_ =
      nh_.advertiseService<ur_dashboard_msgs::GetLoadedProgram::Request, ur_dashboard_msgs::GetLoadedProgram::Response>(
          "get_loaded_program",
          [&](ur_dashboard_msgs::GetLoadedProgram::Request& req, ur_dashboard_msgs::GetLoadedProgram::Response& resp) {
            resp.answer = this->client_.sendAndReceive("get loaded program\n");
            std::smatch match;
            std::regex expected("Loaded program: (.+)");
            resp.success = std::regex_match(resp.answer, match, expected);
            if (resp.success)
            {
              resp.program_name = match[1];
            }
            return true;
          });

  // Load a robot installation from a file
  load_installation_service_ =
      nh_.advertiseService<ur_dashboard_msgs::Load::Request, ur_dashboard_msgs::Load::Response>(
          "load_installation", [&](ur_dashboard_msgs::Load::Request& req, ur_dashboard_msgs::Load::Response& resp) {
            resp.answer = this->client_.sendAndReceive("load installation " + req.filename + "\n");
            resp.success = std::regex_match(resp.answer, std::regex("Loading installation: .+"));
            return true;
          });

  // Load a robot program from a file
  load_program_service_ = nh_.advertiseService<ur_dashboard_msgs::Load::Request, ur_dashboard_msgs::Load::Response>(
      "load_program", [&](ur_dashboard_msgs::Load::Request& req, ur_dashboard_msgs::Load::Response& resp) {
        resp.answer = this->client_.sendAndReceive("load " + req.filename + "\n");
        resp.success = std::regex_match(resp.answer, std::regex("Loading program: .+"));
        return true;
      });

  // Query whether the current program is saved
  is_program_saved_service_ = nh_.advertiseService("program_saved", &DashboardClientROS::handleSavedQuery, this);

  // Service to show a popup on the UR Teach pendant.
  popup_service_ = nh_.advertiseService<ur_dashboard_msgs::Popup::Request, ur_dashboard_msgs::Popup::Response>(
      "popup", [&](ur_dashboard_msgs::Popup::Request& req, ur_dashboard_msgs::Popup::Response& resp) {
        resp.answer = this->client_.sendAndReceive("popup " + req.message + "\n");
        resp.success = std::regex_match(resp.answer, std::regex("showing popup"));

        return true;
      });

  // Service to query the current program state
  program_state_service_ =
      nh_.advertiseService<ur_dashboard_msgs::GetProgramState::Request, ur_dashboard_msgs::GetProgramState::Response>(
          "program_state",
          [&](ur_dashboard_msgs::GetProgramState::Request& req, ur_dashboard_msgs::GetProgramState::Response& resp) {
            resp.answer = this->client_.sendAndReceive("programState\n");
            std::smatch match;
            std::regex expected("(STOPPED|PLAYING|PAUSED) (.+)");
            resp.success = std::regex_match(resp.answer, match, expected);
            if (resp.success)
            {
              resp.state.state = match[1];
              resp.program_name = match[2];
            }
            return true;
          });

  // Service to query the current safety mode
  safety_mode_service_ = nh_.advertiseService("get_safety_mode", &DashboardClientROS::handleSafetyModeQuery, this);

  // Service to query the current robot mode
  robot_mode_service_ = nh_.advertiseService("get_robot_mode", &DashboardClientROS::handleRobotModeQuery, this);

  // Service to add a message to the robot's log
  add_to_log_service_ =
      nh_.advertiseService<ur_dashboard_msgs::AddToLog::Request, ur_dashboard_msgs::AddToLog::Response>(
          "add_to_log", [&](ur_dashboard_msgs::AddToLog::Request& req, ur_dashboard_msgs::AddToLog::Response& resp) {
            resp.answer = this->client_.sendAndReceive("addToLog " + req.message + "\n");
            resp.success = std::regex_match(resp.answer, std::regex("(Added log message|No log message to add)"));

            return true;
          });

  // General purpose service to send arbitrary messages to the dashboard server
  raw_request_service_ =
      nh_.advertiseService<ur_dashboard_msgs::RawRequest::Request, ur_dashboard_msgs::RawRequest::Response>(
          "raw_request",
          [&](ur_dashboard_msgs::RawRequest::Request& req, ur_dashboard_msgs::RawRequest::Response& resp) {
            resp.answer = this->client_.sendAndReceive(req.query + "\n");
            return true;
          });

  // Service to reconnect to the dashboard server
  reconnect_service_ = nh_.advertiseService<std_srvs::Trigger::Request, std_srvs::Trigger::Response>(
      "connect", [&](std_srvs::Trigger::Request& req, std_srvs::Trigger::Response& resp) {
        resp.success = connect();
        return true;
      });

  // Disconnect from the dashboard service.
  quit_service_ = nh_.advertiseService<std_srvs::Trigger::Request, std_srvs::Trigger::Response>(
      "quit", [&](std_srvs::Trigger::Request& req, std_srvs::Trigger::Response& resp) {
        resp.message = this->client_.sendAndReceive("quit\n");
        resp.success = std::regex_match(resp.message, std::regex("Disconnected"));
        client_.disconnect();
        return true;
      });
}

bool DashboardClientROS::handleRunningQuery(ur_dashboard_msgs::IsProgramRunning::Request& req,
                                            ur_dashboard_msgs::IsProgramRunning::Response& resp)
{
  resp.answer = this->client_.sendAndReceive("running\n");
  std::regex expected("Program running: (true|false)");
  std::smatch match;
  resp.success = std::regex_match(resp.answer, match, expected);

  if (resp.success)
  {
    resp.program_running = (match[1] == "true");
  }

  return true;
}

bool DashboardClientROS::handleSavedQuery(ur_dashboard_msgs::IsProgramSaved::Request& req,
                                          ur_dashboard_msgs::IsProgramSaved::Response& resp)
{
  resp.answer = this->client_.sendAndReceive("isProgramSaved\n");
  std::regex expected("(true|false) ([^\\s]+)");
  std::smatch match;
  resp.success = std::regex_match(resp.answer, match, expected);

  if (resp.success)
  {
    resp.program_saved = (match[1] == "true");
    resp.program_name = match[2];
  }

  return true;
}

bool DashboardClientROS::handleSafetyModeQuery(ur_dashboard_msgs::GetSafetyMode::Request& req,
                                               ur_dashboard_msgs::GetSafetyMode::Response& resp)
{
  resp.answer = this->client_.sendAndReceive("safetymode\n");
  std::smatch match;
  std::regex expected("Safetymode: (.+)");
  resp.success = std::regex_match(resp.answer, match, expected);
  if (resp.success)
  {
    if (match[1] == "NORMAL")
    {
      resp.safety_mode.mode = ur_dashboard_msgs::SafetyMode::NORMAL;
    }
    else if (match[1] == "REDUCED")
    {
      resp.safety_mode.mode = ur_dashboard_msgs::SafetyMode::REDUCED;
    }
    else if (match[1] == "PROTECTIVE_STOP")
    {
      resp.safety_mode.mode = ur_dashboard_msgs::SafetyMode::PROTECTIVE_STOP;
    }
    else if (match[1] == "RECOVERY")
    {
      resp.safety_mode.mode = ur_dashboard_msgs::SafetyMode::RECOVERY;
    }
    else if (match[1] == "SAFEGUARD_STOP")
    {
      resp.safety_mode.mode = ur_dashboard_msgs::SafetyMode::SAFEGUARD_STOP;
    }
    else if (match[1] == "SYSTEM_EMERGENCY_STOP")
    {
      resp.safety_mode.mode = ur_dashboard_msgs::SafetyMode::SYSTEM_EMERGENCY_STOP;
    }
    else if (match[1] == "ROBOT_EMERGENCY_STOP")
    {
      resp.safety_mode.mode = ur_dashboard_msgs::SafetyMode::ROBOT_EMERGENCY_STOP;
    }
    else if (match[1] == "VIOLATION")
    {
      resp.safety_mode.mode = ur_dashboard_msgs::SafetyMode::VIOLATION;
    }
    else if (match[1] == "FAULT")
    {
      resp.safety_mode.mode = ur_dashboard_msgs::SafetyMode::FAULT;
    }
    // The following are only available in SafetyStatus from 5.5 on
    // else if (match[1] == "AUTOMATIC_MODE_SAFEGUARD_STOP")
    //{
    // resp.safety_mode.mode = ur_dashboard_msgs::SafetyMode::AUTOMATIC_MODE_SAFEGUARD_STOP;
    //}
    // else if (match[1] == "SYSTEM_THREE_POSITION_ENABLING_STOP")
    //{
    // resp.safety_mode.mode = ur_dashboard_msgs::SafetyMode::SYSTEM_THREE_POSITION_ENABLING_STOP;
    //}
  }
  return true;
}

bool DashboardClientROS::handleRobotModeQuery(ur_dashboard_msgs::GetRobotMode::Request& req,
                                              ur_dashboard_msgs::GetRobotMode::Response& resp)
{
  resp.answer = this->client_.sendAndReceive("robotmode\n");
  std::smatch match;
  std::regex expected("Robotmode: (.+)");
  resp.success = std::regex_match(resp.answer, match, expected);
  if (resp.success)
  {
    if (match[1] == "NO_CONTROLLER")
    {
      resp.robot_mode.mode = ur_dashboard_msgs::RobotMode::NO_CONTROLLER;
    }
    else if (match[1] == "DISCONNECTED")
    {
      resp.robot_mode.mode = ur_dashboard_msgs::RobotMode::DISCONNECTED;
    }
    else if (match[1] == "CONFIRM_SAFETY")
    {
      resp.robot_mode.mode = ur_dashboard_msgs::RobotMode::CONFIRM_SAFETY;
    }
    else if (match[1] == "BOOTING")
    {
      resp.robot_mode.mode = ur_dashboard_msgs::RobotMode::BOOTING;
    }
    else if (match[1] == "POWER_OFF")
    {
      resp.robot_mode.mode = ur_dashboard_msgs::RobotMode::POWER_OFF;
    }
    else if (match[1] == "POWER_ON")
    {
      resp.robot_mode.mode = ur_dashboard_msgs::RobotMode::POWER_ON;
    }
    else if (match[1] == "IDLE")
    {
      resp.robot_mode.mode = ur_dashboard_msgs::RobotMode::IDLE;
    }
    else if (match[1] == "BACKDRIVE")
    {
      resp.robot_mode.mode = ur_dashboard_msgs::RobotMode::BACKDRIVE;
    }
    else if (match[1] == "RUNNING")
    {
      resp.robot_mode.mode = ur_dashboard_msgs::RobotMode::RUNNING;
    }
    else if (match[1] == "UPDATING_FIRMWARE")
    {
      resp.robot_mode.mode = ur_dashboard_msgs::RobotMode::UPDATING_FIRMWARE;
    }
  }
  return true;
}

bool DashboardClientROS::connect()
{
  timeval tv;
  // Timeout after which a call to the dashboard server will be considered failure if no answer has
  // been received.
  tv.tv_sec = nh_.param("receive_timeout", 1);
  tv.tv_usec = 0;
  client_.setReceiveTimeout(tv);
  return client_.connect();
}
}  // namespace ur_driver
<|endoftext|>


<commit_before>/**
 *   Copyright 2011-2015 Quickstep Technologies LLC.
 *   Copyright 2015 Pivotal Software, Inc.
 *
 *   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.
 **/

#ifndef QUICKSTEP_QUERY_EXECUTION_WORKER_MESSAGE_HPP_
#define QUICKSTEP_QUERY_EXECUTION_WORKER_MESSAGE_HPP_

#include <cstddef>

namespace quickstep {

class WorkOrder;
/**
 * @brief The messages to be sent to the worker from Foreman.
 *
 * @note  This class is copyable.
 **/
class WorkerMessage {
 public:
  enum WorkerMessageType {
    kRebuildWorkOrder = 0,
    kWorkOrder,
    kPoison
  };

  /**
   * @brief A static factory method for generating rebuild WorkOrder messages.
   *
   * @param rebuild_workorder The rebuild WorkOrder to be executed by the worker.
   * @param relational_op_index The index of the relational operator in the
   *        query plan DAG that generated the given rebuild WorkOrder.
   **/
  static WorkerMessage* RebuildWorkOrderMessage(WorkOrder *rebuild_workorder, const std::size_t relational_op_index) {
    return new WorkerMessage(rebuild_workorder, relational_op_index, kRebuildWorkOrder);
  }

  /**
   * @brief A static factory method for generating WorkOrder messages.
   *
   * @param workorder The work order to be executed by the worker.
   * @param relational_op_index The index of the relational operator in the
   *                            query plan DAG that generated the given
   *                            workorder.
   **/
  static WorkerMessage* WorkOrderMessage(WorkOrder *workorder, const std::size_t relational_op_index) {
    return new WorkerMessage(workorder, relational_op_index, kWorkOrder);
  }

  /**
   * @brief A static factory method for generating a poison message.
   **/
  static WorkerMessage* PoisonMessage() {
    return new WorkerMessage(nullptr, 0, kPoison);
  }

  /**
   * @brief Destructor.
   **/
  ~WorkerMessage() {
  }

  /**
   * @brief Gets the work order to be executed by the worker.
   * @return A pointer to the work order which the worker should execute.
   **/
  inline WorkOrder* getWorkOrder() const {
    return work_unit_;
  }

  /**
   * @brief Get the index of the relational operator in the DAG that generated
   *        the workorder.
   **/
  inline std::size_t getRelationalOpIndex() const {
    return relational_op_index_;
  }

  /**
   * @brief Get the type of this WorkerMessage.
   **/
  inline WorkerMessageType getType() const {
    return type_;
  }

 private:
  /**
   * @brief Constructor.
   *
   * @param work_unit The work order to be executed by the worker. A NULL
   *        workorder indicates a poison message.
   * @param relational_op_index The index of the relational operator in the
   *        query plan DAG that generated the given WorkOrder.
   * @param type Type of the WorkerMessage.
   **/
  WorkerMessage(WorkOrder *work_unit,
                const std::size_t relational_op_index,
                const WorkerMessageType type)
      : work_unit_(work_unit),
        relational_op_index_(relational_op_index),
        type_(type) {
  }

  WorkOrder *work_unit_;
  const std::size_t relational_op_index_;
  const WorkerMessageType type_;
};

}  // namespace quickstep

#endif  // QUICKSTEP_QUERY_EXECUTION_WORKER_MESSAGE_HPP_
<commit_msg>Added @return for factory methods.<commit_after>/**
 *   Copyright 2011-2015 Quickstep Technologies LLC.
 *   Copyright 2015 Pivotal Software, Inc.
 *
 *   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.
 **/

#ifndef QUICKSTEP_QUERY_EXECUTION_WORKER_MESSAGE_HPP_
#define QUICKSTEP_QUERY_EXECUTION_WORKER_MESSAGE_HPP_

#include <cstddef>

namespace quickstep {

class WorkOrder;
/**
 * @brief The messages to be sent to the worker from Foreman.
 *
 * @note  This class is copyable.
 **/
class WorkerMessage {
 public:
  enum WorkerMessageType {
    kRebuildWorkOrder = 0,
    kWorkOrder,
    kPoison
  };

  /**
   * @brief A static factory method for generating rebuild WorkOrder messages.
   *
   * @param rebuild_workorder The rebuild WorkOrder to be executed by the worker.
   * @param relational_op_index The index of the relational operator in the
   *        query plan DAG that generated the given rebuild WorkOrder.
   *
   * @return The constructed RebuildWorkOrderMessage.
   **/
  static WorkerMessage* RebuildWorkOrderMessage(WorkOrder *rebuild_workorder, const std::size_t relational_op_index) {
    return new WorkerMessage(rebuild_workorder, relational_op_index, kRebuildWorkOrder);
  }

  /**
   * @brief A static factory method for generating WorkOrder messages.
   *
   * @param workorder The work order to be executed by the worker.
   * @param relational_op_index The index of the relational operator in the
   *                            query plan DAG that generated the given
   *                            workorder.
   *
   * @return The constructed WorkOrderMessage.
   **/
  static WorkerMessage* WorkOrderMessage(WorkOrder *workorder, const std::size_t relational_op_index) {
    return new WorkerMessage(workorder, relational_op_index, kWorkOrder);
  }

  /**
   * @brief A static factory method for generating a poison message.
   *
   * @return The constructed PoisonMessage.
   **/
  static WorkerMessage* PoisonMessage() {
    return new WorkerMessage(nullptr, 0, kPoison);
  }

  /**
   * @brief Destructor.
   **/
  ~WorkerMessage() {
  }

  /**
   * @brief Gets the work order to be executed by the worker.
   * @return A pointer to the work order which the worker should execute.
   **/
  inline WorkOrder* getWorkOrder() const {
    return work_unit_;
  }

  /**
   * @brief Get the index of the relational operator in the DAG that generated
   *        the workorder.
   **/
  inline std::size_t getRelationalOpIndex() const {
    return relational_op_index_;
  }

  /**
   * @brief Get the type of this WorkerMessage.
   **/
  inline WorkerMessageType getType() const {
    return type_;
  }

 private:
  /**
   * @brief Constructor.
   *
   * @param work_unit The work order to be executed by the worker. A NULL
   *        workorder indicates a poison message.
   * @param relational_op_index The index of the relational operator in the
   *        query plan DAG that generated the given WorkOrder.
   * @param type Type of the WorkerMessage.
   **/
  WorkerMessage(WorkOrder *work_unit,
                const std::size_t relational_op_index,
                const WorkerMessageType type)
      : work_unit_(work_unit),
        relational_op_index_(relational_op_index),
        type_(type) {
  }

  WorkOrder *work_unit_;
  const std::size_t relational_op_index_;
  const WorkerMessageType type_;
};

}  // namespace quickstep

#endif  // QUICKSTEP_QUERY_EXECUTION_WORKER_MESSAGE_HPP_
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
//
//  File: InputPly.cpp
//
//  For more information, please see: http://www.nektar.info/
//
//  The MIT License
//
//  Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
//  Department of Aeronautics, Imperial College London (UK), and Scientific
//  Computing and Imaging Institute, University of Utah (USA).
//
//  License for the specific language governing rights and limitations under
//  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.
//
//  Description: PLY converter.
//
////////////////////////////////////////////////////////////////////////////////

#include <string>
#include <iostream>
using namespace std;

#include "MeshElements.h"
#include "InputPly.h"

namespace Nektar
{
    namespace Utilities
    {
        ModuleKey InputPly::className =
            GetModuleFactory().RegisterCreatorFunction(
                ModuleKey(eInputModule, "ply"), InputPly::create,
                "Reads ply triangulation format.");

        InputPly::InputPly(MeshSharedPtr m) : InputModule(m)
        {

        }

        InputPly::~InputPly()
        {

        }

        /**
         *
         * @param   pFilename           Filename of Gmsh file to read.
         */
        void InputPly::Process()
        {

            // Open the file stream.
            OpenStream();

            ReadPly(m_mshFile);

            m_mshFile.close();

            ProcessVertices();
            ProcessEdges();
            ProcessFaces();
            ProcessElements();
            ProcessComposites();
        }

        void InputPly::ReadPly(std::ifstream &mshFile, NekDouble scale)
        {
            m_mesh->m_expDim = 0;
            string line;
            int nVertices = 0;
            int nEntities = 0;
            int nProperties = 0;
            LibUtilities::ShapeType elType = LibUtilities::eTriangle;
            map<string, int> propMap;

            if (m_mesh->m_verbose)
            {
                cout << "InputPly: Start reading file..." << endl;
            }

            while (!mshFile.eof())
            {
                getline(mshFile, line);
                stringstream s(line);
                string word;
                s >> word;
                if (word == "element")
                {
                    s >> word;
                    if (word == "vertex")
                    {
                        s >> nVertices;
                    }
                    else if (word == "face")
                    {
                        s >> nEntities;
                    }
                    continue;
                }
                else if (word == "property")
                {
                    s >> word >> word;
                    propMap[word] = nProperties++;
                }
                else if (word == "end_header")
                {
                    // Read nodes
                    vector<double> data(nProperties);
                    for (int i = 0; i < nVertices; ++i)
                    {
                        getline(mshFile, line);
                        stringstream st(line);

                        for (int j = 0; j < nProperties; ++j)
                        {
                            st >> data[j];
                        }

                        double x = data[propMap["x"]];
                        double y = data[propMap["y"]];
                        double z = data[propMap["z"]];

                        if ((y * y) > 0.000001 && m_mesh->m_spaceDim != 3)
                        {
                            m_mesh->m_spaceDim = 2;
                        }
                        if ((z * z) > 0.000001)
                        {
                            m_mesh->m_spaceDim = 3;
                        }

                        x *= scale;
                        y *= scale;
                        z *= scale;

                        m_mesh->m_node.push_back(
                            boost::shared_ptr<Node>(new Node(i, x, y, z)));

                        // Read vertex normals.
                        if (propMap.count("nx") > 0)
                        {
                            double nx = data[propMap["nx"]];
                            double ny = data[propMap["ny"]];
                            double nz = data[propMap["nz"]];
                            m_mesh->m_vertexNormals[i] = Node(0, nx, ny, nz);
                        }
                    }

                    // Read elements
                    for (int i = 0; i < nEntities; ++i)
                    {
                        getline(mshFile, line);
                        stringstream st(line);
                        int id = 0;

                        // Create element tags
                        vector<int> tags;
                        tags.push_back(0); // composite

                        // Read element node list
                        st >> id;
                        vector<NodeSharedPtr> nodeList;
                        for (int k = 0; k < 3; ++k)
                        {
                            int node = 0;
                            st >> node;
                            nodeList.push_back(m_mesh->m_node[node]);
                        }

                        // Create element
                        ElmtConfig conf(elType,1,false,false);
                        ElementSharedPtr E = GetElementFactory().
                            CreateInstance(elType,conf,nodeList,tags);

                        // Determine mesh expansion dimension
                        if (E->GetDim() > m_mesh->m_expDim)
                        {
                            m_mesh->m_expDim = E->GetDim();
                        }
                        m_mesh->m_element[E->GetDim()].push_back(E);
                    }
                }
            }
    }

    }
}
<commit_msg>Put in check for input format to be ascii<commit_after>////////////////////////////////////////////////////////////////////////////////
//
//  File: InputPly.cpp
//
//  For more information, please see: http://www.nektar.info/
//
//  The MIT License
//
//  Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
//  Department of Aeronautics, Imperial College London (UK), and Scientific
//  Computing and Imaging Institute, University of Utah (USA).
//
//  License for the specific language governing rights and limitations under
//  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.
//
//  Description: PLY converter.
//
////////////////////////////////////////////////////////////////////////////////

#include <string>
#include <iostream>
using namespace std;

#include "MeshElements.h"
#include "InputPly.h"

namespace Nektar
{
    namespace Utilities
    {
        ModuleKey InputPly::className =
            GetModuleFactory().RegisterCreatorFunction(
                ModuleKey(eInputModule, "ply"), InputPly::create,
                "Reads ply triangulation format.");

        InputPly::InputPly(MeshSharedPtr m) : InputModule(m)
        {

        }

        InputPly::~InputPly()
        {

        }

        /**
         *
         * @param   pFilename           Filename of Gmsh file to read.
         */
        void InputPly::Process()
        {

            // Open the file stream.
            OpenStream();

            ReadPly(m_mshFile);

            m_mshFile.close();

            ProcessVertices();
            ProcessEdges();
            ProcessFaces();
            ProcessElements();
            ProcessComposites();
        }

        void InputPly::ReadPly(std::ifstream &mshFile, NekDouble scale)
        {
            m_mesh->m_expDim = 0;
            string line;
            int nVertices = 0;
            int nEntities = 0;
            int nProperties = 0;
            LibUtilities::ShapeType elType = LibUtilities::eTriangle;
            map<string, int> propMap;

            if (m_mesh->m_verbose)
            {
                cout << "InputPly: Start reading file..." << endl;
            }

            while (!mshFile.eof())
            {
                getline(mshFile, line);
                stringstream s(line);
                string word;
                s >> word;
                if(word == "format")
                {
                    s >> word;
                    if(word != "ascii")
                    {
                        ASSERTL0(false,"InputPly file currently only set up to read ascii formatted ply files");
                    }
                }
                else if (word == "element")
                {
                    s >> word;
                    if (word == "vertex")
                    {
                        s >> nVertices;
                    }
                    else if (word == "face")
                    {
                        s >> nEntities;
                    }
                    continue;
                }
                else if (word == "property")
                {
                    s >> word >> word;
                    propMap[word] = nProperties++;
                }
                else if (word == "end_header")
                {
                    // Read nodes
                    vector<double> data(nProperties);
                    for (int i = 0; i < nVertices; ++i)
                    {
                        getline(mshFile, line);
                        stringstream st(line);

                        for (int j = 0; j < nProperties; ++j)
                        {
                            st >> data[j];
                        }

                        double x = data[propMap["x"]];
                        double y = data[propMap["y"]];
                        double z = data[propMap["z"]];

                        if ((y * y) > 0.000001 && m_mesh->m_spaceDim != 3)
                        {
                            m_mesh->m_spaceDim = 2;
                        }
                        if ((z * z) > 0.000001)
                        {
                            m_mesh->m_spaceDim = 3;
                        }

                        x *= scale;
                        y *= scale;
                        z *= scale;

                        m_mesh->m_node.push_back(
                            boost::shared_ptr<Node>(new Node(i, x, y, z)));

                        // Read vertex normals.
                        if (propMap.count("nx") > 0)
                        {
                            double nx = data[propMap["nx"]];
                            double ny = data[propMap["ny"]];
                            double nz = data[propMap["nz"]];
                            m_mesh->m_vertexNormals[i] = Node(0, nx, ny, nz);
                        }
                    }

                    // Read elements
                    for (int i = 0; i < nEntities; ++i)
                    {
                        getline(mshFile, line);
                        stringstream st(line);
                        int id = 0;

                        // Create element tags
                        vector<int> tags;
                        tags.push_back(0); // composite

                        // Read element node list
                        st >> id;
                        vector<NodeSharedPtr> nodeList;
                        for (int k = 0; k < 3; ++k)
                        {
                            int node = 0;
                            st >> node;
                            nodeList.push_back(m_mesh->m_node[node]);
                        }

                        // Create element
                        ElmtConfig conf(elType,1,false,false);
                        ElementSharedPtr E = GetElementFactory().
                            CreateInstance(elType,conf,nodeList,tags);

                        // Determine mesh expansion dimension
                        if (E->GetDim() > m_mesh->m_expDim)
                        {
                            m_mesh->m_expDim = E->GetDim();
                        }
                        m_mesh->m_element[E->GetDim()].push_back(E);
                    }
                }
            }
    }

    }
}
<|endoftext|>