<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: pyuno_impl.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-03-22 10:49:43 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _PYUNO_IMPL_
#define _PYUNO_IMPL_

#include <hash_map>
#include <hash_set>

#include <pyuno/pyuno.hxx>

#include <com/sun/star/beans/XIntrospection.hpp>
#include <com/sun/star/script/XTypeConverter.hpp>
#include <com/sun/star/script/XInvocation2.hpp>
#include <com/sun/star/script/XInvocationAdapterFactory2.hpp>

#include <com/sun/star/reflection/XIdlReflection.hpp>

#include <com/sun/star/container/XHierarchicalNameAccess.hpp>

#include <com/sun/star/lang/XUnoTunnel.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>

#include <cppuhelper/implbase2.hxx>
#include <cppuhelper/weakref.hxx>

namespace pyuno
{

//--------------------------------------------------
// Logging API - implementation can be found in pyuno_util
//--------------------------------------------------
struct RuntimeCargo;
namespace LogLevel
{
// when you add a loglevel, extend the log function !
static const sal_Int32 NONE = 0;
static const sal_Int32 CALL = 1;
static const sal_Int32 ARGS = 2;
}

bool isLog( RuntimeCargo *cargo, sal_Int32 loglevel );
void log( RuntimeCargo *cargo, sal_Int32 level, const rtl::OUString &logString );
void log( RuntimeCargo *cargo, sal_Int32 level, const char *str );
void logCall( RuntimeCargo *cargo, const char *intro,
              sal_Int64 ptr, const rtl::OUString & aFunctionName,
              const com::sun::star::uno::Sequence< com::sun::star::uno::Any > & args );
void logReply( RuntimeCargo *cargo, const char *intro,
              sal_Int64 ptr, const rtl::OUString & aFunctionName,
              const com::sun::star::uno::Any &returnValue,
              const com::sun::star::uno::Sequence< com::sun::star::uno::Any > & args );
void logException( RuntimeCargo *cargo, const char *intro,
                   sal_Int64 ptr, const rtl::OUString &aFunctionName,
                   const void * data, const com::sun::star::uno::Type & type );
static const sal_Int32 VAL2STR_MODE_DEEP = 0;
static const sal_Int32 VAL2STR_MODE_SHALLOW = 1;
rtl::OUString val2str( const void * pVal, typelib_TypeDescriptionReference * pTypeRef, sal_Int32 mode = VAL2STR_MODE_DEEP ) SAL_THROW( () );
//--------------------------------------------------

typedef ::std::hash_map
<
    PyRef,
    com::sun::star::uno::WeakReference< com::sun::star::script::XInvocation >,
    PyRef::Hash,
    std::equal_to< PyRef >
> PyRef2Adapter;

typedef ::std::hash_map
<
rtl::OUString,
PyRef,
rtl::OUStringHash,
std::equal_to<rtl::OUString>
> ExceptionClassMap;

typedef ::std::hash_map
<
    rtl::OUString,
    com::sun::star::uno::Sequence< sal_Int16 >,
    rtl::OUStringHash,
    std::equal_to< rtl::OUString >
> MethodOutIndexMap;

typedef ::std::hash_set< PyRef , PyRef::Hash , std::equal_to<PyRef> > ClassSet;

PyObject* PyUNO_new(
    const com::sun::star::uno::Any & targetInterface,
    const com::sun::star::uno::Reference<com::sun::star::lang::XSingleServiceFactory> & ssf);

PyObject* PyUNO_new_UNCHECKED (
    const com::sun::star::uno::Any & targetInterface,
    const com::sun::star::uno::Reference<com::sun::star::lang::XSingleServiceFactory> & ssf);

typedef struct
{
    com::sun::star::uno::Reference <com::sun::star::script::XInvocation2> xInvocation;
    com::sun::star::uno::Any wrappedObject;
} PyUNOInternals;

typedef struct
{
    PyObject_HEAD
    PyUNOInternals* members;
} PyUNO;

PyRef ustring2PyUnicode( const rtl::OUString &source );
PyRef ustring2PyString( const ::rtl::OUString & source );
rtl::OUString pyString2ustring( PyObject *str );

PyRef AnyToPyObject (const com::sun::star::uno::Any & a, const Runtime &r )
    throw ( com::sun::star::uno::RuntimeException );

com::sun::star::uno::Any PyObjectToAny (PyObject* o)
    throw ( com::sun::star::uno::RuntimeException );

void raiseInvocationTargetExceptionWhenNeeded( const Runtime &runtime )
    throw ( com::sun::star::reflection::InvocationTargetException );

// bool CheckPyObjectTypes (PyObject* o, Sequence<Type> types);
// bool CheckPyObjectType (PyObject* o, Type type); //Only check 1 object.

com::sun::star::uno::TypeClass StringToTypeClass (char* string);

PyRef PyUNO_callable_new (
    const com::sun::star::uno::Reference<com::sun::star::script::XInvocation2> &xInv,
    const rtl::OUString &methodName,
    const com::sun::star::uno::Reference<com::sun::star::lang::XSingleServiceFactory> &ssf,
    const com::sun::star::uno::Reference<com::sun::star::script::XTypeConverter> &tc,
    ConversionMode mode = REJECT_UNO_ANY );

PyObject* PyUNO_Type_new (const char *typeName , com::sun::star::uno::TypeClass t , const Runtime &r );
PyObject* PyUNO_Enum_new( const char *enumBase, const char *enumValue, const Runtime &r );
PyObject* PyUNO_char_new (sal_Unicode c , const Runtime &r);
PyObject *PyUNO_ByteSequence_new( const com::sun::star::uno::Sequence< sal_Int8 > &, const Runtime &r );

PyObject *importToGlobal( PyObject *typeName, PyObject *dict, PyObject *targetName );

PyRef getTypeClass( const Runtime &);
PyRef getEnumClass( const Runtime &);
PyRef getBoolClass( const Runtime &);
PyRef getCharClass( const Runtime &);
PyRef getByteSequenceClass( const Runtime & );
PyRef getPyUnoClass( const Runtime &);
PyRef getClass( const rtl::OUString & name , const Runtime & runtime );
PyRef getAnyClass( const Runtime &);
PyObject *PyUNO_invoke( PyObject *object, const char *name , PyObject *args );

com::sun::star::uno::Any PyEnum2Enum( PyObject *obj, const Runtime & r )
    throw ( com::sun::star::uno::RuntimeException );
sal_Bool PyBool2Bool( PyObject *o, const Runtime & r )
    throw ( com::sun::star::uno::RuntimeException );
sal_Unicode PyChar2Unicode( PyObject *o, const Runtime & r )
    throw ( com::sun::star::uno::RuntimeException );
com::sun::star::uno::Type PyType2Type( PyObject * o, const Runtime & r )
    throw( com::sun::star::uno::RuntimeException );

void raisePyExceptionWithAny( const com::sun::star::uno::Any &a );
const char *typeClassToString( com::sun::star::uno::TypeClass t );

PyRef getObjectFromUnoModule( const Runtime &runtime, const char * object )
    throw ( com::sun::star::uno::RuntimeException );

sal_Bool isInterfaceClass( const Runtime &, PyObject *obj );
sal_Bool isInstanceOfStructOrException( const Runtime & runtime, PyObject *obj);
com::sun::star::uno::Sequence<com::sun::star::uno::Type> implementsInterfaces(
    const Runtime & runtime, PyObject *obj );

struct RuntimeCargo
{
    com::sun::star::uno::Reference< com::sun::star::lang::XSingleServiceFactory > xInvocation;
    com::sun::star::uno::Reference< com::sun::star::script::XTypeConverter> xTypeConverter;
    com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext > xContext;
    com::sun::star::uno::Reference< com::sun::star::reflection::XIdlReflection > xCoreReflection;
    com::sun::star::uno::Reference< com::sun::star::container::XHierarchicalNameAccess > xTdMgr;
    com::sun::star::uno::Reference< com::sun::star::script::XInvocationAdapterFactory2 > xAdapterFactory;
    com::sun::star::uno::Reference< com::sun::star::beans::XIntrospection > xIntrospection;
    PyRef dictUnoModule;
    bool valid;
    ExceptionClassMap exceptionMap;
    ClassSet interfaceSet;
    PyRef2Adapter mappedObjects;
    FILE *logFile;
    sal_Int32 logLevel;

    PyRef getUnoModule();
};

struct stRuntimeImpl
{
    PyObject_HEAD
    struct RuntimeCargo *cargo;
public:
    static void del( PyObject *self );

    static PyRef create(
        const com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext > & xContext )
        throw ( com::sun::star::uno::RuntimeException );
};

class Adapter : public cppu::WeakImplHelper2<
    com::sun::star::script::XInvocation, com::sun::star::lang::XUnoTunnel >
{
    PyRef mWrappedObject;
    PyInterpreterState *mInterpreter;  // interpreters don't seem to be refcounted !
    com::sun::star::uno::Sequence< com::sun::star::uno::Type > mTypes;
    MethodOutIndexMap m_methodOutIndexMap;

private:
    com::sun::star::uno::Sequence< sal_Int16 > getOutIndexes( const rtl::OUString & functionName );

public:
public:
    Adapter( const PyRef &obj, const Runtime &,
             const com::sun::star::uno::Sequence< com::sun::star::uno::Type > & types );

    static com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();
    PyRef getWrappedObject() { return mWrappedObject; }
    com::sun::star::uno::Sequence< com::sun::star::uno::Type > getWrappedTypes() { return mTypes; }
    virtual ~Adapter();

    // XInvocation
    virtual com::sun::star::uno::Reference< ::com::sun::star::beans::XIntrospectionAccess >
           SAL_CALL getIntrospection(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL invoke(
        const ::rtl::OUString& aFunctionName,
        const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aParams,
        ::com::sun::star::uno::Sequence< sal_Int16 >& aOutParamIndex,
        ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aOutParam )
        throw (::com::sun::star::lang::IllegalArgumentException,
               ::com::sun::star::script::CannotConvertException,
               ::com::sun::star::reflection::InvocationTargetException,
               ::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL setValue(
        const ::rtl::OUString& aPropertyName,
        const ::com::sun::star::uno::Any& aValue )
        throw (::com::sun::star::beans::UnknownPropertyException,
               ::com::sun::star::script::CannotConvertException,
               ::com::sun::star::reflection::InvocationTargetException,
               ::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Any SAL_CALL getValue( const ::rtl::OUString& aPropertyName )
        throw (::com::sun::star::beans::UnknownPropertyException,
               ::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL hasMethod( const ::rtl::OUString& aName )
        throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL hasProperty( const ::rtl::OUString& aName )
        throw (::com::sun::star::uno::RuntimeException);

    // XUnoTunnel
    virtual sal_Int64 SAL_CALL getSomething(
        const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier )
        throw (::com::sun::star::uno::RuntimeException);
};

/** releases a refcount on the interpreter object and on another given python object.

   The function can be called from any thread regardless of whether the global
   interpreter lock is held.

 */
void decreaseRefCount( PyInterpreterState *interpreter, PyObject *object );

}

#endif
<commit_msg>INTEGRATION: CWS warnings01 (1.3.44); FILE MERGED 2006/04/20 14:46:09 sb 1.3.44.5: #i53898# Made code warning-free again after resync to SRC680m162. 2006/04/07 21:24:23 sb 1.3.44.4: RESYNC: (1.4-1.5); FILE MERGED 2006/03/01 10:01:16 sb 1.3.44.3: #i53898# Made code waring-free. 2005/09/23 02:08:50 sb 1.3.44.2: RESYNC: (1.3-1.4); FILE MERGED 2005/09/09 15:31:19 sb 1.3.44.1: #i53898# Made code warning-free.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: pyuno_impl.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 05:03:59 $
 *
 *  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 _PYUNO_IMPL_
#define _PYUNO_IMPL_

#include <pyuno/pyuno.hxx>

#include <hash_map>
#include <hash_set>

#include <com/sun/star/beans/XIntrospection.hpp>
#include <com/sun/star/script/XTypeConverter.hpp>
#include <com/sun/star/script/XInvocation2.hpp>
#include <com/sun/star/script/XInvocationAdapterFactory2.hpp>

#include <com/sun/star/reflection/XIdlReflection.hpp>

#include <com/sun/star/container/XHierarchicalNameAccess.hpp>

#include <com/sun/star/lang/XUnoTunnel.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>

#include <cppuhelper/implbase2.hxx>
#include <cppuhelper/weakref.hxx>

namespace pyuno
{

//--------------------------------------------------
// Logging API - implementation can be found in pyuno_util
//--------------------------------------------------
struct RuntimeCargo;
namespace LogLevel
{
// when you add a loglevel, extend the log function !
static const sal_Int32 NONE = 0;
static const sal_Int32 CALL = 1;
static const sal_Int32 ARGS = 2;
}

bool isLog( RuntimeCargo *cargo, sal_Int32 loglevel );
void log( RuntimeCargo *cargo, sal_Int32 level, const rtl::OUString &logString );
void log( RuntimeCargo *cargo, sal_Int32 level, const char *str );
void logCall( RuntimeCargo *cargo, const char *intro,
              void * ptr, const rtl::OUString & aFunctionName,
              const com::sun::star::uno::Sequence< com::sun::star::uno::Any > & args );
void logReply( RuntimeCargo *cargo, const char *intro,
              void * ptr, const rtl::OUString & aFunctionName,
              const com::sun::star::uno::Any &returnValue,
              const com::sun::star::uno::Sequence< com::sun::star::uno::Any > & args );
void logException( RuntimeCargo *cargo, const char *intro,
                   void * ptr, const rtl::OUString &aFunctionName,
                   const void * data, const com::sun::star::uno::Type & type );
static const sal_Int32 VAL2STR_MODE_DEEP = 0;
static const sal_Int32 VAL2STR_MODE_SHALLOW = 1;
rtl::OUString val2str( const void * pVal, typelib_TypeDescriptionReference * pTypeRef, sal_Int32 mode = VAL2STR_MODE_DEEP ) SAL_THROW( () );
//--------------------------------------------------

typedef ::std::hash_map
<
    PyRef,
    com::sun::star::uno::WeakReference< com::sun::star::script::XInvocation >,
    PyRef::Hash,
    std::equal_to< PyRef >
> PyRef2Adapter;

typedef ::std::hash_map
<
rtl::OUString,
PyRef,
rtl::OUStringHash,
std::equal_to<rtl::OUString>
> ExceptionClassMap;

typedef ::std::hash_map
<
    rtl::OUString,
    com::sun::star::uno::Sequence< sal_Int16 >,
    rtl::OUStringHash,
    std::equal_to< rtl::OUString >
> MethodOutIndexMap;

typedef ::std::hash_set< PyRef , PyRef::Hash , std::equal_to<PyRef> > ClassSet;

PyObject* PyUNO_new(
    const com::sun::star::uno::Any & targetInterface,
    const com::sun::star::uno::Reference<com::sun::star::lang::XSingleServiceFactory> & ssf);

PyObject* PyUNO_new_UNCHECKED (
    const com::sun::star::uno::Any & targetInterface,
    const com::sun::star::uno::Reference<com::sun::star::lang::XSingleServiceFactory> & ssf);

typedef struct
{
    com::sun::star::uno::Reference <com::sun::star::script::XInvocation2> xInvocation;
    com::sun::star::uno::Any wrappedObject;
} PyUNOInternals;

typedef struct
{
    PyObject_HEAD
    PyUNOInternals* members;
} PyUNO;

PyRef ustring2PyUnicode( const rtl::OUString &source );
PyRef ustring2PyString( const ::rtl::OUString & source );
rtl::OUString pyString2ustring( PyObject *str );

PyRef AnyToPyObject (const com::sun::star::uno::Any & a, const Runtime &r )
    throw ( com::sun::star::uno::RuntimeException );

com::sun::star::uno::Any PyObjectToAny (PyObject* o)
    throw ( com::sun::star::uno::RuntimeException );

void raiseInvocationTargetExceptionWhenNeeded( const Runtime &runtime )
    throw ( com::sun::star::reflection::InvocationTargetException );

// bool CheckPyObjectTypes (PyObject* o, Sequence<Type> types);
// bool CheckPyObjectType (PyObject* o, Type type); //Only check 1 object.

com::sun::star::uno::TypeClass StringToTypeClass (char* string);

PyRef PyUNO_callable_new (
    const com::sun::star::uno::Reference<com::sun::star::script::XInvocation2> &xInv,
    const rtl::OUString &methodName,
    const com::sun::star::uno::Reference<com::sun::star::lang::XSingleServiceFactory> &ssf,
    const com::sun::star::uno::Reference<com::sun::star::script::XTypeConverter> &tc,
    ConversionMode mode = REJECT_UNO_ANY );

PyObject* PyUNO_Type_new (const char *typeName , com::sun::star::uno::TypeClass t , const Runtime &r );
PyObject* PyUNO_Enum_new( const char *enumBase, const char *enumValue, const Runtime &r );
PyObject* PyUNO_char_new (sal_Unicode c , const Runtime &r);
PyObject *PyUNO_ByteSequence_new( const com::sun::star::uno::Sequence< sal_Int8 > &, const Runtime &r );

PyObject *importToGlobal( PyObject *typeName, PyObject *dict, PyObject *targetName );

PyRef getTypeClass( const Runtime &);
PyRef getEnumClass( const Runtime &);
PyRef getBoolClass( const Runtime &);
PyRef getCharClass( const Runtime &);
PyRef getByteSequenceClass( const Runtime & );
PyRef getPyUnoClass( const Runtime &);
PyRef getClass( const rtl::OUString & name , const Runtime & runtime );
PyRef getAnyClass( const Runtime &);
PyObject *PyUNO_invoke( PyObject *object, const char *name , PyObject *args );

com::sun::star::uno::Any PyEnum2Enum( PyObject *obj )
    throw ( com::sun::star::uno::RuntimeException );
sal_Bool PyBool2Bool( PyObject *o, const Runtime & r )
    throw ( com::sun::star::uno::RuntimeException );
sal_Unicode PyChar2Unicode( PyObject *o )
    throw ( com::sun::star::uno::RuntimeException );
com::sun::star::uno::Type PyType2Type( PyObject * o )
    throw( com::sun::star::uno::RuntimeException );

void raisePyExceptionWithAny( const com::sun::star::uno::Any &a );
const char *typeClassToString( com::sun::star::uno::TypeClass t );

PyRef getObjectFromUnoModule( const Runtime &runtime, const char * object )
    throw ( com::sun::star::uno::RuntimeException );

sal_Bool isInterfaceClass( const Runtime &, PyObject *obj );
bool isInstanceOfStructOrException( PyObject *obj);
com::sun::star::uno::Sequence<com::sun::star::uno::Type> implementsInterfaces(
    const Runtime & runtime, PyObject *obj );

struct RuntimeCargo
{
    com::sun::star::uno::Reference< com::sun::star::lang::XSingleServiceFactory > xInvocation;
    com::sun::star::uno::Reference< com::sun::star::script::XTypeConverter> xTypeConverter;
    com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext > xContext;
    com::sun::star::uno::Reference< com::sun::star::reflection::XIdlReflection > xCoreReflection;
    com::sun::star::uno::Reference< com::sun::star::container::XHierarchicalNameAccess > xTdMgr;
    com::sun::star::uno::Reference< com::sun::star::script::XInvocationAdapterFactory2 > xAdapterFactory;
    com::sun::star::uno::Reference< com::sun::star::beans::XIntrospection > xIntrospection;
    PyRef dictUnoModule;
    bool valid;
    ExceptionClassMap exceptionMap;
    ClassSet interfaceSet;
    PyRef2Adapter mappedObjects;
    FILE *logFile;
    sal_Int32 logLevel;

    PyRef getUnoModule();
};

struct stRuntimeImpl
{
    PyObject_HEAD
    struct RuntimeCargo *cargo;
public:
    static void del( PyObject *self );

    static PyRef create(
        const com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext > & xContext )
        throw ( com::sun::star::uno::RuntimeException );
};

class Adapter : public cppu::WeakImplHelper2<
    com::sun::star::script::XInvocation, com::sun::star::lang::XUnoTunnel >
{
    PyRef mWrappedObject;
    PyInterpreterState *mInterpreter;  // interpreters don't seem to be refcounted !
    com::sun::star::uno::Sequence< com::sun::star::uno::Type > mTypes;
    MethodOutIndexMap m_methodOutIndexMap;

private:
    com::sun::star::uno::Sequence< sal_Int16 > getOutIndexes( const rtl::OUString & functionName );

public:
public:
    Adapter( const PyRef &obj,
             const com::sun::star::uno::Sequence< com::sun::star::uno::Type > & types );

    static com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();
    PyRef getWrappedObject() { return mWrappedObject; }
    com::sun::star::uno::Sequence< com::sun::star::uno::Type > getWrappedTypes() { return mTypes; }
    virtual ~Adapter();

    // XInvocation
    virtual com::sun::star::uno::Reference< ::com::sun::star::beans::XIntrospectionAccess >
           SAL_CALL getIntrospection(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL invoke(
        const ::rtl::OUString& aFunctionName,
        const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aParams,
        ::com::sun::star::uno::Sequence< sal_Int16 >& aOutParamIndex,
        ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aOutParam )
        throw (::com::sun::star::lang::IllegalArgumentException,
               ::com::sun::star::script::CannotConvertException,
               ::com::sun::star::reflection::InvocationTargetException,
               ::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL setValue(
        const ::rtl::OUString& aPropertyName,
        const ::com::sun::star::uno::Any& aValue )
        throw (::com::sun::star::beans::UnknownPropertyException,
               ::com::sun::star::script::CannotConvertException,
               ::com::sun::star::reflection::InvocationTargetException,
               ::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Any SAL_CALL getValue( const ::rtl::OUString& aPropertyName )
        throw (::com::sun::star::beans::UnknownPropertyException,
               ::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL hasMethod( const ::rtl::OUString& aName )
        throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL hasProperty( const ::rtl::OUString& aName )
        throw (::com::sun::star::uno::RuntimeException);

    // XUnoTunnel
    virtual sal_Int64 SAL_CALL getSomething(
        const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier )
        throw (::com::sun::star::uno::RuntimeException);
};

/** releases a refcount on the interpreter object and on another given python object.

   The function can be called from any thread regardless of whether the global
   interpreter lock is held.

 */
void decreaseRefCount( PyInterpreterState *interpreter, PyObject *object );

}

#endif
<|endoftext|>


<commit_before>//-----------------------------------------------
//
//	This file is part of the Siv3D Engine.
//
//	Copyright (c) 2008-2021 Ryo Suzuki
//	Copyright (c) 2016-2021 OpenSiv3D Project
//
//	Licensed under the MIT License.
//
//-----------------------------------------------

# include <Siv3D/RectanglePacking.hpp>
# include <rectpack2D/finders_interface.h>

namespace s3d
{
	namespace detail
	{
		template <bool AllowFlip>
		[[nodiscard]]
		RectanglePack Pack(const Array<Rect>& rects, const int32 maxSide)
		{
			constexpr int32 DiscardStep = 1;
			using SpacesType = rectpack2D::empty_spaces<AllowFlip, rectpack2D::default_empty_spaces>;
			using RectType = rectpack2D::output_rect_t<SpacesType>;
			auto reportSuccessful = [](RectType&) {
				return rectpack2D::callback_result::CONTINUE_PACKING;
			};
			auto reportUnsuccessful = [](RectType&) {
				return rectpack2D::callback_result::ABORT_PACKING;
			};

			std::vector<RectType> rectangles(rects.size());
			{
				for (size_t i = 0; i < rects.size(); ++i)
				{
					const auto& rect = rects[i];
					rectangles[i] = rectpack2D::rect_xywh(0, 0, rect.w, rect.h);
				}
			}

			const auto resultSize = rectpack2D::find_best_packing<SpacesType>(
				rectangles,
				make_finder_input(
					maxSide,
					DiscardStep,
					reportSuccessful,
					reportUnsuccessful,
					(AllowFlip ? rectpack2D::flipping_option::ENABLED : rectpack2D::flipping_option::DISABLED)));

			Array<Rect> results(rectangles.size());
			{
				for (size_t i = 0; i < rectangles.size(); ++i)
				{
					const auto& r = rectangles[i];
					results[i].set(r.x, r.y, r.w, r.h);
				}
			}

			return{ results, Size{ resultSize.w, resultSize.h } };
		}
	}

	namespace RectanglePacking
	{
		RectanglePack Pack(const Array<Rect>& rects, const int32 maxSide, const AllowFlip allowFlip)
		{
			if (allowFlip)
			{
				return detail::Pack<true>(rects, maxSide);
			}
			else
			{
				return detail::Pack<false>(rects, maxSide);
			}
		}
	}
}
<commit_msg>[共通] fix<commit_after>//-----------------------------------------------
//
//	This file is part of the Siv3D Engine.
//
//	Copyright (c) 2008-2021 Ryo Suzuki
//	Copyright (c) 2016-2021 OpenSiv3D Project
//
//	Licensed under the MIT License.
//
//-----------------------------------------------

# include <Siv3D/RectanglePacking.hpp>
# include <ThirdParty/rectpack2D/finders_interface.h>

namespace s3d
{
	namespace detail
	{
		template <bool AllowFlip>
		[[nodiscard]]
		RectanglePack Pack(const Array<Rect>& rects, const int32 maxSide)
		{
			constexpr int32 DiscardStep = 1;
			using SpacesType = rectpack2D::empty_spaces<AllowFlip, rectpack2D::default_empty_spaces>;
			using RectType = rectpack2D::output_rect_t<SpacesType>;
			auto reportSuccessful = [](RectType&) {
				return rectpack2D::callback_result::CONTINUE_PACKING;
			};
			auto reportUnsuccessful = [](RectType&) {
				return rectpack2D::callback_result::ABORT_PACKING;
			};

			std::vector<RectType> rectangles(rects.size());
			{
				for (size_t i = 0; i < rects.size(); ++i)
				{
					const auto& rect = rects[i];
					rectangles[i] = rectpack2D::rect_xywh(0, 0, rect.w, rect.h);
				}
			}

			const auto resultSize = rectpack2D::find_best_packing<SpacesType>(
				rectangles,
				make_finder_input(
					maxSide,
					DiscardStep,
					reportSuccessful,
					reportUnsuccessful,
					(AllowFlip ? rectpack2D::flipping_option::ENABLED : rectpack2D::flipping_option::DISABLED)));

			Array<Rect> results(rectangles.size());
			{
				for (size_t i = 0; i < rectangles.size(); ++i)
				{
					const auto& r = rectangles[i];
					results[i].set(r.x, r.y, r.w, r.h);
				}
			}

			return{ results, Size{ resultSize.w, resultSize.h } };
		}
	}

	namespace RectanglePacking
	{
		RectanglePack Pack(const Array<Rect>& rects, const int32 maxSide, const AllowFlip allowFlip)
		{
			if (allowFlip)
			{
				return detail::Pack<true>(rects, maxSide);
			}
			else
			{
				return detail::Pack<false>(rects, maxSide);
			}
		}
	}
}
<|endoftext|>


<commit_before>#ifndef LEDBUTTON_HPP_
#define LEDBUTTON_HPP_

/*
 *	Device code for sparkfun LED button
 *  Really simple, its just an LED and a button in one
 */

#include "../lib/Device.hpp"
#include "DigitalDevice.hpp"

class LEDButton : public Device {
private:
	const int led;
	const int button;
public:
	LEDButton(String name, int port_led, int port_button);
	virtual ~LEDButton();

	void setLED(int value);
	int read() const;
};

#endif
<commit_msg>remaining include of removed digitaldevice<commit_after>#ifndef LEDBUTTON_HPP_
#define LEDBUTTON_HPP_

/*
 *	Device code for sparkfun LED button
 *  Really simple, its just an LED and a button in one
 */

#include "../lib/Device.hpp"

class LEDButton : public Device {
private:
	const int led;
	const int button;
public:
	LEDButton(String name, int port_led, int port_button);
	virtual ~LEDButton();

	void setLED(int value);
	int read() const;
};

#endif
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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 "itkTBBMultiThreader.h"
#include "itkNumericTraits.h"
#include "itkProcessObject.h"
#include <iostream>
#include <atomic>
#include <thread>
#include "tbb/parallel_for.h"
#include "tbb/task_scheduler_init.h"

namespace itk
{

TBBMultiThreader::TBBMultiThreader()
{
  ThreadIdType defaultThreads = std::max( 1u, GetGlobalDefaultNumberOfThreads() );
#if defined( ITKV4_COMPATIBILITY )
  m_NumberOfWorkUnits = defaultThreads;
#else
  m_NumberOfWorkUnits = 16 * defaultThreads;
#endif
}

TBBMultiThreader::~TBBMultiThreader()
{
}

void TBBMultiThreader::SetSingleMethod(ThreadFunctionType f, void *data)
{
  m_SingleMethod = f;
  m_SingleData   = data;
}

void TBBMultiThreader::SingleMethodExecute()
{
  if( !m_SingleMethod )
    {
    itkExceptionMacro(<< "No single method set!");
    }

  tbb::task_scheduler_init tbb_init( m_MaximumNumberOfThreads );
  //we request grain size of 1 and simple_partitioner to ensure there is no chunking
  tbb::parallel_for(tbb::blocked_range<int>(0, m_NumberOfWorkUnits, 1), [&](tbb::blocked_range<int>r)
    {
    // Make sure that TBB did not call us with a block of work units
    // but rather with only one work unit to handle
    itkAssertInDebugAndIgnoreInReleaseMacro(r.begin() + 1 == r.end());

    WorkUnitInfo ti;
    ti.WorkUnitID = r.begin();
    ti.UserData = m_SingleData;
    ti.NumberOfWorkUnits = m_NumberOfWorkUnits;
    m_SingleMethod(&ti); //TBB takes care of properly propagating exceptions
    },
      tbb::simple_partitioner());
}

void TBBMultiThreader::SetNumberOfWorkUnits(ThreadIdType numberOfWorkUnits)
{
  m_NumberOfWorkUnits = std::max( 1u, numberOfWorkUnits );
}

void TBBMultiThreader::PrintSelf(std::ostream & os, Indent indent) const
{
  Superclass::PrintSelf(os, indent);
}

void
TBBMultiThreader
::ParallelizeArray(
  SizeValueType firstIndex,
  SizeValueType lastIndexPlus1,
  ArrayThreadingFunctorType aFunc,
  ProcessObject* filter )
{
  MultiThreaderBase::HandleFilterProgress(filter, 0.0f);

  if ( firstIndex + 1 < lastIndexPlus1 )
    {
    unsigned count = lastIndexPlus1 - firstIndex;
    std::atomic< SizeValueType > progress( 0 );
    std::thread::id callingThread = std::this_thread::get_id();
    tbb::task_scheduler_init tbb_init( m_MaximumNumberOfThreads );
    //we request grain size of 1 and simple_partitioner to ensure there is no chunking
    tbb::parallel_for(
        tbb::blocked_range<SizeValueType>(firstIndex, lastIndexPlus1, 1),
        [&](tbb::blocked_range<SizeValueType>r)
        {
        // Make sure that TBB did not call us with a block of "threads"
        // but rather with only one "thread" to handle
        itkAssertInDebugAndIgnoreInReleaseMacro(r.begin() + 1 == r.end());
        MultiThreaderBase::HandleFilterProgress(filter);

        aFunc( r.begin() ); //invoke the function

        if ( filter )
          {
          ++progress;
          //make sure we are updating progress only from the thead which invoked us
          if ( callingThread == std::this_thread::get_id() )
            {
            filter->UpdateProgress( float( progress ) / count );
            }
          }
        },
        tbb::simple_partitioner());
    }
  else if ( firstIndex + 1 == lastIndexPlus1 )
    {
    aFunc( firstIndex );
    }
  // else nothing needs to be executed

  MultiThreaderBase::HandleFilterProgress(filter, 1.0f);
}

}

namespace
{
struct TBBImageRegionSplitter : public itk::ImageIORegion
{
  static const bool is_splittable_in_proportion = true;
  TBBImageRegionSplitter(const TBBImageRegionSplitter&) = default;
  TBBImageRegionSplitter(const itk::ImageIORegion& region)
      :itk::ImageIORegion(region) //use itk::ImageIORegion's copy constructor
  {}
  TBBImageRegionSplitter(TBBImageRegionSplitter& region, tbb::split)
      :TBBImageRegionSplitter(region, tbb::proportional_split(1, 1)) //delegate to proportional split
  {}

  TBBImageRegionSplitter(TBBImageRegionSplitter& region, tbb::proportional_split p)
  {
    *this = region; //most things will be the same
    for (int d = int(this->GetImageDimension()) - 1; d >= 0; d--) //prefer to split along highest dimension
      {
      if (this->GetSize(d) > 1) //split along this dimension
        {
        size_t myP = (this->GetSize(d) * p.right()) / (p.left() + p.right());
        if (myP == 0)
          {
          ++myP;
          }
        else if (myP == this->GetSize(d))
          {
          --myP;
          }
        this->SetSize(d, myP);
        region.SetSize(d, region.GetSize(d) - myP);
        region.SetIndex(d, myP + region.GetIndex(d));
        return;
        }
      }
    itkGenericExceptionMacro("An ImageIORegion could not be split. Region: " << region);
  }

  bool empty() const
  {
    for (unsigned d = 0; d < this->GetImageDimension(); d++)
      {
      if (this->GetSize(d) == 0)
        {
        return true;
        }
      }
    return false;
  }

  bool is_divisible() const
  {
    for (unsigned d = 0; d < this->GetImageDimension(); d++)
      {
      if (this->GetSize(d) > 1)
        {
        return true;
        }
      }
    return false;
  }

};//TBBImageRegionSplitter struct definition
}//anonymous namespace

namespace itk
{
void TBBMultiThreader
::ParallelizeImageRegion(
    unsigned int dimension,
    const IndexValueType index[],
    const SizeValueType size[],
    ThreadingFunctorType funcP,
    ProcessObject* filter)
{
  MultiThreaderBase::HandleFilterProgress(filter, 0.0f);

  if (m_NumberOfWorkUnits == 1) //no multi-threading wanted
    {
    funcP(index, size);
    }
  else //normal multi-threading
    {
    ImageIORegion region(dimension);
    for (unsigned d = 0; d < dimension; d++)
      {
      region.SetIndex(d, index[d]);
      region.SetSize(d, size[d]);
      }
    TBBImageRegionSplitter regionSplitter = region; //use copy constructor

    std::atomic<SizeValueType> pixelProgress = { 0 };
    SizeValueType totalCount = region.GetNumberOfPixels();
    std::thread::id callingThread = std::this_thread::get_id();
    tbb::task_scheduler_init tbb_init( m_MaximumNumberOfThreads );
    tbb::parallel_for(regionSplitter, [&](TBBImageRegionSplitter regionToProcess)
      {
      MultiThreaderBase::HandleFilterProgress(filter);
      funcP(&regionToProcess.GetIndex()[0], &regionToProcess.GetSize()[0]);
      if (filter) //filter is provided, update progress
        {
        SizeValueType pixelCount = regionToProcess.GetNumberOfPixels();
        pixelProgress += pixelCount;
        //make sure we are updating progress only from the thead which invoked filter->Update();
        if (callingThread == std::this_thread::get_id())
          {
          filter->UpdateProgress(float(pixelProgress) / totalCount);
          }
        }
      }); //we implicitly use auto_partitioner for load balancing
    }

  MultiThreaderBase::HandleFilterProgress(filter, 1.0f);
}
}
<commit_msg>COMP: Remove unused static variable warning<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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 "itkTBBMultiThreader.h"
#include "itkNumericTraits.h"
#include "itkProcessObject.h"
#include <iostream>
#include <atomic>
#include <thread>
#include "tbb/parallel_for.h"
#include "tbb/task_scheduler_init.h"

namespace itk
{

TBBMultiThreader::TBBMultiThreader()
{
  ThreadIdType defaultThreads = std::max( 1u, GetGlobalDefaultNumberOfThreads() );
#if defined( ITKV4_COMPATIBILITY )
  m_NumberOfWorkUnits = defaultThreads;
#else
  m_NumberOfWorkUnits = 16 * defaultThreads;
#endif
}

TBBMultiThreader::~TBBMultiThreader()
{
}

void TBBMultiThreader::SetSingleMethod(ThreadFunctionType f, void *data)
{
  m_SingleMethod = f;
  m_SingleData   = data;
}

void TBBMultiThreader::SingleMethodExecute()
{
  if( !m_SingleMethod )
    {
    itkExceptionMacro(<< "No single method set!");
    }

  tbb::task_scheduler_init tbb_init( m_MaximumNumberOfThreads );
  //we request grain size of 1 and simple_partitioner to ensure there is no chunking
  tbb::parallel_for(tbb::blocked_range<int>(0, m_NumberOfWorkUnits, 1), [&](tbb::blocked_range<int>r)
    {
    // Make sure that TBB did not call us with a block of work units
    // but rather with only one work unit to handle
    itkAssertInDebugAndIgnoreInReleaseMacro(r.begin() + 1 == r.end());

    WorkUnitInfo ti;
    ti.WorkUnitID = r.begin();
    ti.UserData = m_SingleData;
    ti.NumberOfWorkUnits = m_NumberOfWorkUnits;
    m_SingleMethod(&ti); //TBB takes care of properly propagating exceptions
    },
      tbb::simple_partitioner());
}

void TBBMultiThreader::SetNumberOfWorkUnits(ThreadIdType numberOfWorkUnits)
{
  m_NumberOfWorkUnits = std::max( 1u, numberOfWorkUnits );
}

void TBBMultiThreader::PrintSelf(std::ostream & os, Indent indent) const
{
  Superclass::PrintSelf(os, indent);
}

void
TBBMultiThreader
::ParallelizeArray(
  SizeValueType firstIndex,
  SizeValueType lastIndexPlus1,
  ArrayThreadingFunctorType aFunc,
  ProcessObject* filter )
{
  MultiThreaderBase::HandleFilterProgress(filter, 0.0f);

  if ( firstIndex + 1 < lastIndexPlus1 )
    {
    unsigned count = lastIndexPlus1 - firstIndex;
    std::atomic< SizeValueType > progress( 0 );
    std::thread::id callingThread = std::this_thread::get_id();
    tbb::task_scheduler_init tbb_init( m_MaximumNumberOfThreads );
    //we request grain size of 1 and simple_partitioner to ensure there is no chunking
    tbb::parallel_for(
        tbb::blocked_range<SizeValueType>(firstIndex, lastIndexPlus1, 1),
        [&](tbb::blocked_range<SizeValueType>r)
        {
        // Make sure that TBB did not call us with a block of "threads"
        // but rather with only one "thread" to handle
        itkAssertInDebugAndIgnoreInReleaseMacro(r.begin() + 1 == r.end());
        MultiThreaderBase::HandleFilterProgress(filter);

        aFunc( r.begin() ); //invoke the function

        if ( filter )
          {
          ++progress;
          //make sure we are updating progress only from the thead which invoked us
          if ( callingThread == std::this_thread::get_id() )
            {
            filter->UpdateProgress( float( progress ) / count );
            }
          }
        },
        tbb::simple_partitioner());
    }
  else if ( firstIndex + 1 == lastIndexPlus1 )
    {
    aFunc( firstIndex );
    }
  // else nothing needs to be executed

  MultiThreaderBase::HandleFilterProgress(filter, 1.0f);
}

}

namespace
{
struct TBBImageRegionSplitter : public itk::ImageIORegion
{
  // Optional. If true, the proportional splitting constructor
  // is defined for the range and may be used by parallel algorithms.
  // https://software.intel.com/en-us/node/506143
  // This variable must exist for tbb to properly identify and use this
  // specialization.
  static constexpr bool is_splittable_in_proportion = true;
  TBBImageRegionSplitter(const TBBImageRegionSplitter&) = default;
  TBBImageRegionSplitter(const itk::ImageIORegion& region)
      :itk::ImageIORegion(region) //use itk::ImageIORegion's copy constructor
  {}
  TBBImageRegionSplitter(TBBImageRegionSplitter& region, tbb::split)
      :TBBImageRegionSplitter(region, tbb::proportional_split(1, 1)) //delegate to proportional split
  {}

  TBBImageRegionSplitter(TBBImageRegionSplitter& region, tbb::proportional_split p)
  {
    // The following if statement is primarily used to ensure use of
    // is_splittable_in_proportion to avoid unused variable warning.
    if( TBBImageRegionSplitter::is_splittable_in_proportion == true )
    {
      *this = region; //most things will be the same
      for (int d = int(this->GetImageDimension()) - 1; d >= 0; d--) //prefer to split along highest dimension
        {
        if (this->GetSize(d) > 1) //split along this dimension
          {
          size_t myP = (this->GetSize(d) * p.right()) / (p.left() + p.right());
          if (myP == 0)
            {
            ++myP;
            }
          else if (myP == this->GetSize(d))
            {
            --myP;
            }
          this->SetSize(d, myP);
          region.SetSize(d, region.GetSize(d) - myP);
          region.SetIndex(d, myP + region.GetIndex(d));
          return;
          }
        }
    }
    itkGenericExceptionMacro("An ImageIORegion could not be split. Region: " << region);
  }

  bool empty() const
  {
    for (unsigned d = 0; d < this->GetImageDimension(); d++)
      {
      if (this->GetSize(d) == 0)
        {
        return true;
        }
      }
    return false;
  }

  bool is_divisible() const
  {
    for (unsigned d = 0; d < this->GetImageDimension(); d++)
      {
      if (this->GetSize(d) > 1)
        {
        return true;
        }
      }
    return false;
  }

};//TBBImageRegionSplitter struct definition
}//anonymous namespace

namespace itk
{
void TBBMultiThreader
::ParallelizeImageRegion(
    unsigned int dimension,
    const IndexValueType index[],
    const SizeValueType size[],
    ThreadingFunctorType funcP,
    ProcessObject* filter)
{
  MultiThreaderBase::HandleFilterProgress(filter, 0.0f);

  if (m_NumberOfWorkUnits == 1) //no multi-threading wanted
    {
    funcP(index, size);
    }
  else //normal multi-threading
    {
    ImageIORegion region(dimension);
    for (unsigned d = 0; d < dimension; d++)
      {
      region.SetIndex(d, index[d]);
      region.SetSize(d, size[d]);
      }
    TBBImageRegionSplitter regionSplitter = region; //use copy constructor

    std::atomic<SizeValueType> pixelProgress = { 0 };
    SizeValueType totalCount = region.GetNumberOfPixels();
    std::thread::id callingThread = std::this_thread::get_id();
    tbb::task_scheduler_init tbb_init( m_MaximumNumberOfThreads );
    tbb::parallel_for(regionSplitter, [&](TBBImageRegionSplitter regionToProcess)
      {
      MultiThreaderBase::HandleFilterProgress(filter);
      funcP(&regionToProcess.GetIndex()[0], &regionToProcess.GetSize()[0]);
      if (filter) //filter is provided, update progress
        {
        SizeValueType pixelCount = regionToProcess.GetNumberOfPixels();
        pixelProgress += pixelCount;
        //make sure we are updating progress only from the thead which invoked filter->Update();
        if (callingThread == std::this_thread::get_id())
          {
          filter->UpdateProgress(float(pixelProgress) / totalCount);
          }
        }
      }); //we implicitly use auto_partitioner for load balancing
    }

  MultiThreaderBase::HandleFilterProgress(filter, 1.0f);
}
}
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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 "itkImageRegionIterator.h"
#include "itkShrinkImageFilter.h"
#include "itkImportImageFilter.h"

int itkImportImageTest(int, char* [] )
{
  // Create a C-array to hold an image
  short *rawImage = new short[8*12];
  for (int i=0; i < 8*12; i++)
    {
    rawImage[i] = i;
    }

  // typdefs to simplify the syntax
  typedef itk::ImportImageFilter<short, 2> ImportImageFilter;
  typedef itk::Image<short, 2>             ShortImage;
  // Create an ImportImageFilter filter
  ImportImageFilter::Pointer import;
  import = ImportImageFilter::New();

  itk::ImageRegion<2>         region;
  itk::ImageRegion<2>::IndexType  index = {{0, 0}};
  itk::ImageRegion<2>::SizeType   size = {{8, 12}};

  region.SetSize( size );
  region.SetIndex( index );

  import->SetRegion( region );
  import->SetImportPointer( rawImage, 8*12, true);

  // Create another filter
  itk::ShrinkImageFilter<ImportImageFilter::OutputImageType, ShortImage >::Pointer shrink;
  shrink = itk::ShrinkImageFilter<ImportImageFilter::OutputImageType, ShortImage>::New();
  shrink->SetInput( import->GetOutput() );
  shrink->SetShrinkFactors(2); //Also tested with factors 3 and 4, with 12x12 image
  try
    {
    shrink->Update();
    }
  catch (itk::ExceptionObject& e)
    {
    std::cerr << "Exception detected: "  << e.GetDescription();
    return EXIT_FAILURE;
    }

  // Test the SetVectorMacros and GetVectorMacros
  const itk::SpacePrecisionType data[2] = {1.0,1.0};
  import->SetSpacing(data);

  const float data2[2] = {1.0,1.0};
  import->SetSpacing(data2);

  const itk::SpacePrecisionType * spacingValue = import->GetSpacing().GetDataPointer();
  std::cout << "import->GetSpacing(): " << spacingValue << std::endl;

  const double data3[2] = {1.0,1.0};
  import->SetOrigin(data3);

  const float data4[2] = {1.0,1.0};
  import->SetOrigin(data4);

  const itk::SpacePrecisionType * originValue = import->GetOrigin().GetDataPointer();
  std::cout << "import->GetOrigin(): " << originValue << std::endl;

  //
  // The rest of this code determines whether the shrink code produced
  // the image we expected.
  //
  ShortImage::RegionType requestedRegion;
  requestedRegion = shrink->GetOutput()->GetRequestedRegion();

  itk::ImageRegionIterator<ShortImage>
    iterator2(shrink->GetOutput(), requestedRegion);

  bool passed = true;
  for (; !iterator2.IsAtEnd(); ++iterator2)
    {
    std::cout << "Pixel " << iterator2.GetIndex() << " = " << iterator2.Get() << std::endl;
    if (iterator2.Get() != itk::Math::RoundHalfIntegerUp<short>(
            static_cast<float>( (shrink->GetShrinkFactors()[0] * iterator2.GetIndex()[0] +
                                 shrink->GetShrinkFactors()[0]/2) +
            (region.GetSize()[0] * ((shrink->GetShrinkFactors()[1]/2) +
                                    (shrink->GetShrinkFactors()[0] * iterator2.GetIndex()[1]))))))
      {
         std::cout << " iterator2.GetIndex() Get() " << iterator2.GetIndex() <<  " " << iterator2.Get()
                   << " compare value " << itk::Math::RoundHalfIntegerUp<short>(
            static_cast<float>( (shrink->GetShrinkFactors()[0] * iterator2.GetIndex()[0] +
                                 shrink->GetShrinkFactors()[0]/2) +
            (region.GetSize()[0] * ((shrink->GetShrinkFactors()[1]/2) +
                                    (shrink->GetShrinkFactors()[0] * iterator2.GetIndex()[1]))))) << "\n";
      passed = false;
      }
    }

  if (passed)
    {
    std::cout << "ImportImageFilter test passed." << std::endl;
    return EXIT_SUCCESS;
    }
  else
    {
    std::cout << "ImportImageFilter test failed." << std::endl;
    return EXIT_FAILURE;
    }

}
<commit_msg>ENH: Improve itkImportImageFilter coverage<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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 "itkImageRegionIterator.h"
#include "itkShrinkImageFilter.h"
#include "itkImportImageFilter.h"
#include "itkTestingMacros.h"

int itkImportImageTest(int, char* [] )
{
  // Create a C-array to hold an image
  short *rawImage = new short[8*12];
  for (int i=0; i < 8*12; i++)
    {
    rawImage[i] = i;
    }

  // typdefs to simplify the syntax
  typedef itk::ImportImageFilter<short, 2> ImportImageFilter;
  typedef itk::Image<short, 2>             ShortImage;
  // Create an ImportImageFilter filter
  ImportImageFilter::Pointer import = ImportImageFilter::New();

  EXERCISE_BASIC_OBJECT_METHODS( import, ImportImageFilter, ImageSource );

  itk::ImageRegion<2>         region;
  itk::ImageRegion<2>::IndexType  index = {{0, 0}};
  itk::ImageRegion<2>::SizeType   size = {{8, 12}};

  region.SetSize( size );
  region.SetIndex( index );

  import->SetRegion( region );
  import->SetImportPointer( rawImage, 8*12, true);

  // Create another filter
  itk::ShrinkImageFilter<ImportImageFilter::OutputImageType, ShortImage >::Pointer shrink;
  shrink = itk::ShrinkImageFilter<ImportImageFilter::OutputImageType, ShortImage>::New();
  shrink->SetInput( import->GetOutput() );
  shrink->SetShrinkFactors(2); //Also tested with factors 3 and 4, with 12x12 image
  try
    {
    shrink->Update();
    }
  catch (itk::ExceptionObject& e)
    {
    std::cerr << "Exception detected: "  << e.GetDescription();
    return EXIT_FAILURE;
    }

  // Test the SetVectorMacros and GetVectorMacros
  const itk::SpacePrecisionType data[2] = {1.0,1.0};
  import->SetSpacing(data);

  const float data2[2] = {1.0,1.0};
  import->SetSpacing(data2);

  const itk::SpacePrecisionType * spacingValue = import->GetSpacing().GetDataPointer();
  std::cout << "import->GetSpacing(): " << *spacingValue << std::endl;

  const double data3[2] = {1.0,1.0};
  import->SetOrigin(data3);

  const float data4[2] = {1.0,1.0};
  import->SetOrigin(data4);

  const itk::SpacePrecisionType * originValue = import->GetOrigin().GetDataPointer();
  std::cout << "import->GetOrigin(): " << *originValue << std::endl;

  //
  // The rest of this code determines whether the shrink code produced
  // the image we expected.
  //
  ShortImage::RegionType requestedRegion;
  requestedRegion = shrink->GetOutput()->GetRequestedRegion();

  itk::ImageRegionIterator<ShortImage>
    iterator2(shrink->GetOutput(), requestedRegion);

  bool passed = true;
  for (; !iterator2.IsAtEnd(); ++iterator2)
    {
    std::cout << "Pixel " << iterator2.GetIndex() << " = " << iterator2.Get() << std::endl;
    if (iterator2.Get() != itk::Math::RoundHalfIntegerUp<short>(
            static_cast<float>( (shrink->GetShrinkFactors()[0] * iterator2.GetIndex()[0] +
                                 shrink->GetShrinkFactors()[0]/2) +
            (region.GetSize()[0] * ((shrink->GetShrinkFactors()[1]/2) +
                                    (shrink->GetShrinkFactors()[0] * iterator2.GetIndex()[1]))))))
      {
         std::cout << " iterator2.GetIndex() Get() " << iterator2.GetIndex() <<  " " << iterator2.Get()
                   << " compare value " << itk::Math::RoundHalfIntegerUp<short>(
            static_cast<float>( (shrink->GetShrinkFactors()[0] * iterator2.GetIndex()[0] +
                                 shrink->GetShrinkFactors()[0]/2) +
            (region.GetSize()[0] * ((shrink->GetShrinkFactors()[1]/2) +
                                    (shrink->GetShrinkFactors()[0] * iterator2.GetIndex()[1]))))) << "\n";
      passed = false;
      }
    }

  if (passed)
    {
    std::cout << "ImportImageFilter test passed." << std::endl;
    return EXIT_SUCCESS;
    }
  else
    {
    std::cout << "ImportImageFilter test failed." << std::endl;
    return EXIT_FAILURE;
    }

}
<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

#include "mitkNavigationDataPlayerBase.h"

// include for exceptions
#include "mitkIGTException.h"

mitk::NavigationDataPlayerBase::NavigationDataPlayerBase()
  : m_NumberOfOutputs(0)
{
  m_Name ="Navigation Data Player Source";
}

mitk::NavigationDataPlayerBase::~NavigationDataPlayerBase()
{
}

void mitk::NavigationDataPlayerBase::UpdateOutputInformation()
{
  this->Modified();  // make sure that we need to be updated
  Superclass::UpdateOutputInformation();
}

bool mitk::NavigationDataPlayerBase::IsAtEnd()
{
  return m_NavigationDataSetIterator == m_NavigationDataSet->End();
}

void mitk::NavigationDataPlayerBase::SetNavigationDataSet(NavigationDataSet::Pointer navigationDataSet)
{
  m_NavigationDataSet = navigationDataSet;
  m_NavigationDataSetIterator = navigationDataSet->Begin();

  this->InitPlayer();
}

unsigned int mitk::NavigationDataPlayerBase::GetNumberOfSnapshots()
{
  return m_NavigationDataSet.IsNull() ? 0 : m_NavigationDataSet->Size();
}

unsigned int mitk::NavigationDataPlayerBase::GetCurrentSnapshotNumber()
{
  return m_NavigationDataSet.IsNull() ? 0 : m_NavigationDataSetIterator - m_NavigationDataSet->Begin();
}

void mitk::NavigationDataPlayerBase::InitPlayer()
{
  if ( m_NavigationDataSet.IsNull() )
  {
    mitkThrowException(mitk::IGTException)
        << "NavigationDataSet has to be set before initializing player.";
  }

  if (m_NumberOfOutputs == 0)
  {
    m_NumberOfOutputs = m_NavigationDataSet->GetNumberOfTools();
    this->SetNumberOfRequiredOutputs(m_NumberOfOutputs);

    for (unsigned int n = 0; n < m_NumberOfOutputs; ++n)
    {
      mitk::NavigationData* output = this->GetOutput(n);
      if (!output)
      {
        DataObjectPointer newOutput = this->MakeOutput(n);
        this->SetNthOutput(n, newOutput);
        this->Modified();
      }
    }
  }
  else if (m_NumberOfOutputs != m_NavigationDataSet->GetNumberOfTools())
  {
    mitkThrowException(mitk::IGTException)
        << "Number of tools cannot be changed in existing player. Please create "
        << "a new player, if the NavigationDataSet has another number of tools now.";
  }

  this->Modified();
}

void mitk::NavigationDataPlayerBase::GraftEmptyOutput()
{
  for (unsigned int index = 0; index < m_NavigationDataSet->GetNumberOfTools(); index++)
  {
    mitk::NavigationData* output = this->GetOutput(index);
    assert(output);

    mitk::NavigationData::Pointer nd = mitk::NavigationData::New();
    mitk::NavigationData::PositionType position;
    mitk::NavigationData::OrientationType orientation(0.0,0.0,0.0,0.0);
    position.Fill(0.0);

    nd->SetPosition(position);
    nd->SetOrientation(orientation);
    nd->SetDataValid(false);

    output->Graft(nd);
  }
}
<commit_msg>Fixed creation of outputs in NavigationDataPlayerBase<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

#include "mitkNavigationDataPlayerBase.h"

// include for exceptions
#include "mitkIGTException.h"

mitk::NavigationDataPlayerBase::NavigationDataPlayerBase()
  : m_NumberOfOutputs(0)
{
  m_Name ="Navigation Data Player Source";
}

mitk::NavigationDataPlayerBase::~NavigationDataPlayerBase()
{
}

void mitk::NavigationDataPlayerBase::UpdateOutputInformation()
{
  this->Modified();  // make sure that we need to be updated
  Superclass::UpdateOutputInformation();
}

bool mitk::NavigationDataPlayerBase::IsAtEnd()
{
  return m_NavigationDataSetIterator == m_NavigationDataSet->End();
}

void mitk::NavigationDataPlayerBase::SetNavigationDataSet(NavigationDataSet::Pointer navigationDataSet)
{
  m_NavigationDataSet = navigationDataSet;
  m_NavigationDataSetIterator = navigationDataSet->Begin();

  this->InitPlayer();
}

unsigned int mitk::NavigationDataPlayerBase::GetNumberOfSnapshots()
{
  return m_NavigationDataSet.IsNull() ? 0 : m_NavigationDataSet->Size();
}

unsigned int mitk::NavigationDataPlayerBase::GetCurrentSnapshotNumber()
{
  return m_NavigationDataSet.IsNull() ? 0 : m_NavigationDataSetIterator - m_NavigationDataSet->Begin();
}

void mitk::NavigationDataPlayerBase::InitPlayer()
{
  if ( m_NavigationDataSet.IsNull() )
  {
    mitkThrowException(mitk::IGTException)
      << "NavigationDataSet has to be set before initializing player.";
  }

  if (m_NumberOfOutputs == 0)
  {
    int requiredOutputs = m_NavigationDataSet->GetNumberOfTools();
    this->SetNumberOfRequiredOutputs(requiredOutputs);

    for (unsigned int n = this->GetNumberOfOutputs(); n < requiredOutputs; ++n)
    {
      DataObjectPointer newOutput = this->MakeOutput(n);
      this->SetNthOutput(n, newOutput);
      this->Modified();
    }
  }
  else if (m_NumberOfOutputs != m_NavigationDataSet->GetNumberOfTools())
  {
    mitkThrowException(mitk::IGTException)
      << "Number of tools cannot be changed in existing player. Please create "
      << "a new player, if the NavigationDataSet has another number of tools now.";
  }

  this->Modified();
}

void mitk::NavigationDataPlayerBase::GraftEmptyOutput()
{
  for (unsigned int index = 0; index < m_NavigationDataSet->GetNumberOfTools(); index++)
  {
    mitk::NavigationData* output = this->GetOutput(index);
    assert(output);

    mitk::NavigationData::Pointer nd = mitk::NavigationData::New();
    mitk::NavigationData::PositionType position;
    mitk::NavigationData::OrientationType orientation(0.0,0.0,0.0,0.0);
    position.Fill(0.0);

    nd->SetPosition(position);
    nd->SetOrientation(orientation);
    nd->SetDataValid(false);

    output->Graft(nd);
  }
}<|endoftext|>


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

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date: 2009-03-21 19:27:37 +0100 (Sa, 21 Mrz 2009) $
Version:   $Revision: 16719 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

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

#include "QmitkToolDistanceWidget.h"

#include <QGridLayout>
#include <itkDataObject.h>
#include <mitkNavigationDataSource.h>
#include <math.h>

QmitkToolDistanceWidget::QmitkToolDistanceWidget(QWidget* parent)
: QWidget(parent), m_Controls(NULL), m_DistanceLabels(NULL)
{
  this->CreateQtPartControl( this );
}

QmitkToolDistanceWidget::~QmitkToolDistanceWidget()
{
  ClearDistanceMatrix();
  delete m_DistanceLabels;
  m_DistanceLabels = NULL;
  m_Controls = NULL;
}

void QmitkToolDistanceWidget::CreateQtPartControl(QWidget *parent)
{
  if (!m_Controls)
  {
    // create GUI widgets
    m_Controls = new Ui::QmitkToolDistanceWidgetControls;
    m_Controls->setupUi(parent);
    m_Controls->m_StatusLabel->setText(QString("No tracking tools connected. Please set up a connection first."));

    this->CreateConnections();
  }
}

void QmitkToolDistanceWidget::CreateConnections()
{

}

void QmitkToolDistanceWidget::CreateToolDistanceMatrix(itk::ProcessObject::DataObjectPointerArray & outputs)
{

  if(outputs.size() > 1)
  {
    this->show();

    mitk::NavigationData* navData;

    if(m_DistanceLabels == NULL)
    {
      m_DistanceLabels = new DistanceLabelType;
    }

    if(m_DistanceLabels->isEmpty())
    {
      this->m_Controls->m_StatusLabel->setText("");

      QLabel* label;

      // labeling of matrix
      for (unsigned int i = 0; i < outputs.size()-1; i++)
      {
        navData = dynamic_cast<mitk::NavigationData*>(outputs.at(i).GetPointer());
        label = new QLabel(navData->GetName(),this);
        label->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
        this->m_Controls->m_GridLayout->addWidget(label,i+1,0);

        navData = dynamic_cast<mitk::NavigationData*>(outputs.at(i+1).GetPointer());
        label = new QLabel(navData->GetName(),this);
        label->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
        this->m_Controls->m_GridLayout->addWidget(label,0,i+1);
      }

      for(unsigned int i = 0; i < outputs.size()-1; i++)
      {
        QVector<QLabel*>* rowDistances = new QVector<QLabel*>();

        for(unsigned int j = i+1; j < outputs.size(); j++)
        {
          // distance labels initializing
          label = new QLabel(QString("---"), this);
          label->setFrameStyle(QFrame::Box | QFrame::Sunken);
          label->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
          rowDistances->append(label);

          //initial distance label adding to the QGridLayout
          this->m_Controls->m_GridLayout->addWidget(label,i+1,j);
        }
        this->m_DistanceLabels->append(*rowDistances);
      }
    }
  }
  else
  {
    this->m_Controls->m_StatusLabel->setText(QString("For distance information please connect at least two tools"));
  }

}

  void QmitkToolDistanceWidget::ShowDistanceValues(itk::ProcessObject::DataObjectPointerArray & outputs)
  {

    mitk::NavigationData* navData;
    mitk::NavigationData* nextNavData;

    for(int i=0; i < m_DistanceLabels->size(); i++)
    {
      int j = i+1;

      for(int k=0; k < m_DistanceLabels->at(i).size(); k++)
      {
        navData = dynamic_cast<mitk::NavigationData*>(outputs.at(i).GetPointer());
        nextNavData = dynamic_cast<mitk::NavigationData*>(outputs.at(j++).GetPointer());

        if(navData == NULL || nextNavData == NULL)
          return;

        mitk::NavigationData::PositionType::RealType distance =  navData->GetPosition().EuclideanDistanceTo(nextNavData->GetPosition());
        distance = floor(distance * 10.) / 10.;
        QString distanceStr;
        if(!navData->IsDataValid() || !nextNavData->IsDataValid())
        {
          distanceStr = "---";
        }
        else
        {
          distanceStr.setNum(distance);
          distanceStr += " mm";
        }
        this->m_DistanceLabels->at(i).at(k)->setText(distanceStr);
      }
    }
  }

  void QmitkToolDistanceWidget::ClearDistanceMatrix()
  {

    while(m_Controls->m_GridLayout->count() > 0)
    {
      QWidget* widget = m_Controls->m_GridLayout->itemAt(0)->widget();
      m_Controls->m_GridLayout->removeWidget(widget);
      delete widget;
    }
   delete this->m_DistanceLabels;
   this->m_DistanceLabels = NULL;

   this->m_Controls->m_StatusLabel->setText(QString("For distance information please set up the connection again."));

  }

  void QmitkToolDistanceWidget::SetDistanceLabelValuesInvalid()
  {
    for(unsigned int i = 0; i < m_DistanceLabels->size(); i++)
    {
      for(unsigned int j= 0; j < m_DistanceLabels->at(i).size(); j++)
      {
        this->m_DistanceLabels->at(i).at(j)->setText(QString("---"));
      }
    }
  }

<commit_msg>COMP (#4211): changed unsigned int <-> int comparison compilation warning<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date: 2009-03-21 19:27:37 +0100 (Sa, 21 Mrz 2009) $
Version:   $Revision: 16719 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

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

#include "QmitkToolDistanceWidget.h"

#include <QGridLayout>
#include <itkDataObject.h>
#include <mitkNavigationDataSource.h>
#include <math.h>

QmitkToolDistanceWidget::QmitkToolDistanceWidget(QWidget* parent)
: QWidget(parent), m_Controls(NULL), m_DistanceLabels(NULL)
{
  this->CreateQtPartControl( this );
}

QmitkToolDistanceWidget::~QmitkToolDistanceWidget()
{
  ClearDistanceMatrix();
  delete m_DistanceLabels;
  m_DistanceLabels = NULL;
  m_Controls = NULL;
}

void QmitkToolDistanceWidget::CreateQtPartControl(QWidget *parent)
{
  if (!m_Controls)
  {
    // create GUI widgets
    m_Controls = new Ui::QmitkToolDistanceWidgetControls;
    m_Controls->setupUi(parent);
    m_Controls->m_StatusLabel->setText(QString("No tracking tools connected. Please set up a connection first."));

    this->CreateConnections();
  }
}

void QmitkToolDistanceWidget::CreateConnections()
{

}

void QmitkToolDistanceWidget::CreateToolDistanceMatrix(itk::ProcessObject::DataObjectPointerArray & outputs)
{

  if(outputs.size() > 1)
  {
    this->show();

    mitk::NavigationData* navData;

    if(m_DistanceLabels == NULL)
    {
      m_DistanceLabels = new DistanceLabelType;
    }

    if(m_DistanceLabels->isEmpty())
    {
      this->m_Controls->m_StatusLabel->setText("");

      QLabel* label;

      // labeling of matrix
      for (unsigned int i = 0; i < outputs.size()-1; i++)
      {
        navData = dynamic_cast<mitk::NavigationData*>(outputs.at(i).GetPointer());
        label = new QLabel(navData->GetName(),this);
        label->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
        this->m_Controls->m_GridLayout->addWidget(label,i+1,0);

        navData = dynamic_cast<mitk::NavigationData*>(outputs.at(i+1).GetPointer());
        label = new QLabel(navData->GetName(),this);
        label->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
        this->m_Controls->m_GridLayout->addWidget(label,0,i+1);
      }

      for(unsigned int i = 0; i < outputs.size()-1; i++)
      {
        QVector<QLabel*>* rowDistances = new QVector<QLabel*>();

        for(unsigned int j = i+1; j < outputs.size(); j++)
        {
          // distance labels initializing
          label = new QLabel(QString("---"), this);
          label->setFrameStyle(QFrame::Box | QFrame::Sunken);
          label->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
          rowDistances->append(label);

          //initial distance label adding to the QGridLayout
          this->m_Controls->m_GridLayout->addWidget(label,i+1,j);
        }
        this->m_DistanceLabels->append(*rowDistances);
      }
    }
  }
  else
  {
    this->m_Controls->m_StatusLabel->setText(QString("For distance information please connect at least two tools"));
  }

}

  void QmitkToolDistanceWidget::ShowDistanceValues(itk::ProcessObject::DataObjectPointerArray & outputs)
  {

    mitk::NavigationData* navData;
    mitk::NavigationData* nextNavData;

    for(int i=0; i < m_DistanceLabels->size(); i++)
    {
      int j = i+1;

      for(int k=0; k < m_DistanceLabels->at(i).size(); k++)
      {
        navData = dynamic_cast<mitk::NavigationData*>(outputs.at(i).GetPointer());
        nextNavData = dynamic_cast<mitk::NavigationData*>(outputs.at(j++).GetPointer());

        if(navData == NULL || nextNavData == NULL)
          return;

        mitk::NavigationData::PositionType::RealType distance =  navData->GetPosition().EuclideanDistanceTo(nextNavData->GetPosition());
        distance = floor(distance * 10.) / 10.;
        QString distanceStr;
        if(!navData->IsDataValid() || !nextNavData->IsDataValid())
        {
          distanceStr = "---";
        }
        else
        {
          distanceStr.setNum(distance);
          distanceStr += " mm";
        }
        this->m_DistanceLabels->at(i).at(k)->setText(distanceStr);
      }
    }
  }

  void QmitkToolDistanceWidget::ClearDistanceMatrix()
  {

    while(m_Controls->m_GridLayout->count() > 0)
    {
      QWidget* widget = m_Controls->m_GridLayout->itemAt(0)->widget();
      m_Controls->m_GridLayout->removeWidget(widget);
      delete widget;
    }
   delete this->m_DistanceLabels;
   this->m_DistanceLabels = NULL;

   this->m_Controls->m_StatusLabel->setText(QString("For distance information please set up the connection again."));

  }

  void QmitkToolDistanceWidget::SetDistanceLabelValuesInvalid()
  {
    for(int i = 0; i < m_DistanceLabels->size(); i++)
    {
      for(int j= 0; j < m_DistanceLabels->at(i).size(); j++)
      {
        this->m_DistanceLabels->at(i).at(j)->setText(QString("---"));
      }
    }
  }

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2007 Sebastian Sauer <mail@dipe.org>
 *
 * This file is part of SuperKaramba.
 *
 * SuperKaramba is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * SuperKaramba 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with SuperKaramba; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "plasmaengine.h"

#include <plasma/dataenginemanager.h>

#if 0
#include <QFile>
#include <QTextStream>
#endif

/// \internal helper function that translates plasma data into a QVariantMap.
QVariantMap dataToMap(Plasma::DataEngine::Data data)
{
    QVariantMap map;
    Plasma::DataEngine::DataIterator it(data);
    while( it.hasNext() ) {
        it.next();
        map.insert(it.key(), it.value());
    }
    return map;
}

/*
/// \internal helper function that translates a QVariantMap into plasma data.
Plasma::DataEngine::Data mapToData(QVariantMap map)
{
    Plasma::DataEngine::Data data;
    for(QVariantMap::Iterator it = map.begin(); it != map.end(); ++it)
        data.insert(it.key(), it.value());
    return data;
}
*/

/*****************************************************************************************
* PlasmaSensorConnector
*/

/// \internal d-pointer class.
class PlasmaSensorConnector::Private
{
    public:
        Meter* meter;
        QString source;
        QString format;
};

PlasmaSensorConnector::PlasmaSensorConnector(Meter *meter, const QString& source) : QObject(meter), d(new Private)
{
    //kDebug()<<"PlasmaSensorConnector Ctor"<<endl;
    setObjectName(source);
    d->meter = meter;
    d->source = source;
}

PlasmaSensorConnector::~PlasmaSensorConnector()
{
    //kDebug()<<"PlasmaSensorConnector Dtor"<<endl;
    delete d;
}

Meter* PlasmaSensorConnector::meter() const
{
    return d->meter;
}

QString PlasmaSensorConnector::source() const
{
    return d->source;
}

void PlasmaSensorConnector::setSource(const QString& source)
{
    d->source = source;
}

QString PlasmaSensorConnector::format() const
{
    return d->format;
}

void PlasmaSensorConnector::setFormat(const QString& format)
{
    d->format = format;
}

void PlasmaSensorConnector::dataUpdated(const QString& source, const Plasma::DataEngine::Data &data)
{
    //kDebug()<<"PlasmaSensorConnector::dataUpdated d->source="<<d->source<<" source="<<source<<endl;
    if( d->source.isEmpty() ) {
        emit sourceUpdated(source, dataToMap(data));
        return;
    }
    if( source != d->source ) {
        return;
    }
    QString v = d->format;
    Plasma::DataEngine::DataIterator it(data);
    while( it.hasNext() ) {
        it.next();
        QString s = QString("%%1").arg( it.key() );
        v.replace(s,it.value().toString());
    }
    d->meter->setValue(v);
}

/*****************************************************************************************
* PlasmaSensor
*/

/// \internal d-pointer class.
class PlasmaSensor::Private
{
    public:
        Plasma::DataEngine* engine;
        QString engineName;
        explicit Private() : engine(0) {}
};

PlasmaSensor::PlasmaSensor(int msec) : Sensor(msec), d(new Private)
{
    kDebug()<<"PlasmaSensor Ctor"<<endl;
}

PlasmaSensor::~PlasmaSensor()
{
    kDebug()<<"PlasmaSensor Dtor"<<endl;
    delete d;
}

Plasma::DataEngine* PlasmaSensor::engineImpl() const
{
    return d->engine;
}

void PlasmaSensor::setEngineImpl(Plasma::DataEngine* engine, const QString& engineName)
{
    d->engine = engine;
    d->engineName = engineName;
}

QString PlasmaSensor::engine()
{
    return d->engine ? d->engineName : QString();
}

void PlasmaSensor::setEngine(const QString& name)
{
    //kDebug()<<"PlasmaSensor::setEngine name="<<name<<endl;
    if( d->engine ) {
        disconnect(d->engine, SIGNAL(newSource(QString)), this, SIGNAL(sourceAdded(QString)));
        disconnect(d->engine, SIGNAL(sourceRemoved(QString)), this, SIGNAL(sourceRemoved(QString)));
        Plasma::DataEngineManager::self()->unloadEngine(d->engineName);
    }
    d->engineName = QString();
    d->engine = Plasma::DataEngineManager::self()->engine(name);
    if( ! d->engine || ! d->engine->isValid() ) {
        d->engine = Plasma::DataEngineManager::self()->loadEngine(name);
        if( ! d->engine || ! d->engine->isValid() ) {
            kWarning()<<"PlasmaSensor::setEngine: No such engine: "<<name<<endl;
            return;
        }
    }
    d->engineName = name;
    connect(d->engine, SIGNAL(newSource(QString)), this, SIGNAL(sourceAdded(QString)));
    connect(d->engine, SIGNAL(sourceRemoved(QString)), this, SIGNAL(sourceRemoved(QString)));
    //d->engine->setProperty("reportSeconds", true);
}

bool PlasmaSensor::isValid() const
{
    return d->engine && d->engine->isValid();
}

QStringList PlasmaSensor::sources() const
{
    return d->engine ? d->engine->sources() : QStringList();
}

QVariant PlasmaSensor::property(const QByteArray& name) const
{
    return d->engine ? d->engine->property(name) : QVariant();
}

void PlasmaSensor::setProperty(const QByteArray& name, const QVariant& value)
{
    if( d->engine )
        d->engine->setProperty(name, value);
}

QVariantMap PlasmaSensor::query(const QString& source)
{
    //kDebug()<<"PlasmaSensor::query"<<endl;
    return d->engine ? dataToMap(d->engine->query(source)) : QVariantMap();
}

QObject* PlasmaSensor::connectSource(const QString& source, QObject* visualization)
{
    //kDebug()<<"PlasmaSensor::connectSource source="<<source<<endl;
    if( ! d->engine ) {
        kWarning()<<"PlasmaSensor::connectSource: No engine"<<endl;
        return 0;
    }
    if( Meter* m = dynamic_cast<Meter*>(visualization) ) {
        PlasmaSensorConnector* c = new PlasmaSensorConnector(m, source);
        d->engine->connectSource(source, c);
        kDebug()<<"PlasmaSensor::connectSource meter, engine isValid="<<d->engine->isValid()<<" isUsed="<<d->engine->isUsed()<<endl;
        return c;
    }
    d->engine->connectSource(source, visualization ? visualization : this);
    return 0;
}

void PlasmaSensor::disconnectSource(const QString& source, QObject* visualization)
{
    //kDebug()<<"PlasmaSensor::disconnectSource"<<endl;
    if( Meter* m = dynamic_cast<Meter*>(visualization) ) {
        foreach(PlasmaSensorConnector* c, m->findChildren<PlasmaSensorConnector*>(source))
            if( c->meter() == m )
                delete c;
    }
    else if( d->engine ) {
        d->engine->disconnectSource(source, visualization ? visualization : this);
    }
    else
        kWarning()<<"PlasmaSensor::disconnectSource: No engine"<<endl;
}

void PlasmaSensor::update()
{
    kDebug()<<"PlasmaSensor::update"<<endl;
    /*TODO
    foreach(QObject *it, *objList) {
        SensorParams *sp = qobject_cast<SensorParams*>(it);
        Meter *meter = sp->getMeter();
        const QString format = sp->getParam("FORMAT");
        //if (format.length() == 0) format = "%um";
        //format.replace(QRegExp("%fmb", Qt::CaseInsensitive),QString::number((int)((totalMem - usedMemNoBuffers) / 1024.0 + 0.5)));
        //meter->setValue(format);
    }
    */
}

void PlasmaSensor::dataUpdated(const QString& source, Plasma::DataEngine::Data data)
{
    //kDebug()<<"PlasmaSensor::dataUpdated source="<<source<<endl;
    emit sourceUpdated(source, dataToMap(data));
}

#include "plasmaengine.moc"
<commit_msg>isUsed is private now<commit_after>/*
 * Copyright (C) 2007 Sebastian Sauer <mail@dipe.org>
 *
 * This file is part of SuperKaramba.
 *
 * SuperKaramba is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * SuperKaramba 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with SuperKaramba; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "plasmaengine.h"

#include <plasma/dataenginemanager.h>

#if 0
#include <QFile>
#include <QTextStream>
#endif

/// \internal helper function that translates plasma data into a QVariantMap.
QVariantMap dataToMap(Plasma::DataEngine::Data data)
{
    QVariantMap map;
    Plasma::DataEngine::DataIterator it(data);
    while( it.hasNext() ) {
        it.next();
        map.insert(it.key(), it.value());
    }
    return map;
}

/*
/// \internal helper function that translates a QVariantMap into plasma data.
Plasma::DataEngine::Data mapToData(QVariantMap map)
{
    Plasma::DataEngine::Data data;
    for(QVariantMap::Iterator it = map.begin(); it != map.end(); ++it)
        data.insert(it.key(), it.value());
    return data;
}
*/

/*****************************************************************************************
* PlasmaSensorConnector
*/

/// \internal d-pointer class.
class PlasmaSensorConnector::Private
{
    public:
        Meter* meter;
        QString source;
        QString format;
};

PlasmaSensorConnector::PlasmaSensorConnector(Meter *meter, const QString& source) : QObject(meter), d(new Private)
{
    //kDebug()<<"PlasmaSensorConnector Ctor"<<endl;
    setObjectName(source);
    d->meter = meter;
    d->source = source;
}

PlasmaSensorConnector::~PlasmaSensorConnector()
{
    //kDebug()<<"PlasmaSensorConnector Dtor"<<endl;
    delete d;
}

Meter* PlasmaSensorConnector::meter() const
{
    return d->meter;
}

QString PlasmaSensorConnector::source() const
{
    return d->source;
}

void PlasmaSensorConnector::setSource(const QString& source)
{
    d->source = source;
}

QString PlasmaSensorConnector::format() const
{
    return d->format;
}

void PlasmaSensorConnector::setFormat(const QString& format)
{
    d->format = format;
}

void PlasmaSensorConnector::dataUpdated(const QString& source, const Plasma::DataEngine::Data &data)
{
    //kDebug()<<"PlasmaSensorConnector::dataUpdated d->source="<<d->source<<" source="<<source<<endl;
    if( d->source.isEmpty() ) {
        emit sourceUpdated(source, dataToMap(data));
        return;
    }
    if( source != d->source ) {
        return;
    }
    QString v = d->format;
    Plasma::DataEngine::DataIterator it(data);
    while( it.hasNext() ) {
        it.next();
        QString s = QString("%%1").arg( it.key() );
        v.replace(s,it.value().toString());
    }
    d->meter->setValue(v);
}

/*****************************************************************************************
* PlasmaSensor
*/

/// \internal d-pointer class.
class PlasmaSensor::Private
{
    public:
        Plasma::DataEngine* engine;
        QString engineName;
        explicit Private() : engine(0) {}
};

PlasmaSensor::PlasmaSensor(int msec) : Sensor(msec), d(new Private)
{
    kDebug()<<"PlasmaSensor Ctor"<<endl;
}

PlasmaSensor::~PlasmaSensor()
{
    kDebug()<<"PlasmaSensor Dtor"<<endl;
    delete d;
}

Plasma::DataEngine* PlasmaSensor::engineImpl() const
{
    return d->engine;
}

void PlasmaSensor::setEngineImpl(Plasma::DataEngine* engine, const QString& engineName)
{
    d->engine = engine;
    d->engineName = engineName;
}

QString PlasmaSensor::engine()
{
    return d->engine ? d->engineName : QString();
}

void PlasmaSensor::setEngine(const QString& name)
{
    //kDebug()<<"PlasmaSensor::setEngine name="<<name<<endl;
    if( d->engine ) {
        disconnect(d->engine, SIGNAL(newSource(QString)), this, SIGNAL(sourceAdded(QString)));
        disconnect(d->engine, SIGNAL(sourceRemoved(QString)), this, SIGNAL(sourceRemoved(QString)));
        Plasma::DataEngineManager::self()->unloadEngine(d->engineName);
    }
    d->engineName = QString();
    d->engine = Plasma::DataEngineManager::self()->engine(name);
    if( ! d->engine || ! d->engine->isValid() ) {
        d->engine = Plasma::DataEngineManager::self()->loadEngine(name);
        if( ! d->engine || ! d->engine->isValid() ) {
            kWarning()<<"PlasmaSensor::setEngine: No such engine: "<<name<<endl;
            return;
        }
    }
    d->engineName = name;
    connect(d->engine, SIGNAL(newSource(QString)), this, SIGNAL(sourceAdded(QString)));
    connect(d->engine, SIGNAL(sourceRemoved(QString)), this, SIGNAL(sourceRemoved(QString)));
    //d->engine->setProperty("reportSeconds", true);
}

bool PlasmaSensor::isValid() const
{
    return d->engine && d->engine->isValid();
}

QStringList PlasmaSensor::sources() const
{
    return d->engine ? d->engine->sources() : QStringList();
}

QVariant PlasmaSensor::property(const QByteArray& name) const
{
    return d->engine ? d->engine->property(name) : QVariant();
}

void PlasmaSensor::setProperty(const QByteArray& name, const QVariant& value)
{
    if( d->engine )
        d->engine->setProperty(name, value);
}

QVariantMap PlasmaSensor::query(const QString& source)
{
    //kDebug()<<"PlasmaSensor::query"<<endl;
    return d->engine ? dataToMap(d->engine->query(source)) : QVariantMap();
}

QObject* PlasmaSensor::connectSource(const QString& source, QObject* visualization)
{
    //kDebug()<<"PlasmaSensor::connectSource source="<<source<<endl;
    if( ! d->engine ) {
        kWarning()<<"PlasmaSensor::connectSource: No engine"<<endl;
        return 0;
    }
    if( Meter* m = dynamic_cast<Meter*>(visualization) ) {
        PlasmaSensorConnector* c = new PlasmaSensorConnector(m, source);
        d->engine->connectSource(source, c);
        kDebug()<<"PlasmaSensor::connectSource meter, engine isValid="<<d->engine->isValid();
        return c;
    }
    d->engine->connectSource(source, visualization ? visualization : this);
    return 0;
}

void PlasmaSensor::disconnectSource(const QString& source, QObject* visualization)
{
    //kDebug()<<"PlasmaSensor::disconnectSource"<<endl;
    if( Meter* m = dynamic_cast<Meter*>(visualization) ) {
        foreach(PlasmaSensorConnector* c, m->findChildren<PlasmaSensorConnector*>(source))
            if( c->meter() == m )
                delete c;
    }
    else if( d->engine ) {
        d->engine->disconnectSource(source, visualization ? visualization : this);
    }
    else
        kWarning()<<"PlasmaSensor::disconnectSource: No engine"<<endl;
}

void PlasmaSensor::update()
{
    kDebug()<<"PlasmaSensor::update"<<endl;
    /*TODO
    foreach(QObject *it, *objList) {
        SensorParams *sp = qobject_cast<SensorParams*>(it);
        Meter *meter = sp->getMeter();
        const QString format = sp->getParam("FORMAT");
        //if (format.length() == 0) format = "%um";
        //format.replace(QRegExp("%fmb", Qt::CaseInsensitive),QString::number((int)((totalMem - usedMemNoBuffers) / 1024.0 + 0.5)));
        //meter->setValue(format);
    }
    */
}

void PlasmaSensor::dataUpdated(const QString& source, Plasma::DataEngine::Data data)
{
    //kDebug()<<"PlasmaSensor::dataUpdated source="<<source<<endl;
    emit sourceUpdated(source, dataToMap(data));
}

#include "plasmaengine.moc"
<|endoftext|>