<commit_before>#pragma once
#include "support/uref.hpp"

#include <boost/python/to_python_converter.hpp>
#include <boost/python/tuple.hpp>
#include <boost/python/cast.hpp>

#define NPY_NO_DEPRECATED_API NPY_1_8_API_VERSION
#include <numpy/ndarrayobject.h>

#include <cstdint>

namespace bp = boost::python;

/// type map: C++ type to numpy type
template<class T> struct dtype;
template<> struct dtype<bool> { static constexpr auto value = NPY_BOOL; };
template<> struct dtype<float> { static constexpr auto value = NPY_FLOAT; };
template<> struct dtype<double> { static constexpr auto value = NPY_DOUBLE; };
template<> struct dtype<std::complex<float>> { static constexpr auto value = NPY_CFLOAT; };
template<> struct dtype<std::complex<double>> { static constexpr auto value = NPY_CDOUBLE; };
template<> struct dtype<std::int8_t> { static constexpr auto value = NPY_INT8; };
template<> struct dtype<std::int16_t> { static constexpr auto value = NPY_INT16; };
template<> struct dtype<std::int32_t> { static constexpr auto value = NPY_INT32; };
template<> struct dtype<std::int64_t> { static constexpr auto value = NPY_INT64; };
template<> struct dtype<std::uint8_t> { static constexpr auto value = NPY_UINT8; };
template<> struct dtype<std::uint16_t> { static constexpr auto value = NPY_UINT16; };
template<> struct dtype<std::uint32_t> { static constexpr auto value = NPY_UINT32; };
template<> struct dtype<std::uint64_t> { static constexpr auto value = NPY_UINT64; };

template<>
struct bp::base_type_traits<PyArrayObject> : std::true_type {};

struct denseuref_to_python {
    static PyObject* convert(const DenseURef& u) {
        int ndim = (u.rows == 1 || u.cols == 1) ? 1 : 2;

        npy_intp shape[ndim];
        if (ndim == 1) { // row or column vector
            shape[0] = u.is_row_major ? u.cols : u.rows;
        }
        else { // matrix
            shape[0] = u.rows;
            shape[1] = u.cols;
        }

        auto const type = [&]{
            switch (u.type) {
                case ScalarType::f: return NPY_FLOAT;
                case ScalarType::cf: return NPY_CFLOAT;
                case ScalarType::d: return NPY_DOUBLE;
                case ScalarType::cd: return NPY_CDOUBLE;
                case ScalarType::b: return NPY_BOOL;
                case ScalarType::i8: return NPY_INT8;
                case ScalarType::i16: return NPY_INT16;
                case ScalarType::i32: return NPY_INT32;
                case ScalarType::u8: return NPY_UINT8;
                case ScalarType::u16: return NPY_UINT16;
                case ScalarType::u32: return NPY_UINT32;
                default: return NPY_VOID;
            }
        }();

        int flags = u.is_row_major ? NPY_ARRAY_CARRAY : NPY_ARRAY_FARRAY;

        // ndarray from existing data -> it does not own the data and will not delete it
        return PyArray_New(&PyArray_Type, ndim, shape, type, nullptr,
                           (void*)u.data, 0, flags, nullptr);
    }

    static const PyTypeObject* get_pytype() { return &PyArray_Type; }
};

template<class EigenType>
struct eigen3_to_numpy {
    static PyObject* convert(const EigenType& eigen_object) {
        constexpr int ndim = EigenType::IsVectorAtCompileTime ? 1 : 2;

        npy_intp shape[ndim];
        if (ndim == 1) { // row or column vector
            shape[0] = EigenType::IsRowMajor ? eigen_object.cols() : eigen_object.rows();
        }
        else { // matrix
            shape[0] = eigen_object.rows();
            shape[1] = eigen_object.cols();
        }

        using scalar_t = typename EigenType::Scalar;
        int flags = EigenType::IsRowMajor ? NPY_ARRAY_CARRAY : NPY_ARRAY_FARRAY;

        // new empty ndarray of the correct type and shape
        PyObject* array = PyArray_New(&PyArray_Type, ndim, shape, dtype<scalar_t>::value,
                                      nullptr, nullptr, 0, flags, nullptr);
        std::memcpy(
            PyArray_DATA(bp::downcast<PyArrayObject>(array)),
            eigen_object.data(),
            eigen_object.size() * sizeof(scalar_t)
        );
        return array;
    }

    static const PyTypeObject* get_pytype() { return &PyArray_Type; }
};

/**
 Helper function that will construct an eigen vector or matrix
 */
template<class EigenType, int ndim, bool fixed_size> struct construct_eigen;

template<class EigenType>
struct construct_eigen<EigenType, 1, false> {
    static void exec(EigenType* v, typename EigenType::Scalar* data, npy_intp const* shape) {
        new (v) EigenType(shape[0]);
        std::copy_n(data, v->size(), v->data());
    }
};

template<class EigenType>
struct construct_eigen<EigenType, 2, false> {
    static void exec(EigenType* v, typename EigenType::Scalar* data, npy_intp const* shape) {
        new (v) EigenType(shape[0], shape[1]);
        std::copy_n(data, v->rows() * v->cols(), v->data());
    }
};

template<class EigenType>
struct construct_eigen<EigenType, 1, true> {
    static void exec(EigenType* v, typename EigenType::Scalar* data, npy_intp const* shape) {
        new (v) EigenType(EigenType::Zero());
        auto size = std::min(v->size(), shape[0]);
        std::copy_n(data, size, v->data());
    }
};

template<class EigenType>
struct numpy_to_eigen3 {
    numpy_to_eigen3() {
        bp::converter::registry::insert_rvalue_converter(
            &convertible, &construct, bp::type_id<EigenType>(), &PyArray_Type
        );
    }

    static constexpr auto ndim = EigenType::IsVectorAtCompileTime ? 1 : 2;
    static constexpr auto ndtype = dtype<typename EigenType::Scalar>::value;
    static constexpr auto fixed_size = EigenType::SizeAtCompileTime > 0;

    static void* convertible(PyObject* p) {
        // try to make an ndarray from the python object
        auto ndarray = bp::handle<PyArrayObject>{bp::allow_null(PyArray_FROMANY(
            p, ndtype, ndim, ndim,
            EigenType::IsRowMajor ? NPY_ARRAY_C_CONTIGUOUS : NPY_ARRAY_F_CONTIGUOUS
        ))};

        if (!ndarray)
            return nullptr;
        if (EigenType::IsRowMajor && !PyArray_IS_C_CONTIGUOUS(ndarray.get()))
            return nullptr; // row major only accepts C-style array
        if (!EigenType::IsRowMajor && !PyArray_IS_F_CONTIGUOUS(ndarray.get()))
            return nullptr; // column major only accepts Fortran-style array

        return p;
    }

    static void construct(PyObject* p, bp::converter::rvalue_from_python_stage1_data* data) {
        // get the pointer to memory where to construct the new eigen3 object
        auto storage = reinterpret_cast<EigenType*>(
            ((bp::converter::rvalue_from_python_storage<EigenType>*)data)->storage.bytes
        );

        auto ndarray = bp::handle<PyArrayObject>{PyArray_FROMANY(
            p, ndtype, ndim, ndim,
            EigenType::IsRowMajor ? NPY_ARRAY_C_CONTIGUOUS : NPY_ARRAY_F_CONTIGUOUS
        )};
        auto array_data = static_cast<typename EigenType::Scalar*>(PyArray_DATA(ndarray.get()));
        auto array_shape = PyArray_SHAPE(ndarray.get());

        // in-place construct a new eigen3 object using data from the numpy array
        construct_eigen<EigenType, ndim, fixed_size>::exec(storage, array_data, array_shape);

        // save the pointer to the eigen3 object for later use by boost.python
        data->convertible = storage;
    }
};

template<class EigenType>
inline void eigen3_numpy_register_type() {
    numpy_to_eigen3<EigenType>{};
    bp::to_python_converter<EigenType, eigen3_to_numpy<EigenType>>{};
}
<commit_msg>Add numpy to Eigen::Map converter<commit_after>#pragma once
#include "support/uref.hpp"

#include <boost/python/to_python_converter.hpp>
#include <boost/python/tuple.hpp>
#include <boost/python/cast.hpp>

#define NPY_NO_DEPRECATED_API NPY_1_8_API_VERSION
#include <numpy/ndarrayobject.h>

#include <cstdint>

namespace bp = boost::python;

/// type map: C++ type to numpy type
template<class T> struct dtype;
template<> struct dtype<bool> { static constexpr auto value = NPY_BOOL; };
template<> struct dtype<float> { static constexpr auto value = NPY_FLOAT; };
template<> struct dtype<double> { static constexpr auto value = NPY_DOUBLE; };
template<> struct dtype<std::complex<float>> { static constexpr auto value = NPY_CFLOAT; };
template<> struct dtype<std::complex<double>> { static constexpr auto value = NPY_CDOUBLE; };
template<> struct dtype<std::int8_t> { static constexpr auto value = NPY_INT8; };
template<> struct dtype<std::int16_t> { static constexpr auto value = NPY_INT16; };
template<> struct dtype<std::int32_t> { static constexpr auto value = NPY_INT32; };
template<> struct dtype<std::int64_t> { static constexpr auto value = NPY_INT64; };
template<> struct dtype<std::uint8_t> { static constexpr auto value = NPY_UINT8; };
template<> struct dtype<std::uint16_t> { static constexpr auto value = NPY_UINT16; };
template<> struct dtype<std::uint32_t> { static constexpr auto value = NPY_UINT32; };
template<> struct dtype<std::uint64_t> { static constexpr auto value = NPY_UINT64; };

template<>
struct bp::base_type_traits<PyArrayObject> : std::true_type {};

struct denseuref_to_python {
    static PyObject* convert(const DenseURef& u) {
        int ndim = (u.rows == 1 || u.cols == 1) ? 1 : 2;

        npy_intp shape[ndim];
        if (ndim == 1) { // row or column vector
            shape[0] = u.is_row_major ? u.cols : u.rows;
        }
        else { // matrix
            shape[0] = u.rows;
            shape[1] = u.cols;
        }

        auto const type = [&]{
            switch (u.type) {
                case ScalarType::f: return NPY_FLOAT;
                case ScalarType::cf: return NPY_CFLOAT;
                case ScalarType::d: return NPY_DOUBLE;
                case ScalarType::cd: return NPY_CDOUBLE;
                case ScalarType::b: return NPY_BOOL;
                case ScalarType::i8: return NPY_INT8;
                case ScalarType::i16: return NPY_INT16;
                case ScalarType::i32: return NPY_INT32;
                case ScalarType::u8: return NPY_UINT8;
                case ScalarType::u16: return NPY_UINT16;
                case ScalarType::u32: return NPY_UINT32;
                default: return NPY_VOID;
            }
        }();

        int flags = u.is_row_major ? NPY_ARRAY_CARRAY : NPY_ARRAY_FARRAY;

        // ndarray from existing data -> it does not own the data and will not delete it
        return PyArray_New(&PyArray_Type, ndim, shape, type, nullptr,
                           (void*)u.data, 0, flags, nullptr);
    }

    static const PyTypeObject* get_pytype() { return &PyArray_Type; }
};

template<class EigenType>
struct eigen3_to_numpy {
    static PyObject* convert(const EigenType& eigen_object) {
        constexpr int ndim = EigenType::IsVectorAtCompileTime ? 1 : 2;

        npy_intp shape[ndim];
        if (ndim == 1) { // row or column vector
            shape[0] = EigenType::IsRowMajor ? eigen_object.cols() : eigen_object.rows();
        }
        else { // matrix
            shape[0] = eigen_object.rows();
            shape[1] = eigen_object.cols();
        }

        using scalar_t = typename EigenType::Scalar;
        int flags = EigenType::IsRowMajor ? NPY_ARRAY_CARRAY : NPY_ARRAY_FARRAY;

        // new empty ndarray of the correct type and shape
        PyObject* array = PyArray_New(&PyArray_Type, ndim, shape, dtype<scalar_t>::value,
                                      nullptr, nullptr, 0, flags, nullptr);
        std::memcpy(
            PyArray_DATA(bp::downcast<PyArrayObject>(array)),
            eigen_object.data(),
            eigen_object.size() * sizeof(scalar_t)
        );
        return array;
    }

    static const PyTypeObject* get_pytype() { return &PyArray_Type; }
};

/**
 Helper function that will construct an eigen vector or matrix
 */
template<class EigenType, int ndim, bool fixed_size> struct construct_eigen;

template<class EigenType>
struct construct_eigen<EigenType, 1, false> {
    static void exec(EigenType* v, typename EigenType::Scalar* data, npy_intp const* shape) {
        new (v) EigenType(shape[0]);
        std::copy_n(data, v->size(), v->data());
    }
};

template<class EigenType>
struct construct_eigen<EigenType, 2, false> {
    static void exec(EigenType* v, typename EigenType::Scalar* data, npy_intp const* shape) {
        new (v) EigenType(shape[0], shape[1]);
        std::copy_n(data, v->rows() * v->cols(), v->data());
    }
};

template<class EigenType>
struct construct_eigen<EigenType, 1, true> {
    static void exec(EigenType* v, typename EigenType::Scalar* data, npy_intp const* shape) {
        new (v) EigenType(EigenType::Zero());
        auto size = std::min(v->size(), shape[0]);
        std::copy_n(data, size, v->data());
    }
};

template<class EigenType>
struct numpy_to_eigen3 {
    numpy_to_eigen3() {
        bp::converter::registry::insert_rvalue_converter(
            &convertible, &construct, bp::type_id<EigenType>(), &PyArray_Type
        );
    }

    static constexpr auto ndim = EigenType::IsVectorAtCompileTime ? 1 : 2;
    static constexpr auto ndtype = dtype<typename EigenType::Scalar>::value;
    static constexpr auto fixed_size = EigenType::SizeAtCompileTime > 0;

    static void* convertible(PyObject* p) {
        // try to make an ndarray from the python object
        auto ndarray = bp::handle<PyArrayObject>{bp::allow_null(PyArray_FROMANY(
            p, ndtype, ndim, ndim,
            EigenType::IsRowMajor ? NPY_ARRAY_C_CONTIGUOUS : NPY_ARRAY_F_CONTIGUOUS
        ))};

        if (!ndarray)
            return nullptr;
        if (EigenType::IsRowMajor && !PyArray_IS_C_CONTIGUOUS(ndarray.get()))
            return nullptr; // row major only accepts C-style array
        if (!EigenType::IsRowMajor && !PyArray_IS_F_CONTIGUOUS(ndarray.get()))
            return nullptr; // column major only accepts Fortran-style array

        return p;
    }

    static void construct(PyObject* p, bp::converter::rvalue_from_python_stage1_data* data) {
        // get the pointer to memory where to construct the new eigen3 object
        auto storage = reinterpret_cast<EigenType*>(
            ((bp::converter::rvalue_from_python_storage<EigenType>*)data)->storage.bytes
        );

        auto ndarray = bp::handle<PyArrayObject>{PyArray_FROMANY(
            p, ndtype, ndim, ndim,
            EigenType::IsRowMajor ? NPY_ARRAY_C_CONTIGUOUS : NPY_ARRAY_F_CONTIGUOUS
        )};
        auto array_data = static_cast<typename EigenType::Scalar*>(PyArray_DATA(ndarray.get()));
        auto array_shape = PyArray_SHAPE(ndarray.get());

        // in-place construct a new eigen3 object using data from the numpy array
        construct_eigen<EigenType, ndim, fixed_size>::exec(storage, array_data, array_shape);

        // save the pointer to the eigen3 object for later use by boost.python
        data->convertible = storage;
    }
};

template<class EigenType, int ndim> struct construct_eigen_map;

template<class EigenType>
struct construct_eigen_map<EigenType, 1> {
    static void exec(void* storage, typename EigenType::Scalar* data, npy_intp const* shape) {
        new (storage) Eigen::Map<EigenType>{data, shape[0]};
    }
};

template<class EigenType>
struct construct_eigen_map<EigenType, 2> {
    static void exec(void* storage, typename EigenType::Scalar* data, npy_intp const* shape) {
        new (storage) Eigen::Map<EigenType>{data, shape[0], shape[1]};
    }
};

template<class EigenType>
struct numpy_to_eigen3_map {
    numpy_to_eigen3_map() {
        bp::converter::registry::insert_rvalue_converter(
            &convertible, &construct, bp::type_id<Eigen::Map<EigenType>>(), &PyArray_Type
        );
    }

    static constexpr auto ndim = EigenType::IsVectorAtCompileTime ? 1 : 2;
    static constexpr auto ndtype = dtype<typename EigenType::Scalar>::value;

    static void* convertible(PyObject* p) {
        if (!PyArray_Check(p))
            return nullptr;

        auto array = (PyArrayObject*)p;
        if (PyArray_NDIM(array) != ndim || PyArray_TYPE(array) != ndtype)
            return nullptr;
        if (EigenType::IsRowMajor && !PyArray_IS_C_CONTIGUOUS(array))
            return nullptr;
        if (!EigenType::IsRowMajor && !PyArray_IS_F_CONTIGUOUS(array))
            return nullptr;

        return p;
    }

    static void construct(PyObject* p, bp::converter::rvalue_from_python_stage1_data* data) {
        void* storage = ((bp::converter::rvalue_from_python_storage<EigenType>*)
            data)->storage.bytes;

        auto array = (PyArrayObject*)p;
        auto array_data = static_cast<typename EigenType::Scalar*>(PyArray_DATA(array));
        auto array_shape = PyArray_SHAPE(array);

        construct_eigen_map<EigenType, ndim>::exec(storage, array_data, array_shape);
        data->convertible = storage;
    }
};

template<class EigenType>
inline void eigen3_numpy_register_type() {
    numpy_to_eigen3<EigenType>{};
    numpy_to_eigen3_map<EigenType>{};
    bp::to_python_converter<EigenType, eigen3_to_numpy<EigenType>>{};
}
<|endoftext|>


<commit_before>/*
 * Copyright 1999-2004 The Apache Software Foundation.
 *
 * 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.
 */

/**
 * @author Matthew Hoyt (mhoyt@ca.ibm.com)
 */

#if !defined(XALANDEQUE_HEADER_GUARD_1357924680)
#define XALANDEQUE_HEADER_GUARD_1357924680

// Base include file.  Must be first.
#include <xalanc/Include/PlatformDefinitions.hpp>

#include <xalanc/Include/XalanVector.hpp>
#include <xalanc/Include/XalanMemoryManagement.hpp>

XALAN_CPP_NAMESPACE_BEGIN

template <class Value>
struct XalanDequeIteratorTraits
{
	typedef Value	        value_type;
	typedef Value&	        reference;
	typedef Value*	        pointer;
    typedef const Value&    const_reference;
};

template <class Value>
struct XalanDequeConstIteratorTraits
{
	typedef Value	        value_type;
	typedef const Value&	reference;
	typedef const Value*	pointer;
    typedef const Value&	const_reference;
};

template <class XalanDequeTraits, class XalanDeque>
struct  XalanDequeIterator
{
    typedef size_t  size_type;
    typedef typename XalanDequeTraits::value_type       value_type;
    typedef typename XalanDequeTraits::reference        reference;
    typedef typename XalanDequeTraits::pointer          pointer;
    typedef typename XalanDequeTraits::const_reference  const_reference;
    typedef ptrdiff_t		                            difference_type;

    typedef XalanDequeIterator<XalanDequeIteratorTraits<value_type>, XalanDeque> Iterator;

	typedef XALAN_STD_QUALIFIER random_access_iterator_tag iterator_category;

    XalanDequeIterator(XalanDeque*  deque,
                       size_type    pos) :
        m_deque(deque),
        m_pos(pos)
    {
    }

    XalanDequeIterator(const Iterator & iterator) :
        m_deque(iterator.m_deque),
        m_pos(iterator.m_pos)
    {
    }

    XalanDequeIterator& operator=(const Iterator & iterator)
    {
        m_deque = iterator.m_deque;
        m_pos = iterator.m_pos;
        return *this;
    }

    XalanDequeIterator& operator++()
    {
        ++m_pos;
        return *this;
    }

    XalanDequeIterator operator++(int)
    {
        XalanDequeIterator temp = *this;
        ++m_pos;
        return temp;
    }

    XalanDequeIterator& operator--()
    {
        --m_pos;
        return *this;
    }

    pointer operator->()
    {
        return &(*m_deque[m_pos]);
    }

    reference operator*()
    {
        return (*m_deque)[m_pos];
    }

    const_reference operator*() const
    {
        return (*m_deque)[m_pos];
    }

    XalanDequeIterator operator+(difference_type difference) const
    {
        return XalanDequeIterator(m_deque, m_pos + difference);
    }

    XalanDequeIterator operator-(difference_type difference) const
    {
        return XalanDequeIterator(m_deque, m_pos - difference);
    }

    difference_type operator-(const XalanDequeIterator &theRhs) const
    {
        return m_pos - theRhs.m_pos;
    }

    bool operator==(const XalanDequeIterator & theRhs) const
    {
        return (theRhs.m_deque == m_deque)
            &&  theRhs.m_pos == m_pos;
    }

    bool operator!=(const XalanDequeIterator & theRhs) const
    {
        return !(theRhs == *this);
    }

    XalanDeque* m_deque;
    size_type   m_pos;
};

/**
 * Xalan implementation of deque
 */
template <class Type, class ConstructionTraits = MemoryManagedConstructionTraits<Type> >
class XalanDeque
{
public:

    typedef size_t  size_type;

    typedef Type            value_type;
    typedef Type&           reference;
    typedef const Type&     const_reference;

    typedef XalanVector<Type, ConstructionTraits>	    BlockType;

    typedef XalanVector<BlockType*> BlockIndexType;

    typedef XalanDequeIterator<XalanDequeIteratorTraits<value_type>, XalanDeque> iterator;
    typedef XalanDequeIterator<XalanDequeConstIteratorTraits<value_type>, XalanDeque> const_iterator;

#if defined(XALAN_HAS_STD_ITERATORS)
    typedef XALAN_STD_QUALIFIER reverse_iterator<iterator>          reverse_iterator_;
    typedef XALAN_STD_QUALIFIER reverse_iterator<const_iterator>    const_reverse_iterator_;
#elif defined(XALAN_RW_NO_CLASS_PARTIAL_SPEC)
    typedef XALAN_STD_QUALIFIER reverse_iterator<
        iterator,
        XALAN_STD_QUALIFIER random_access_iterator_tag,
        value_type> reverse_iterator_;
    typedef XALAN_STD_QUALIFIER reverse_iterator<
        const_iterator,
        XALAN_STD_QUALIFIER random_access_iterator_tag,
        const value_type> const_reverse_iterator_;
#else
    typedef XALAN_STD_QUALIFIER reverse_iterator<iterator, value_type>                          reverse_iterator_;
    typedef XALAN_STD_QUALIFIER reverse_iterator<const_iterator, value_type, const_reference>   const_reverse_iterator_;
#endif

    typedef reverse_iterator_           reverse_iterator;
    typedef const_reverse_iterator_     const_reverse_iterator;

    XalanDeque(
    		MemoryManagerType& memoryManager,
            size_type initialSize = 0,
            size_type blockSize = 10) :
        m_memoryManager(&memoryManager),
        m_blockSize(blockSize),
        m_blockIndex(memoryManager,
                    initialSize / blockSize + (initialSize % blockSize == 0 ? 0 : 1)),
        m_freeBlockVector(memoryManager)
    {
        typename ConstructionTraits::Constructor::ConstructableType defaultValue(*m_memoryManager);

        XALAN_STD_QUALIFIER fill_n(XALAN_STD_QUALIFIER back_inserter(*this), initialSize, defaultValue.value);
    }

    XalanDeque(const XalanDeque& theRhs, MemoryManagerType& memoryManager) :
        m_memoryManager(&memoryManager),
        m_blockSize(theRhs.m_blockSize),
        m_blockIndex(*theRhs.m_memoryManager,
                    theRhs.size() / theRhs.m_blockSize + (theRhs.size() % theRhs.m_blockSize == 0 ? 0 : 1)),
        m_freeBlockVector(memoryManager)
    {
        XALAN_STD_QUALIFIER copy(theRhs.begin(), theRhs.end(), XALAN_STD_QUALIFIER back_inserter(*this));
    }

   static XalanDeque*
   create(
            MemoryManagerType&  theManager,
            size_type initialSize = 0,
            size_type blockSize = 10)
    {
        typedef XalanDeque ThisType;

        XalanMemMgrAutoPtr<ThisType, false> theGuard( theManager , (ThisType*)theManager.allocate(sizeof(ThisType)));

        ThisType* theResult = theGuard.get();

        new (theResult) ThisType(theManager, initialSize, blockSize);

        theGuard.release();

        return theResult;
    }

    ~XalanDeque()
    {
        clear();
        typename BlockIndexType::iterator iter = m_freeBlockVector.begin();

        while (iter != m_freeBlockVector.end())
        {
            (*iter)->~XalanVector<Type, ConstructionTraits>();
            deallocate(*iter);
            ++iter;
        }
    }

    iterator begin()
    {
        return iterator(this, 0);
    }

    const_iterator begin() const
    {
        return const_iterator(const_cast<XalanDeque*>(this), 0);
    }

    iterator end()
    {
        return iterator(this, size());
    }

    const_iterator end() const
    {
         return const_iterator(const_cast<XalanDeque*>(this), size());
    }

    const_reverse_iterator rbegin() const
    {
        return const_reverse_iterator(end());
    }

    const_reverse_iterator rend() const
    {
        return const_reverse_iterator(begin());
    }

    bool empty() const
    {
        return m_blockIndex.empty();
    }

    size_type size() const
    {
       if (m_blockIndex.empty())
       {
           return 0;
       }
       else
       {
           return (m_blockIndex.size() - 1) * m_blockSize
               +  m_blockIndex.back()->size();
       }
    }

    value_type& back()
    {
        return m_blockIndex.back()->back();
    }

    value_type& operator[](size_type index)
    {
        BlockType & block = *(m_blockIndex[index / m_blockSize]);
        return block[index % m_blockSize];
    }

    const value_type& operator[](size_type index) const
    {
        BlockType & block = *(m_blockIndex[index / m_blockSize]);
        return block[index % m_blockSize];
    }

    void clear()
    {
        typename BlockIndexType::iterator iter = m_blockIndex.begin();

        m_freeBlockVector.reserve(m_freeBlockVector.size() + m_blockIndex.size());

        while (iter != m_blockIndex.end())
        {
            (*iter)->clear();
            m_freeBlockVector.push_back(*iter);
            ++iter;
        }

        m_blockIndex.clear();
    }

    void push_back(const value_type & value)
    {
        if (m_blockIndex.empty() ||
            m_blockIndex.back()->size() >= m_blockSize)
        {
            m_blockIndex.push_back(getNewBlock());
        }

        m_blockIndex.back()->push_back(value);
    }

    void pop_back()
    {
        BlockType & lastBlock = *(m_blockIndex.back());
        lastBlock.pop_back();
        if (lastBlock.empty())
        {
            m_freeBlockVector.push_back(&lastBlock);
            m_blockIndex.pop_back();
        }
    }

    void resize(size_type newSize)
    {
        typename ConstructionTraits::Constructor::ConstructableType defaultValue(*m_memoryManager);
        if (newSize > size())
        {
            for (size_type i = 0; i < newSize - size(); ++i)
            {
                push_back(defaultValue.value);
            }
        }
        else
        {
            for (size_type i = 0; i < size() - newSize; ++i)
            {
                pop_back();
            }
        }
    }

    void swap(XalanDeque& theRhs)
    {
        MemoryManagerType* tempMemoryManager = m_memoryManager;
        m_memoryManager = theRhs.m_memoryManager;
        theRhs.m_memoryManager = tempMemoryManager;

        theRhs.m_blockIndex.swap(m_blockIndex);
        theRhs.m_freeBlockVector.swap(m_freeBlockVector);
    }

    XalanDeque & operator=(const XalanDeque & theRhs)
    {
        clear();
        XALAN_STD_QUALIFIER copy(theRhs.begin(), theRhs.end(), XALAN_STD_QUALIFIER back_inserter(*this));
        return *this;
    }

    MemoryManagerType&
    getMemoryManager()
    {
        assert (m_memoryManager != 0);

        return *m_memoryManager;
    }
protected:

    BlockType* getNewBlock()
    {
        BlockType * newBlock;

        if (m_freeBlockVector.empty())
        {
            newBlock = allocate(1);
            new (&*newBlock) BlockType(*m_memoryManager, m_blockSize);
        }
        else
        {
            newBlock = m_freeBlockVector.back();
            m_freeBlockVector.pop_back();
        }

        assert (newBlock != 0);

        return newBlock;
    }

    BlockType*
    allocate(size_type  size)
    {
        const size_type     theBytesNeeded = size * sizeof(BlockType);

        BlockType* pointer = (BlockType*)m_memoryManager->allocate(theBytesNeeded);

        assert(pointer != 0);

        return pointer;
     }

    void
    deallocate(BlockType*  pointer)
    {
    	m_memoryManager->deallocate(pointer);
    }

    MemoryManagerType*  m_memoryManager;
    const size_type     m_blockSize;

    BlockIndexType     m_blockIndex;
    BlockIndexType     m_freeBlockVector;

private:
	// Not implemented
	XalanDeque();
	XalanDeque(const XalanDeque&);

};

XALAN_CPP_NAMESPACE_END

#endif  // XALANDEQUE_HEADER_GUARD_1357924680

<commit_msg>Fix to enable build on BC++B6<commit_after>/*
 * Copyright 1999-2004 The Apache Software Foundation.
 *
 * 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.
 */

/**
 * @author Matthew Hoyt (mhoyt@ca.ibm.com)
 */

#if !defined(XALANDEQUE_HEADER_GUARD_1357924680)
#define XALANDEQUE_HEADER_GUARD_1357924680

// Base include file.  Must be first.
#include <xalanc/Include/PlatformDefinitions.hpp>

#include <xalanc/Include/XalanVector.hpp>
#include <xalanc/Include/XalanMemoryManagement.hpp>

XALAN_CPP_NAMESPACE_BEGIN

template <class Value>
struct XalanDequeIteratorTraits
{
	typedef Value	        value_type;
	typedef Value&	        reference;
	typedef Value*	        pointer;
    typedef const Value&    const_reference;
};

template <class Value>
struct XalanDequeConstIteratorTraits
{
	typedef Value	        value_type;
	typedef const Value&	reference;
	typedef const Value*	pointer;
    typedef const Value&	const_reference;
};

template <class XalanDequeTraits, class XalanDeque>
struct  XalanDequeIterator
{
    typedef size_t  size_type;
    typedef typename XalanDequeTraits::value_type       value_type;
    typedef typename XalanDequeTraits::reference        reference;
    typedef typename XalanDequeTraits::pointer          pointer;
    typedef typename XalanDequeTraits::const_reference  const_reference;
    typedef ptrdiff_t		                            difference_type;

    typedef XalanDequeIterator<XalanDequeIteratorTraits<value_type>, XalanDeque> Iterator;

	typedef XALAN_STD_QUALIFIER random_access_iterator_tag iterator_category;

    XalanDequeIterator(XalanDeque*  deque,
                       size_type    pos) :
        m_deque(deque),
        m_pos(pos)
    {
    }

    XalanDequeIterator(const Iterator & iterator) :
        m_deque(iterator.m_deque),
        m_pos(iterator.m_pos)
    {
    }

    XalanDequeIterator& operator=(const Iterator & iterator)
    {
        m_deque = iterator.m_deque;
        m_pos = iterator.m_pos;
        return *this;
    }

    XalanDequeIterator& operator++()
    {
        ++m_pos;
        return *this;
    }

    XalanDequeIterator operator++(int)
    {
        XalanDequeIterator temp = *this;
        ++m_pos;
        return temp;
    }

    XalanDequeIterator& operator--()
    {
        --m_pos;
        return *this;
    }

    pointer operator->()
    {
        return &(*m_deque[m_pos]);
    }

    reference operator*()
    {
        return (*m_deque)[m_pos];
    }

    const_reference operator*() const
    {
        return (*m_deque)[m_pos];
    }

    XalanDequeIterator operator+(difference_type difference) const
    {
        return XalanDequeIterator(m_deque, m_pos + difference);
    }

    XalanDequeIterator operator-(difference_type difference) const
    {
        return XalanDequeIterator(m_deque, m_pos - difference);
    }

    difference_type operator-(const XalanDequeIterator &theRhs) const
    {
        return m_pos - theRhs.m_pos;
    }

    bool operator==(const XalanDequeIterator & theRhs) const
    {
        return (theRhs.m_deque == m_deque)
            &&  theRhs.m_pos == m_pos;
    }

    bool operator!=(const XalanDequeIterator & theRhs) const
    {
        return !(theRhs == *this);
    }

    XalanDeque* m_deque;
    size_type   m_pos;
};

/**
 * Xalan implementation of deque
 */
template <class Type, class ConstructionTraits = MemoryManagedConstructionTraits<Type> >
class XalanDeque
{
public:

    typedef size_t  size_type;

    typedef Type            value_type;
    typedef Type&           reference;
    typedef const Type&     const_reference;

    typedef XalanVector<Type, ConstructionTraits>	    BlockType;

    typedef XalanVector<BlockType*> BlockIndexType;

    typedef XalanDeque<Type, ConstructionTraits>							ThisType;
    typedef XalanDequeIterator<XalanDequeIteratorTraits<value_type>, ThisType> 		iterator;
    typedef XalanDequeIterator<XalanDequeConstIteratorTraits<value_type>, ThisType> 	const_iterator;

#if defined(XALAN_HAS_STD_ITERATORS)
    typedef XALAN_STD_QUALIFIER reverse_iterator<iterator>          reverse_iterator_;
    typedef XALAN_STD_QUALIFIER reverse_iterator<const_iterator>    const_reverse_iterator_;
#elif defined(XALAN_RW_NO_CLASS_PARTIAL_SPEC)
    typedef XALAN_STD_QUALIFIER reverse_iterator<
        iterator,
        XALAN_STD_QUALIFIER random_access_iterator_tag,
        value_type> reverse_iterator_;
    typedef XALAN_STD_QUALIFIER reverse_iterator<
        const_iterator,
        XALAN_STD_QUALIFIER random_access_iterator_tag,
        const value_type> const_reverse_iterator_;
#else
    typedef XALAN_STD_QUALIFIER reverse_iterator<iterator, value_type>                          reverse_iterator_;
    typedef XALAN_STD_QUALIFIER reverse_iterator<const_iterator, value_type, const_reference>   const_reverse_iterator_;
#endif

    typedef reverse_iterator_           reverse_iterator;
    typedef const_reverse_iterator_     const_reverse_iterator;

    XalanDeque(
    		MemoryManagerType& memoryManager,
            size_type initialSize = 0,
            size_type blockSize = 10) :
        m_memoryManager(&memoryManager),
        m_blockSize(blockSize),
        m_blockIndex(memoryManager,
                    initialSize / blockSize + (initialSize % blockSize == 0 ? 0 : 1)),
        m_freeBlockVector(memoryManager)
    {
        typename ConstructionTraits::Constructor::ConstructableType defaultValue(*m_memoryManager);

        XALAN_STD_QUALIFIER fill_n(XALAN_STD_QUALIFIER back_inserter(*this), initialSize, defaultValue.value);
    }

    XalanDeque(const XalanDeque& theRhs, MemoryManagerType& memoryManager) :
        m_memoryManager(&memoryManager),
        m_blockSize(theRhs.m_blockSize),
        m_blockIndex(*theRhs.m_memoryManager,
                    theRhs.size() / theRhs.m_blockSize + (theRhs.size() % theRhs.m_blockSize == 0 ? 0 : 1)),
        m_freeBlockVector(memoryManager)
    {
        XALAN_STD_QUALIFIER copy(theRhs.begin(), theRhs.end(), XALAN_STD_QUALIFIER back_inserter(*this));
    }

   static XalanDeque*
   create(
            MemoryManagerType&  theManager,
            size_type initialSize = 0,
            size_type blockSize = 10)
    {
        typedef XalanDeque ThisType;

        XalanMemMgrAutoPtr<ThisType, false> theGuard( theManager , (ThisType*)theManager.allocate(sizeof(ThisType)));

        ThisType* theResult = theGuard.get();

        new (theResult) ThisType(theManager, initialSize, blockSize);

        theGuard.release();

        return theResult;
    }

    ~XalanDeque()
    {
        clear();
        typename BlockIndexType::iterator iter = m_freeBlockVector.begin();

        while (iter != m_freeBlockVector.end())
        {
            (*iter)->~XalanVector<Type, ConstructionTraits>();
            deallocate(*iter);
            ++iter;
        }
    }

    iterator begin()
    {
        return iterator(this, 0);
    }

    const_iterator begin() const
    {
        return const_iterator(const_cast<XalanDeque*>(this), 0);
    }

    iterator end()
    {
        return iterator(this, size());
    }

    const_iterator end() const
    {
         return const_iterator(const_cast<XalanDeque*>(this), size());
    }

    const_reverse_iterator rbegin() const
    {
        return const_reverse_iterator(end());
    }

    const_reverse_iterator rend() const
    {
        return const_reverse_iterator(begin());
    }

    bool empty() const
    {
        return m_blockIndex.empty();
    }

    size_type size() const
    {
       if (m_blockIndex.empty())
       {
           return 0;
       }
       else
       {
           return (m_blockIndex.size() - 1) * m_blockSize
               +  m_blockIndex.back()->size();
       }
    }

    value_type& back()
    {
        return m_blockIndex.back()->back();
    }

    value_type& operator[](size_type index)
    {
        BlockType & block = *(m_blockIndex[index / m_blockSize]);
        return block[index % m_blockSize];
    }

    const value_type& operator[](size_type index) const
    {
        BlockType & block = *(m_blockIndex[index / m_blockSize]);
        return block[index % m_blockSize];
    }

    void clear()
    {
        typename BlockIndexType::iterator iter = m_blockIndex.begin();

        m_freeBlockVector.reserve(m_freeBlockVector.size() + m_blockIndex.size());

        while (iter != m_blockIndex.end())
        {
            (*iter)->clear();
            m_freeBlockVector.push_back(*iter);
            ++iter;
        }

        m_blockIndex.clear();
    }

    void push_back(const value_type & value)
    {
        if (m_blockIndex.empty() ||
            m_blockIndex.back()->size() >= m_blockSize)
        {
            m_blockIndex.push_back(getNewBlock());
        }

        m_blockIndex.back()->push_back(value);
    }

    void pop_back()
    {
        BlockType & lastBlock = *(m_blockIndex.back());
        lastBlock.pop_back();
        if (lastBlock.empty())
        {
            m_freeBlockVector.push_back(&lastBlock);
            m_blockIndex.pop_back();
        }
    }

    void resize(size_type newSize)
    {
        typename ConstructionTraits::Constructor::ConstructableType defaultValue(*m_memoryManager);
        if (newSize > size())
        {
            for (size_type i = 0; i < newSize - size(); ++i)
            {
                push_back(defaultValue.value);
            }
        }
        else
        {
            for (size_type i = 0; i < size() - newSize; ++i)
            {
                pop_back();
            }
        }
    }

    void swap(XalanDeque& theRhs)
    {
        MemoryManagerType* tempMemoryManager = m_memoryManager;
        m_memoryManager = theRhs.m_memoryManager;
        theRhs.m_memoryManager = tempMemoryManager;

        theRhs.m_blockIndex.swap(m_blockIndex);
        theRhs.m_freeBlockVector.swap(m_freeBlockVector);
    }

    XalanDeque & operator=(const XalanDeque & theRhs)
    {
        clear();
        XALAN_STD_QUALIFIER copy(theRhs.begin(), theRhs.end(), XALAN_STD_QUALIFIER back_inserter(*this));
        return *this;
    }

    MemoryManagerType&
    getMemoryManager()
    {
        assert (m_memoryManager != 0);

        return *m_memoryManager;
    }
protected:

    BlockType* getNewBlock()
    {
        BlockType * newBlock;

        if (m_freeBlockVector.empty())
        {
            newBlock = allocate(1);
            new (&*newBlock) BlockType(*m_memoryManager, m_blockSize);
        }
        else
        {
            newBlock = m_freeBlockVector.back();
            m_freeBlockVector.pop_back();
        }

        assert (newBlock != 0);

        return newBlock;
    }

    BlockType*
    allocate(size_type  size)
    {
        const size_type     theBytesNeeded = size * sizeof(BlockType);

        BlockType* pointer = (BlockType*)m_memoryManager->allocate(theBytesNeeded);

        assert(pointer != 0);

        return pointer;
     }

    void
    deallocate(BlockType*  pointer)
    {
    	m_memoryManager->deallocate(pointer);
    }

    MemoryManagerType*  m_memoryManager;
    const size_type     m_blockSize;

    BlockIndexType     m_blockIndex;
    BlockIndexType     m_freeBlockVector;

private:
	// Not implemented
	XalanDeque();
	XalanDeque(const XalanDeque&);

};

XALAN_CPP_NAMESPACE_END

#endif  // XALANDEQUE_HEADER_GUARD_1357924680

<|endoftext|>


<commit_before>/*
 *  Copyright 2009 Utkin Dmitry
 *
 *  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.
 */

/*
 *  This file is part of the WSF Staff project.
 *  Please, visit http://code.google.com/p/staff for more information.
 */

#include <axiom.h>
#include <axis2_util.h>
#include <axiom_soap.h>
#include <map>
#include <rise/common/ExceptionTemplate.h>
#include <rise/common/exmacros.h>
#include "Runtime.h"

namespace staff
{
  class Runtime::RuntimeImpl
  {
  public:
    RuntimeImpl():
      m_pEnv(axutil_env_create_all("staff.log", GetAxis2LogLevel()))
    {
    }

    ~RuntimeImpl()
    {
      if (m_mEnv.size() != 0)
      {
        for (AxutilEnvMap::iterator itEnv = m_mEnv.begin(); itEnv != m_mEnv.end(); ++itEnv)
        {
          if (itEnv->second.pEnv)
          {
            axutil_env_free(itEnv->second.pEnv);
          }
        }
        m_mEnv.clear();
      }
      axutil_env_free(m_pEnv);
    }

    static axutil_log_levels_t GetAxis2LogLevel()
    {
      static axutil_log_levels_t eLogLevel = static_cast<axutil_log_levels_t>(-1);
      if (eLogLevel == static_cast<axutil_log_levels_t>(-1))
      {
        const char* szAxis2LogEnv = getenv("STAFF_AXIS2C_LOG_LEVEL");
        if (szAxis2LogEnv)
        {
          std::string sAxis2LogEnv(szAxis2LogEnv);
          if (sAxis2LogEnv == "CRITICAL")
          {
            eLogLevel = AXIS2_LOG_LEVEL_CRITICAL;
          }
          else
          if (sAxis2LogEnv == "WARNING")
          {
            eLogLevel = AXIS2_LOG_LEVEL_WARNING;
          }
          else
          if (sAxis2LogEnv == "INFO")
          {
            eLogLevel = AXIS2_LOG_LEVEL_INFO;
          }
          else
          if (sAxis2LogEnv == "DEBUG")
          {
            eLogLevel = AXIS2_LOG_LEVEL_DEBUG;
          }
          else
          if (sAxis2LogEnv == "USER")
          {
            eLogLevel = AXIS2_LOG_LEVEL_USER;
          }
          else
          if (sAxis2LogEnv == "TRACE")
          {
            eLogLevel = AXIS2_LOG_LEVEL_TRACE;
          }
          else
          {
            eLogLevel = AXIS2_LOG_LEVEL_WARNING;
          }
        }
        else
        {
          eLogLevel = AXIS2_LOG_LEVEL_WARNING;
        }
      }
      return eLogLevel;
    }

  public:
    struct AxutilEnvCounted
    {
      int nCounter;
      axutil_env_t* pEnv;

      AxutilEnvCounted():
        nCounter(1), pEnv(NULL)
      {
      }
    };

    typedef std::map<std::string, AxutilEnvCounted> AxutilEnvMap;

  public:
    AxutilEnvMap m_mEnv;
    axutil_env_t* m_pEnv;
  };

  Runtime::Runtime():
    m_pImpl(new RuntimeImpl)
  {
  }

  Runtime::~Runtime()
  {
    delete m_pImpl;
  }

  Runtime& Runtime::Inst()
  {
    static Runtime tInst;
    return tInst;
  }

  axutil_env_t* Runtime::GetAxis2Env()
  {
    return m_pImpl->m_pEnv;
  }

  axutil_env_t* Runtime::GetAxis2Env(const std::string& sEnvComponent)
  {
    if (sEnvComponent == "staff")
    {
      return m_pImpl->m_pEnv;
    }

    RuntimeImpl::AxutilEnvMap::iterator itEnv = m_pImpl->m_mEnv.find(sEnvComponent);
    if (itEnv == m_pImpl->m_mEnv.end())
    {
      axutil_env_t* pEnv = axutil_env_create_all((sEnvComponent + ".log").c_str(), RuntimeImpl::GetAxis2LogLevel());
      m_pImpl->m_mEnv[sEnvComponent].pEnv = pEnv;
      return pEnv;
    }

    ++itEnv->second.nCounter;
    return itEnv->second.pEnv;
  }

  void Runtime::FreeAxis2Env(const std::string& sEnvComponent)
  {
    RuntimeImpl::AxutilEnvMap::iterator itEnv = m_pImpl->m_mEnv.find(sEnvComponent);
    if (itEnv != m_pImpl->m_mEnv.end())
    {
      --itEnv->second.nCounter;
      if (itEnv->second.nCounter == 0)
      {
        axutil_env_free(itEnv->second.pEnv);
        m_pImpl->m_mEnv.erase(itEnv);
      }
    }
  }

  std::string Runtime::GetEnv(const std::string& rEnvVariable) const
  {
    const char* szEnv = getenv(rEnvVariable.c_str());
    RISE_ASSERTES(szEnv, rise::CLogicNoItemException,
                  "Environment variable " + rEnvVariable + " not found");
    return szEnv;
  }

  std::string Runtime::GetAxis2Home() const
  {
    return GetEnv("AXIS2C_HOME");
  }

  std::string Runtime::GetStaffHome() const
  {
    return GetEnv("STAFF_HOME");
  }

  std::string Runtime::GetComponentsHome() const
  {
    return GetStaffHome() + RISE_PATH_SEPARATOR + std::string("components");
  }

  std::string Runtime::GetComponentHome(const std::string& sComponent) const
  {
    return GetComponentsHome() + RISE_PATH_SEPARATOR + sComponent;
  }

}
<commit_msg>core: Runtime: fixed thread unsafety while concurent calling of GetAxis2Env and FreeAxis2Env functions<commit_after>/*
 *  Copyright 2009 Utkin Dmitry
 *
 *  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.
 */

/*
 *  This file is part of the WSF Staff project.
 *  Please, visit http://code.google.com/p/staff for more information.
 */

#include <axiom.h>
#include <axis2_util.h>
#include <axiom_soap.h>
#include <map>
#include <rise/common/ExceptionTemplate.h>
#include <rise/common/exmacros.h>
#include <rise/threading/CriticalSection.h>
#include "Runtime.h"

namespace staff
{
  class Runtime::RuntimeImpl
  {
  public:
    RuntimeImpl():
      m_pEnv(axutil_env_create_all("staff.log", GetAxis2LogLevel()))
    {
    }

    ~RuntimeImpl()
    {
      if (m_mEnv.size() != 0)
      {
        for (AxutilEnvMap::iterator itEnv = m_mEnv.begin(); itEnv != m_mEnv.end(); ++itEnv)
        {
          if (itEnv->second.pEnv)
          {
            axutil_env_free(itEnv->second.pEnv);
          }
        }
        m_mEnv.clear();
      }
      axutil_env_free(m_pEnv);
    }

    static axutil_log_levels_t GetAxis2LogLevel()
    {
      static axutil_log_levels_t eLogLevel = static_cast<axutil_log_levels_t>(-1);
      if (eLogLevel == static_cast<axutil_log_levels_t>(-1))
      {
        const char* szAxis2LogEnv = getenv("STAFF_AXIS2C_LOG_LEVEL");
        if (szAxis2LogEnv)
        {
          std::string sAxis2LogEnv(szAxis2LogEnv);
          if (sAxis2LogEnv == "CRITICAL")
          {
            eLogLevel = AXIS2_LOG_LEVEL_CRITICAL;
          }
          else
          if (sAxis2LogEnv == "WARNING")
          {
            eLogLevel = AXIS2_LOG_LEVEL_WARNING;
          }
          else
          if (sAxis2LogEnv == "INFO")
          {
            eLogLevel = AXIS2_LOG_LEVEL_INFO;
          }
          else
          if (sAxis2LogEnv == "DEBUG")
          {
            eLogLevel = AXIS2_LOG_LEVEL_DEBUG;
          }
          else
          if (sAxis2LogEnv == "USER")
          {
            eLogLevel = AXIS2_LOG_LEVEL_USER;
          }
          else
          if (sAxis2LogEnv == "TRACE")
          {
            eLogLevel = AXIS2_LOG_LEVEL_TRACE;
          }
          else
          {
            eLogLevel = AXIS2_LOG_LEVEL_WARNING;
          }
        }
        else
        {
          eLogLevel = AXIS2_LOG_LEVEL_WARNING;
        }
      }
      return eLogLevel;
    }

  public:
    struct AxutilEnvCounted
    {
      int nCounter;
      axutil_env_t* pEnv;

      AxutilEnvCounted():
        nCounter(1), pEnv(NULL)
      {
      }
    };

    typedef std::map<std::string, AxutilEnvCounted> AxutilEnvMap;

  public:
    AxutilEnvMap m_mEnv;
    axutil_env_t* m_pEnv;
    rise::threading::CCriticalSection m_tLock;
  };

  Runtime::Runtime():
    m_pImpl(new RuntimeImpl)
  {
  }

  Runtime::~Runtime()
  {
    delete m_pImpl;
  }

  Runtime& Runtime::Inst()
  {
    static Runtime tInst;
    return tInst;
  }

  axutil_env_t* Runtime::GetAxis2Env()
  {
    return m_pImpl->m_pEnv;
  }

  axutil_env_t* Runtime::GetAxis2Env(const std::string& sEnvComponent)
  {
    if (sEnvComponent == "staff")
    {
      return m_pImpl->m_pEnv;
    }

    {
      rise::threading::CScopedCriticalSection tScopedLock(m_pImpl->m_tLock);

      RuntimeImpl::AxutilEnvMap::iterator itEnv = m_pImpl->m_mEnv.find(sEnvComponent);
      if (itEnv == m_pImpl->m_mEnv.end())
      {
        axutil_env_t* pEnv = axutil_env_create_all((sEnvComponent + ".log").c_str(),
                                                   RuntimeImpl::GetAxis2LogLevel());
        m_pImpl->m_mEnv[sEnvComponent].pEnv = pEnv;
        return pEnv;
      }

      ++itEnv->second.nCounter;
      return itEnv->second.pEnv;
    }
  }

  void Runtime::FreeAxis2Env(const std::string& sEnvComponent)
  {
    rise::threading::CScopedCriticalSection tScopedLock(m_pImpl->m_tLock);

    RuntimeImpl::AxutilEnvMap::iterator itEnv = m_pImpl->m_mEnv.find(sEnvComponent);
    if (itEnv != m_pImpl->m_mEnv.end())
    {
      --itEnv->second.nCounter;
      if (itEnv->second.nCounter == 0)
      {
        axutil_env_free(itEnv->second.pEnv);
        m_pImpl->m_mEnv.erase(itEnv);
      }
    }
  }

  std::string Runtime::GetEnv(const std::string& rEnvVariable) const
  {
    const char* szEnv = getenv(rEnvVariable.c_str());
    RISE_ASSERTES(szEnv, rise::CLogicNoItemException,
                  "Environment variable " + rEnvVariable + " not found");
    return szEnv;
  }

  std::string Runtime::GetAxis2Home() const
  {
    return GetEnv("AXIS2C_HOME");
  }

  std::string Runtime::GetStaffHome() const
  {
    return GetEnv("STAFF_HOME");
  }

  std::string Runtime::GetComponentsHome() const
  {
    return GetStaffHome() + RISE_PATH_SEPARATOR + std::string("components");
  }

  std::string Runtime::GetComponentHome(const std::string& sComponent) const
  {
    return GetComponentsHome() + RISE_PATH_SEPARATOR + sComponent;
  }

}
<|endoftext|>


<commit_before>/*********************************************************************
 *
 *  Software License Agreement (BSD License)
 *
 *  Copyright (c) 2014, Christian Rose
 *                      Team Hector,
 *                      Technische Universität Darmstadt
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Technische Universität Darmstadt nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************/

#include <hector_small_arm_ros_control/hector_small_arm_control.hpp>

#include <controller_manager/controller_manager.h>

namespace hector_small_arm_control
{

Hector_Small_Arm_Control::Hector_Small_Arm_Control()
{
    joint_name_vector_.push_back("joint_0");
    joint_name_vector_.push_back("joint_1");
    joint_name_vector_.push_back("joint_2");
    joint_name_vector_.push_back("joint_3");
    joint_name_vector_.push_back("joint_4");
    joint_name_vector_.push_back("joint_5");

    joint_offset["joint_0"] = 0.14317154020265985;
    joint_offset["joint_1"] = -1.1351457830353746;
    joint_offset["joint_2"] = 1.5033011721279284;
    joint_offset["joint_3"] = 0.6749515466696822;
    joint_offset["joint_4"] = 0.32213596545598466;
    joint_offset["joint_5"] = 0;

  for(unsigned int i=0; i<joint_name_vector_.size(); i++)
    {
        joint_positions_[joint_name_vector_[i]] = 0.0;
        joint_velocitys_[joint_name_vector_[i]] = 0.0;
        joint_efforts_[joint_name_vector_[i]] = 0.0;

        joint_cmd_pubs_[joint_name_vector_[i]] = nh_.advertise<std_msgs::Float64>("/" + joint_name_vector_[i] + "/command", 5);

        ros::Subscriber sub = nh_.subscribe("/" + joint_name_vector_[i] + "/state", 1, &Hector_Small_Arm_Control::jointStateCallback, this);
        joint_state_subs_[joint_name_vector_[i]] = sub;

        nh_.setCallbackQueue(&subscriber_queue_);

        hardware_interface::JointStateHandle state_handle(joint_name_vector_[i], &joint_positions_[joint_name_vector_[i]], &joint_velocitys_[joint_name_vector_[i]], &joint_efforts_[joint_name_vector_[i]]);
        joint_state_interface_.registerHandle(state_handle);

        hardware_interface::JointHandle pos_handle(joint_state_interface_.getHandle(joint_name_vector_[i]), &joint_pos_cmds_[joint_name_vector_[i]]);
        position_joint_interface_.registerHandle(pos_handle);
    }

    registerInterface(&joint_state_interface_);
    registerInterface(&position_joint_interface_);

    subscriber_spinner_.reset(new ros::AsyncSpinner(1, &subscriber_queue_));
    subscriber_spinner_->start();

    _fake_dof_value = 0.0;
}

void Hector_Small_Arm_Control::cleanup()
{
    subscriber_spinner_->stop();
}

void Hector_Small_Arm_Control::read(ros::Time time, ros::Duration period)
{
    if(received_joint_states_.size()<5){
        return;
    }
    for(unsigned int i=0; i<joint_name_vector_.size()-1; i++)
    {
        joint_positions_[joint_name_vector_[i]] = received_joint_states_[joint_name_vector_[i]]->current_pos - joint_offset[joint_name_vector_[i]];
    }

    //take last dof as fake
    joint_positions_[joint_name_vector_[joint_name_vector_.size()-1]] = _fake_dof_value;
}

void Hector_Small_Arm_Control::write(ros::Time time, ros::Duration period)
{
    for(unsigned int i=0; i<joint_name_vector_.size(); i++)
      {
        std_msgs::Float64 msg;
        msg.data = joint_pos_cmds_[joint_name_vector_[i]];
        joint_cmd_pubs_[joint_name_vector_[i]].publish(msg);
    }

   //remember last joint value for fake 6. dof
   _fake_dof_value = joint_pos_cmds_[joint_name_vector_[joint_name_vector_.size()-1]];
}

void Hector_Small_Arm_Control::jointStateCallback(const dynamixel_msgs::JointStateConstPtr& dyn_joint_state)
{
   // received_joint_states_[dyn_joint_state->name] = dyn_joint_state;
}

}

int main(int argc, char** argv){

try{
        ROS_INFO("starting");
        ros::init(argc, argv, "hector_small_arm_control");

        hector_small_arm_control::Hector_Small_Arm_Control hector_small_arm;

        controller_manager::ControllerManager cm(&hector_small_arm);

        ros::AsyncSpinner spinner(4);
        spinner.start();

        ros::Rate loop_rate(50);

        ros::Time last_time = ros::Time::now();

        while (ros::ok())
                {
                    //ROS_INFO("in main loop");
                    loop_rate.sleep();

                    ros::Time current_time = ros::Time::now();
                    ros::Duration elapsed_time = current_time - last_time;
                    last_time = current_time;

                    //ROS_INFO("before read");
                    hector_small_arm.read(current_time, elapsed_time);
                    //ROS_INFO("after read");

                    //ROS_INFO("before cm.update");
                    cm.update(current_time, elapsed_time);
                    //ROS_INFO("after cm.update");

                    //ROS_INFO("before write");
                    hector_small_arm.write(current_time, elapsed_time);
                    //ROS_INFO("after write");
                }

        hector_small_arm.cleanup();
    }
    catch(...)
    {
        ROS_ERROR("Unhandled exception!");
        return -1;
    }

    return 0;
}
<commit_msg>offset for reading and writing now<commit_after>/*********************************************************************
 *
 *  Software License Agreement (BSD License)
 *
 *  Copyright (c) 2014, Christian Rose
 *                      Team Hector,
 *                      Technische Universität Darmstadt
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Technische Universität Darmstadt nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************/

#include <hector_small_arm_ros_control/hector_small_arm_control.hpp>

#include <controller_manager/controller_manager.h>

namespace hector_small_arm_control
{

Hector_Small_Arm_Control::Hector_Small_Arm_Control()
{
    joint_name_vector_.push_back("joint_0");
    joint_name_vector_.push_back("joint_1");
    joint_name_vector_.push_back("joint_2");
    joint_name_vector_.push_back("joint_3");
    joint_name_vector_.push_back("joint_4");
    joint_name_vector_.push_back("joint_5");

    joint_offset["joint_0"] = 0.14317154020265985;
    joint_offset["joint_1"] = -1.1351457830353746;
    joint_offset["joint_2"] = 1.5033011721279284;
    joint_offset["joint_3"] = 0.6749515466696822;
    joint_offset["joint_4"] = 0.32213596545598466;
    joint_offset["joint_5"] = 0;

  for(unsigned int i=0; i<joint_name_vector_.size(); i++)
    {
        joint_positions_[joint_name_vector_[i]] = 0.0;
        joint_velocitys_[joint_name_vector_[i]] = 0.0;
        joint_efforts_[joint_name_vector_[i]] = 0.0;

        joint_cmd_pubs_[joint_name_vector_[i]] = nh_.advertise<std_msgs::Float64>("/" + joint_name_vector_[i] + "/command", 5);

        ros::Subscriber sub = nh_.subscribe("/" + joint_name_vector_[i] + "/state", 1, &Hector_Small_Arm_Control::jointStateCallback, this);
        joint_state_subs_[joint_name_vector_[i]] = sub;

        nh_.setCallbackQueue(&subscriber_queue_);

        hardware_interface::JointStateHandle state_handle(joint_name_vector_[i], &joint_positions_[joint_name_vector_[i]], &joint_velocitys_[joint_name_vector_[i]], &joint_efforts_[joint_name_vector_[i]]);
        joint_state_interface_.registerHandle(state_handle);

        hardware_interface::JointHandle pos_handle(joint_state_interface_.getHandle(joint_name_vector_[i]), &joint_pos_cmds_[joint_name_vector_[i]]);
        position_joint_interface_.registerHandle(pos_handle);
    }

    registerInterface(&joint_state_interface_);
    registerInterface(&position_joint_interface_);

    subscriber_spinner_.reset(new ros::AsyncSpinner(1, &subscriber_queue_));
    subscriber_spinner_->start();

    _fake_dof_value = 0.0;
}

void Hector_Small_Arm_Control::cleanup()
{
    subscriber_spinner_->stop();
}

void Hector_Small_Arm_Control::read(ros::Time time, ros::Duration period)
{
    if(received_joint_states_.size()<5){
        return;
    }
    for(unsigned int i=0; i<joint_name_vector_.size()-1; i++)
    {
        joint_positions_[joint_name_vector_[i]] = received_joint_states_[joint_name_vector_[i]]->current_pos - joint_offset[joint_name_vector_[i]];
    }

    //take last dof as fake
    joint_positions_[joint_name_vector_[joint_name_vector_.size()-1]] = _fake_dof_value;
}

void Hector_Small_Arm_Control::write(ros::Time time, ros::Duration period)
{
    for(unsigned int i=0; i<joint_name_vector_.size(); i++)
      {
        std_msgs::Float64 msg;
        msg.data = joint_pos_cmds_[joint_name_vector_[i]] + joint_offset[joint_name_vector_[i]];
        joint_cmd_pubs_[joint_name_vector_[i]].publish(msg);
    }

   //remember last joint value for fake 6. dof
   _fake_dof_value = joint_pos_cmds_[joint_name_vector_[joint_name_vector_.size()-1]];
}

void Hector_Small_Arm_Control::jointStateCallback(const dynamixel_msgs::JointStateConstPtr& dyn_joint_state)
{
   // received_joint_states_[dyn_joint_state->name] = dyn_joint_state;
}

}

int main(int argc, char** argv){

try{
        ROS_INFO("starting");
        ros::init(argc, argv, "hector_small_arm_control");

        hector_small_arm_control::Hector_Small_Arm_Control hector_small_arm;

        controller_manager::ControllerManager cm(&hector_small_arm);

        ros::AsyncSpinner spinner(4);
        spinner.start();

        ros::Rate loop_rate(50);

        ros::Time last_time = ros::Time::now();

        while (ros::ok())
                {
                    //ROS_INFO("in main loop");
                    loop_rate.sleep();

                    ros::Time current_time = ros::Time::now();
                    ros::Duration elapsed_time = current_time - last_time;
                    last_time = current_time;

                    //ROS_INFO("before read");
                    hector_small_arm.read(current_time, elapsed_time);
                    //ROS_INFO("after read");

                    //ROS_INFO("before cm.update");
                    cm.update(current_time, elapsed_time);
                    //ROS_INFO("after cm.update");

                    //ROS_INFO("before write");
                    hector_small_arm.write(current_time, elapsed_time);
                    //ROS_INFO("after write");
                }

        hector_small_arm.cleanup();
    }
    catch(...)
    {
        ROS_ERROR("Unhandled exception!");
        return -1;
    }

    return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: bulitem.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: ka $ $Date: 2001-10-31 16:48:59 $
 *
 *  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 _SVX_BULITEM_HXX
#define _SVX_BULITEM_HXX

// include ---------------------------------------------------------------

// define ----------------------------------------------------------------

// Styles
#define BS_ABC_BIG          0
#define BS_ABC_SMALL        1
#define BS_ROMAN_BIG        2
#define BS_ROMAN_SMALL      3
#define BS_123              4
#define BS_NONE             5
#define BS_BULLET           6
#define BS_BMP              128

// Justification
#define BJ_HLEFT            0x01
#define BJ_HRIGHT           0x02
#define BJ_HCENTER          0x04
#define BJ_VTOP             0x08
#define BJ_VBOTTOM          0x10
#define BJ_VCENTER          0x20

// Valid-Bits
// Erstmal nur die Werte, die vom Dialog geaendert werden...
#define VALID_FONTCOLOR     0x0001
#define VALID_FONTNAME      0x0002
#define VALID_SYMBOL        0x0004
#define VALID_BITMAP        0x0008
#define VALID_SCALE         0x0010
#define VALID_START         0x0020
#define VALID_STYLE         0x0040
#define VALID_PREVTEXT      0x0080
#define VALID_FOLLOWTEXT    0x0100

#ifndef _SFXPOOLITEM_HXX //autogen
#include <svtools/poolitem.hxx>
#endif
#ifndef _VCL_FONT_HXX //autogen
#include <vcl/font.hxx>
#endif
#ifndef _GRFMGR_HXX //autogen
#include <goodies/grfmgr.hxx>
#endif

// class SvxBulletItem ---------------------------------------------------

class SvxBulletItem : public SfxPoolItem
{
    Font            aFont;
    GraphicObject*  pGraphicObject;
    String          aPrevText;
    String          aFollowText;
    USHORT          nStart;
    USHORT          nStyle;
    long            nWidth;
    USHORT          nScale;
    sal_Unicode     cSymbol;
    BYTE            nJustify;
    USHORT          nValidMask; // Nur temporaer fuer GetAttribs/SetAttribs, wegen des grossen Bullets

#ifdef _SVX_BULITEM_CXX
    void    SetDefaultFont_Impl();
    void    SetDefaults_Impl();
#endif

public:
    TYPEINFO();

    SvxBulletItem( USHORT nWhich = 0 );
    SvxBulletItem( BYTE nStyle, const Font& rFont, USHORT nStart = 0, USHORT nWhich = 0 );
    SvxBulletItem( const Font& rFont, sal_Unicode cSymbol, USHORT nWhich=0 );
    SvxBulletItem( const Bitmap&, USHORT nWhich = 0 );
    SvxBulletItem( const GraphicObject&, USHORT nWhich = 0 );
    SvxBulletItem( SvStream& rStrm, USHORT nWhich = 0 );
    SvxBulletItem( const SvxBulletItem& );
    ~SvxBulletItem();

    virtual SfxPoolItem*    Clone( SfxItemPool *pPool = 0 ) const;
    virtual SfxPoolItem*    Create( SvStream&, USHORT nVersion ) const;
    virtual SvStream&       Store( SvStream & , USHORT nItemVersion ) const;

    String              GetFullText() const;
    sal_Unicode         GetSymbol() const { return cSymbol; }
    String              GetPrevText() const { return aPrevText; }
    String              GetFollowText() const { return aFollowText; }

    USHORT              GetStart() const { return nStart; }
    long                GetWidth() const { return nWidth; }
    USHORT              GetStyle() const { return nStyle; }
    BYTE                GetJustification() const { return nJustify; }
    Font                GetFont() const { return aFont; }
    USHORT              GetScale() const { return nScale; }

    Bitmap              GetBitmap() const;
    void                SetBitmap( const Bitmap& rBmp );

    const GraphicObject& GetGraphicObject() const;
    void                 SetGraphicObject( const GraphicObject& rGraphicObject );

    void                SetSymbol( sal_Unicode c) { cSymbol = c; }
    void                SetPrevText( const String& rStr) { aPrevText = rStr;}
    void                SetFollowText(const String& rStr) { aFollowText=rStr;}

    void                SetStart( USHORT nNew ) { nStart = nNew; }
    void                SetWidth( long nNew ) { nWidth = nNew; }
    void                SetStyle( USHORT nNew ) { nStyle = nNew; }
    void                SetJustification( BYTE nNew ) { nJustify = nNew; }
    void                SetFont( const Font& rNew) { aFont = rNew; }
    void                SetScale( USHORT nNew ) { nScale = nNew; }

    virtual USHORT      GetVersion(USHORT nFileVersion) const;
    virtual int         operator==( const SfxPoolItem& ) const;
    virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
                                    SfxMapUnit eCoreMetric,
                                    SfxMapUnit ePresMetric,
                                    String &rText, const IntlWrapper * = 0 ) const;

    static void         StoreFont( SvStream&, const Font& );
    static Font         CreateFont( SvStream&, USHORT nVer );

    USHORT&             GetValidMask()                  { return nValidMask;    }
    USHORT              GetValidMask() const            { return nValidMask;    }
    USHORT              IsValid( USHORT nFlag ) const   { return nValidMask & nFlag; }
    void                SetValid( USHORT nFlag, BOOL bValid )
                        {
                            if ( bValid )
                                nValidMask |= nFlag;
                            else
                                nValidMask &= ~nFlag;
                        }
    void                CopyValidProperties( const SvxBulletItem& rCopyFrom );
};

#endif

<commit_msg>INTEGRATION: CWS visibility01 (1.3.1022); FILE MERGED 2004/12/06 08:10:10 mnicel 1.3.1022.1: Part of symbol visibility markup - #i35758#<commit_after>/*************************************************************************
 *
 *  $RCSfile: bulitem.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: kz $ $Date: 2005-01-21 14:10:27 $
 *
 *  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 _SVX_BULITEM_HXX
#define _SVX_BULITEM_HXX

// include ---------------------------------------------------------------

#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

// define ----------------------------------------------------------------

// Styles
#define BS_ABC_BIG          0
#define BS_ABC_SMALL        1
#define BS_ROMAN_BIG        2
#define BS_ROMAN_SMALL      3
#define BS_123              4
#define BS_NONE             5
#define BS_BULLET           6
#define BS_BMP              128

// Justification
#define BJ_HLEFT            0x01
#define BJ_HRIGHT           0x02
#define BJ_HCENTER          0x04
#define BJ_VTOP             0x08
#define BJ_VBOTTOM          0x10
#define BJ_VCENTER          0x20

// Valid-Bits
// Erstmal nur die Werte, die vom Dialog geaendert werden...
#define VALID_FONTCOLOR     0x0001
#define VALID_FONTNAME      0x0002
#define VALID_SYMBOL        0x0004
#define VALID_BITMAP        0x0008
#define VALID_SCALE         0x0010
#define VALID_START         0x0020
#define VALID_STYLE         0x0040
#define VALID_PREVTEXT      0x0080
#define VALID_FOLLOWTEXT    0x0100

#ifndef _SFXPOOLITEM_HXX //autogen
#include <svtools/poolitem.hxx>
#endif
#ifndef _VCL_FONT_HXX //autogen
#include <vcl/font.hxx>
#endif
#ifndef _GRFMGR_HXX //autogen
#include <goodies/grfmgr.hxx>
#endif

// class SvxBulletItem ---------------------------------------------------

class SVX_DLLPUBLIC SvxBulletItem : public SfxPoolItem
{
    Font            aFont;
    GraphicObject*  pGraphicObject;
    String          aPrevText;
    String          aFollowText;
    USHORT          nStart;
    USHORT          nStyle;
    long            nWidth;
    USHORT          nScale;
    sal_Unicode     cSymbol;
    BYTE            nJustify;
    USHORT          nValidMask; // Nur temporaer fuer GetAttribs/SetAttribs, wegen des grossen Bullets

#ifdef _SVX_BULITEM_CXX
    void    SetDefaultFont_Impl();
    void    SetDefaults_Impl();
#endif

public:
    TYPEINFO();

    SvxBulletItem( USHORT nWhich = 0 );
    SvxBulletItem( BYTE nStyle, const Font& rFont, USHORT nStart = 0, USHORT nWhich = 0 );
    SvxBulletItem( const Font& rFont, sal_Unicode cSymbol, USHORT nWhich=0 );
    SvxBulletItem( const Bitmap&, USHORT nWhich = 0 );
    SvxBulletItem( const GraphicObject&, USHORT nWhich = 0 );
    SvxBulletItem( SvStream& rStrm, USHORT nWhich = 0 );
    SvxBulletItem( const SvxBulletItem& );
    ~SvxBulletItem();

    virtual SfxPoolItem*    Clone( SfxItemPool *pPool = 0 ) const;
    virtual SfxPoolItem*    Create( SvStream&, USHORT nVersion ) const;
    virtual SvStream&       Store( SvStream & , USHORT nItemVersion ) const;

    String              GetFullText() const;
    sal_Unicode         GetSymbol() const { return cSymbol; }
    String              GetPrevText() const { return aPrevText; }
    String              GetFollowText() const { return aFollowText; }

    USHORT              GetStart() const { return nStart; }
    long                GetWidth() const { return nWidth; }
    USHORT              GetStyle() const { return nStyle; }
    BYTE                GetJustification() const { return nJustify; }
    Font                GetFont() const { return aFont; }
    USHORT              GetScale() const { return nScale; }

    Bitmap              GetBitmap() const;
    void                SetBitmap( const Bitmap& rBmp );

    const GraphicObject& GetGraphicObject() const;
    void                 SetGraphicObject( const GraphicObject& rGraphicObject );

    void                SetSymbol( sal_Unicode c) { cSymbol = c; }
    void                SetPrevText( const String& rStr) { aPrevText = rStr;}
    void                SetFollowText(const String& rStr) { aFollowText=rStr;}

    void                SetStart( USHORT nNew ) { nStart = nNew; }
    void                SetWidth( long nNew ) { nWidth = nNew; }
    void                SetStyle( USHORT nNew ) { nStyle = nNew; }
    void                SetJustification( BYTE nNew ) { nJustify = nNew; }
    void                SetFont( const Font& rNew) { aFont = rNew; }
    void                SetScale( USHORT nNew ) { nScale = nNew; }

    virtual USHORT      GetVersion(USHORT nFileVersion) const;
    virtual int         operator==( const SfxPoolItem& ) const;
    virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
                                    SfxMapUnit eCoreMetric,
                                    SfxMapUnit ePresMetric,
                                    String &rText, const IntlWrapper * = 0 ) const;

    static void         StoreFont( SvStream&, const Font& );
    static Font         CreateFont( SvStream&, USHORT nVer );

    USHORT&             GetValidMask()                  { return nValidMask;    }
    USHORT              GetValidMask() const            { return nValidMask;    }
    USHORT              IsValid( USHORT nFlag ) const   { return nValidMask & nFlag; }
    void                SetValid( USHORT nFlag, BOOL bValid )
                        {
                            if ( bValid )
                                nValidMask |= nFlag;
                            else
                                nValidMask &= ~nFlag;
                        }
    void                CopyValidProperties( const SvxBulletItem& rCopyFrom );
};

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: galmisc.hxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: ihi $ $Date: 2006-08-29 14:26:24 $
 *
 *  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 _SVX_GALMISC_HXX_
#define _SVX_GALMISC_HXX_

#include <sot/storage.hxx>
#include <tools/urlobj.hxx>
#include <svtools/imap.hxx>
#include <svtools/hint.hxx>
#include <svtools/transfer.hxx>
#include "svdobj.hxx"
#include "galobj.hxx"

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_AWT_XPROGRESSMONITOR_HPP
#include <com/sun/star/awt/XProgressMonitor.hpp>
#endif

#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

// -----------
// - Defines -
// -----------

#define IV_IMAPINFO             (UINT32('S')*0x00000001+UINT32('D')*0x00000100+UINT32('U')*0x00010000+UINT32('D')*0x01000000)
#define ID_IMAPINFO             2

#define USERDATA_HDL()          (LINK(this,SgaUserDataFactory,MakeUserData))

#define GAL_RESID( nId )        ResId( nId, GetGalleryResMgr() )
#define STREAMBUF_SIZE          16384L

#define SGA_IMPORT_NONE         0x0000
#define SGA_IMPORT_FILE         0x0001
#define SGA_IMPORT_INET         0x0002

#define GALLERY_PROGRESS_RANGE  10000

#define GALLERY_FG_COLOR        Application::GetSettings().GetStyleSettings().GetWindowTextColor()
#define GALLERY_BG_COLOR        Application::GetSettings().GetStyleSettings().GetWindowColor()
#define GALLERY_DLG_COLOR       Application::GetSettings().GetStyleSettings().GetDialogColor()

// -------------
// - Functions -
// -------------

class ResMgr;
class String;
class SvStream;
class Graphic;
class FmFormModel;
class ImageMap;
class Gallery;

SVX_DLLPUBLIC ResMgr*           GetGalleryResMgr();
USHORT          GalleryGraphicImport( const INetURLObject& rURL, Graphic& rGraphic, String& rFilterName, BOOL bShowProgress = FALSE );
BOOL            GallerySvDrawImport( SvStream& rIStm, FmFormModel& rModel );
BOOL            CreateIMapGraphic( const FmFormModel& rModel, Graphic& rGraphic, ImageMap& rImageMap );
SVX_DLLPUBLIC String            GetReducedString( const INetURLObject& rURL, ULONG nMaxLen );
String          GetSvDrawStreamNameFromURL( const INetURLObject& rSvDrawObjURL );

BOOL            FileExists( const INetURLObject& rURL );
BOOL            CreateDir(  const INetURLObject& rURL );
BOOL            CopyFile(  const INetURLObject& rSrcURL, const INetURLObject& rDstURL );
BOOL            KillFile( const INetURLObject& rURL );
BitmapEx        GalleryResGetBitmapEx( sal_uInt32 nId );

// ---------------
// - SgaIMapInfo -
// ---------------

class SgaIMapInfo : public SdrObjUserData, public SfxListener
{
    ImageMap                aImageMap;

public:
                            SgaIMapInfo() : SdrObjUserData( IV_IMAPINFO, ID_IMAPINFO, 0 ) {};

                            SgaIMapInfo( const ImageMap& rImageMap) :
                                SdrObjUserData( IV_IMAPINFO, ID_IMAPINFO, 0 ),
                                aImageMap( rImageMap ) {};

    virtual                 ~SgaIMapInfo() {};

    virtual SdrObjUserData* Clone( SdrObject* ) const
                            {
                                SgaIMapInfo* pInfo = new SgaIMapInfo;
                                pInfo->aImageMap = aImageMap;
                                return pInfo;
                            }

    const ImageMap&         GetImageMap() const { return aImageMap; }
};

// ----------------------
// - SgaUserDataFactory -
// ----------------------

class SgaUserDataFactory
{
public:
        SgaUserDataFactory() { SdrObjFactory::InsertMakeUserDataHdl( USERDATA_HDL() ); }
        ~SgaUserDataFactory() { SdrObjFactory::RemoveMakeUserDataHdl( USERDATA_HDL() ); }

        DECL_LINK( MakeUserData, SdrObjFactory* );
};

// -------------------
// - GalleryProgress -
// -------------------

class GraphicFilter;

class SVX_DLLPUBLIC GalleryProgress
{
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XProgressBar > mxProgressBar;
    GraphicFilter*                                                          mpFilter;

                                    DECL_LINK( Update, GraphicFilter * );

    public:

                                    GalleryProgress( GraphicFilter* pFilter = NULL );
                                    ~GalleryProgress();

    void                            Update( ULONG nVal, ULONG nMaxVal );
};

// -----------------------
// - GalleryTransferable -
// -----------------------

class Gallery;
class GalleryTheme;
class GraphicObject;

class GalleryTransferable : public TransferableHelper
{
friend class GalleryTheme;

private:

    GalleryTheme*                   mpTheme;
    SgaObjKind                      meObjectKind;
    sal_uInt32                      mnObjectPos;
    SotStorageStreamRef             mxModelStream;
    GraphicObject*                  mpGraphicObject;
    ImageMap*                       mpImageMap;
    INetURLObject*                  mpURL;

protected:

                                    GalleryTransferable( GalleryTheme* pTheme, ULONG nObjectPos, bool bLazy );
                                    ~GalleryTransferable();

    void                            InitData( bool bLazy );

    // TransferableHelper
    virtual void                    AddSupportedFormats();
    virtual sal_Bool                GetData( const ::com::sun::star::datatransfer::DataFlavor& rFlavor );
    virtual sal_Bool                WriteObject( SotStorageStreamRef& rxOStm, void* pUserObject, sal_uInt32 nUserObjectId, const ::com::sun::star::datatransfer::DataFlavor& rFlavor );
    virtual void                    DragFinished( sal_Int8 nDropAction );
    virtual void                    ObjectReleased();

    void                            CopyToClipboard( Window* pWindow );
    void                            StartDrag( Window* pWindow, sal_Int8 nDragSourceActions,
                                               sal_Int32 nDragPointer = DND_POINTER_NONE,
                                               sal_Int32 nDragImage = DND_IMAGE_NONE );
};

// ---------------
// - GalleryHint -
// ---------------

#define GALLERY_HINT_NONE               0x00000000
#define GALLERY_HINT_CLOSE_THEME        0x00000001
#define GALLERY_HINT_THEME_REMOVED      0x00000002
#define GALLERY_HINT_THEME_RENAMED      0x00000004
#define GALLERY_HINT_THEME_CREATED      0x00000008
#define GALLERY_HINT_THEME_UPDATEVIEW   0x00000010
#define GALLERY_HINT_CLOSE_OBJECT       0x00000020
#define GALLERY_HINT_OBJECT_REMOVED     0x00000040

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

class GalleryHint : public SfxHint
{
private:

    ULONG           mnType;
    String          maThemeName;
    String          maStringData;
    ULONG           mnData1;
    ULONG           mnData2;

public:

                    GalleryHint( ULONG nType, const String& rThemeName, ULONG nData1 = 0UL, ULONG nData2 = 0UL ) :
                        mnType( nType ), maThemeName( rThemeName ), mnData1( nData1 ), mnData2( nData2 ) {}

                    GalleryHint( ULONG nType, const String& rThemeName, const String& rStringData, ULONG nData1 = 0UL, ULONG nData2 = 0UL ) :
                        mnType( nType ), maThemeName( rThemeName ), maStringData( rStringData ), mnData1( nData1 ), mnData2( nData2 ) {}

    ULONG           GetType() const { return mnType; }
    const String&   GetThemeName() const { return maThemeName; }
    const String&   GetStringData() const { return maStringData; }
    ULONG           GetData1() const { return mnData1; }
    ULONG           GetData2() const { return mnData2; }
};

    #endif
<commit_msg>INTEGRATION: CWS sb59 (1.12.60); FILE MERGED 2006/08/03 13:47:03 cl 1.12.60.1: removed compiler warnings<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: galmisc.hxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: obo $ $Date: 2006-10-12 11:44:01 $
 *
 *  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 _SVX_GALMISC_HXX_
#define _SVX_GALMISC_HXX_

#include <sot/storage.hxx>
#include <tools/urlobj.hxx>
#include <svtools/imap.hxx>
#include <svtools/hint.hxx>
#include <svtools/transfer.hxx>
#include "svdobj.hxx"
#include "galobj.hxx"

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_AWT_XPROGRESSMONITOR_HPP
#include <com/sun/star/awt/XProgressMonitor.hpp>
#endif

#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

// -----------
// - Defines -
// -----------

#define IV_IMAPINFO             (UINT32('S')*0x00000001+UINT32('D')*0x00000100+UINT32('U')*0x00010000+UINT32('D')*0x01000000)
#define ID_IMAPINFO             2

#define USERDATA_HDL()          (LINK(this,SgaUserDataFactory,MakeUserData))

#define GAL_RESID( nId )        ResId( nId, GetGalleryResMgr() )
#define STREAMBUF_SIZE          16384L

#define SGA_IMPORT_NONE         0x0000
#define SGA_IMPORT_FILE         0x0001
#define SGA_IMPORT_INET         0x0002

#define GALLERY_PROGRESS_RANGE  10000

#define GALLERY_FG_COLOR        Application::GetSettings().GetStyleSettings().GetWindowTextColor()
#define GALLERY_BG_COLOR        Application::GetSettings().GetStyleSettings().GetWindowColor()
#define GALLERY_DLG_COLOR       Application::GetSettings().GetStyleSettings().GetDialogColor()

// -------------
// - Functions -
// -------------

class ResMgr;
class String;
class SvStream;
class Graphic;
class FmFormModel;
class ImageMap;
class Gallery;

SVX_DLLPUBLIC ResMgr*           GetGalleryResMgr();
USHORT          GalleryGraphicImport( const INetURLObject& rURL, Graphic& rGraphic, String& rFilterName, BOOL bShowProgress = FALSE );
BOOL            GallerySvDrawImport( SvStream& rIStm, FmFormModel& rModel );
BOOL            CreateIMapGraphic( const FmFormModel& rModel, Graphic& rGraphic, ImageMap& rImageMap );
SVX_DLLPUBLIC String            GetReducedString( const INetURLObject& rURL, ULONG nMaxLen );
String          GetSvDrawStreamNameFromURL( const INetURLObject& rSvDrawObjURL );

BOOL            FileExists( const INetURLObject& rURL );
BOOL            CreateDir(  const INetURLObject& rURL );
BOOL            CopyFile(  const INetURLObject& rSrcURL, const INetURLObject& rDstURL );
BOOL            KillFile( const INetURLObject& rURL );
BitmapEx        GalleryResGetBitmapEx( sal_uInt32 nId );

// ---------------
// - SgaIMapInfo -
// ---------------

class SgaIMapInfo : public SdrObjUserData, public SfxListener
{
    ImageMap                aImageMap;

public:
                            SgaIMapInfo() : SdrObjUserData( IV_IMAPINFO, ID_IMAPINFO, 0 ) {};

                            SgaIMapInfo( const ImageMap& rImageMap) :
                                SdrObjUserData( IV_IMAPINFO, ID_IMAPINFO, 0 ),
                                aImageMap( rImageMap ) {};

    virtual                 ~SgaIMapInfo() {};

    virtual SdrObjUserData* Clone( SdrObject* ) const
                            {
                                SgaIMapInfo* pInfo = new SgaIMapInfo;
                                pInfo->aImageMap = aImageMap;
                                return pInfo;
                            }

    const ImageMap&         GetImageMap() const { return aImageMap; }
};

// ----------------------
// - SgaUserDataFactory -
// ----------------------

class SgaUserDataFactory
{
public:
        SgaUserDataFactory() { SdrObjFactory::InsertMakeUserDataHdl( USERDATA_HDL() ); }
        ~SgaUserDataFactory() { SdrObjFactory::RemoveMakeUserDataHdl( USERDATA_HDL() ); }

        DECL_LINK( MakeUserData, SdrObjFactory* );
};

// -------------------
// - GalleryProgress -
// -------------------

class GraphicFilter;

class SVX_DLLPUBLIC GalleryProgress
{
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XProgressBar > mxProgressBar;
    GraphicFilter*                                                          mpFilter;

                                    DECL_LINK( Update, GraphicFilter * );

    public:

                                    GalleryProgress( GraphicFilter* pFilter = NULL );
                                    ~GalleryProgress();

    void                            Update( ULONG nVal, ULONG nMaxVal );
};

// -----------------------
// - GalleryTransferable -
// -----------------------

class Gallery;
class GalleryTheme;
class GraphicObject;

class GalleryTransferable : public TransferableHelper
{
friend class GalleryTheme;
using TransferableHelper::CopyToClipboard;

private:

    GalleryTheme*                   mpTheme;
    SgaObjKind                      meObjectKind;
    sal_uInt32                      mnObjectPos;
    SotStorageStreamRef             mxModelStream;
    GraphicObject*                  mpGraphicObject;
    ImageMap*                       mpImageMap;
    INetURLObject*                  mpURL;

protected:

                                    GalleryTransferable( GalleryTheme* pTheme, ULONG nObjectPos, bool bLazy );
                                    ~GalleryTransferable();

    void                            InitData( bool bLazy );

    // TransferableHelper
    virtual void                    AddSupportedFormats();
    virtual sal_Bool                GetData( const ::com::sun::star::datatransfer::DataFlavor& rFlavor );
    virtual sal_Bool                WriteObject( SotStorageStreamRef& rxOStm, void* pUserObject, sal_uInt32 nUserObjectId, const ::com::sun::star::datatransfer::DataFlavor& rFlavor );
    virtual void                    DragFinished( sal_Int8 nDropAction );
    virtual void                    ObjectReleased();

    void                            CopyToClipboard( Window* pWindow );
    void                            StartDrag( Window* pWindow, sal_Int8 nDragSourceActions,
                                               sal_Int32 nDragPointer = DND_POINTER_NONE,
                                               sal_Int32 nDragImage = DND_IMAGE_NONE );
};

// ---------------
// - GalleryHint -
// ---------------

#define GALLERY_HINT_NONE               0x00000000
#define GALLERY_HINT_CLOSE_THEME        0x00000001
#define GALLERY_HINT_THEME_REMOVED      0x00000002
#define GALLERY_HINT_THEME_RENAMED      0x00000004
#define GALLERY_HINT_THEME_CREATED      0x00000008
#define GALLERY_HINT_THEME_UPDATEVIEW   0x00000010
#define GALLERY_HINT_CLOSE_OBJECT       0x00000020
#define GALLERY_HINT_OBJECT_REMOVED     0x00000040

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

class GalleryHint : public SfxHint
{
private:

    ULONG           mnType;
    String          maThemeName;
    String          maStringData;
    ULONG           mnData1;
    ULONG           mnData2;

public:

                    GalleryHint( ULONG nType, const String& rThemeName, ULONG nData1 = 0UL, ULONG nData2 = 0UL ) :
                        mnType( nType ), maThemeName( rThemeName ), mnData1( nData1 ), mnData2( nData2 ) {}

                    GalleryHint( ULONG nType, const String& rThemeName, const String& rStringData, ULONG nData1 = 0UL, ULONG nData2 = 0UL ) :
                        mnType( nType ), maThemeName( rThemeName ), maStringData( rStringData ), mnData1( nData1 ), mnData2( nData2 ) {}

    ULONG           GetType() const { return mnType; }
    const String&   GetThemeName() const { return maThemeName; }
    const String&   GetStringData() const { return maStringData; }
    ULONG           GetData1() const { return mnData1; }
    ULONG           GetData2() const { return mnData2; }
};

    #endif
<|endoftext|>