<commit_before>// @(#)root/pyroot:$Id$
// Author: Wim Lavrijsen, Jan 2005

// Bindings
#include "PyROOT.h"
#include "PyStrings.h"
#include "ObjectProxy.h"
#include "Utility.h"

// ROOT
#include "TObject.h"
#include "TBufferFile.h"      // for pickling

//- data _______________________________________________________________________
R__EXTERN PyObject* gRootModule;

//____________________________________________________________________________
void PyROOT::op_dealloc_nofree( ObjectProxy* pyobj ) {
   if ( pyobj->fObject && ( pyobj->fFlags & ObjectProxy::kIsOwner ) ) {
      pyobj->ObjectIsA()->Destructor( pyobj->fObject );
   }
}

//____________________________________________________________________________
namespace PyROOT {

namespace {

//= PyROOT object proxy nullness checking ====================================
   PyObject* op_nonzero( ObjectProxy* self, void* )
   {
      return PyInt_FromLong( self->GetObject() ? 1 : 0 );
   }

//= PyROOT object proxy pickle support =======================================
   PyObject* op_reduce( ObjectProxy* self )
   {
   // Turn the object proxy instance into a character stream and return for
   // pickle, together with the callable object that can restore the stream
   // into the object proxy instance.

   // keep a borrowed reference around to the callable function for expanding;
   // because it is borrowed, it means that there can be no pickling during the
   // shutdown of the libPyROOT module
      static PyObject* s_expand = PyDict_GetItemString(
         PyModule_GetDict( gRootModule ),  const_cast< char* >( "_ObjectProxy__expand__" ) );

   // TBuffer and its derived classes can't write themselves, but can be created
   // directly from the buffer, so handle them in a special case
      static TClassRef s_bfClass( "TBufferFile" );

      TBufferFile* buff = 0;
      if ( s_bfClass == self->ObjectIsA() ) {
         buff = (TBufferFile*)self->GetObject();
      } else {
      // no cast is needed, but WriteObject taking a TClass argument is protected,
      // so use WriteObjectAny()
         static TBufferFile s_buff( TBuffer::kWrite );
         s_buff.Reset();
         if ( s_buff.WriteObjectAny( self->GetObject(), self->ObjectIsA() ) != 1 ) {
            PyErr_Format( PyExc_IOError,
               "could not stream object of type %s", self->ObjectIsA()->GetName() );
            return 0;
         }
         buff = &s_buff;
      }

   // use a string for the serialized result, as a python buffer will not copy
   // the buffer contents; use a string for the class name, used when casting
   // on reading back in (see RootModule.cxx:TObjectExpand)
      PyObject* res2 = PyTuple_New( 2 );
      PyTuple_SET_ITEM( res2, 0, PyString_FromStringAndSize( buff->Buffer(), buff->Length() ) );
      PyTuple_SET_ITEM( res2, 1, PyString_FromString( self->ObjectIsA()->GetName() ) );

      PyObject* result = PyTuple_New( 2 );
      Py_INCREF( s_expand );
      PyTuple_SET_ITEM( result, 0, s_expand );
      PyTuple_SET_ITEM( result, 1, res2 );

      return result;
   }

//____________________________________________________________________________
   PyMethodDef op_methods[] = {
      { (char*)"__nonzero__", (PyCFunction)op_nonzero, METH_NOARGS, NULL },
      { (char*)"__reduce__",  (PyCFunction)op_reduce,  METH_NOARGS, NULL },
      { (char*)NULL, NULL, 0, NULL }
   };

//= PyROOT object proxy construction/destruction =============================
   ObjectProxy* op_new( PyTypeObject* subtype, PyObject*, PyObject* )
   {
      ObjectProxy* pyobj = (ObjectProxy*)subtype->tp_alloc( subtype, 0 );
      pyobj->fObject = NULL;
      pyobj->fFlags  = 0;

      return pyobj;
   }

//____________________________________________________________________________
   void op_dealloc( ObjectProxy* pyobj )
   {
      op_dealloc_nofree( pyobj );
      pyobj->ob_type->tp_free( (PyObject*)pyobj );
   }

//____________________________________________________________________________
   PyObject* op_richcompare( ObjectProxy* self, ObjectProxy* other, int op )
   {
      if ( op != Py_EQ && op != Py_NE ) {
         Py_INCREF( Py_NotImplemented );
         return Py_NotImplemented;
      }

      bool bIsEq = false;

   // special case for None to compare True to a null-pointer
      if ( (PyObject*)other == Py_None && ! self->fObject )
         bIsEq = true;

   // type + held pointer value defines identity (will cover if other is not
   // actually an ObjectProxy, as ob_type will be unequal)
      else if ( self->ob_type == other->ob_type && self->fObject == other->fObject )
         bIsEq = true;

      if ( ( op == Py_EQ && bIsEq ) || ( op == Py_NE && ! bIsEq ) ) {
         Py_INCREF( Py_True );
         return Py_True;
      }

      Py_INCREF( Py_False );
      return Py_False;
   }

//____________________________________________________________________________
   PyObject* op_repr( ObjectProxy* pyobj )
   {
      TClass* klass = pyobj->ObjectIsA();
      std::string clName = klass ? klass->GetName() : "<unknown>";
      if ( pyobj->fFlags & ObjectProxy::kIsReference )
         clName.append( "*" );

   // need to prevent accidental derefs when just printing (usually unsafe)
      if ( ! PyObject_HasAttr( (PyObject*)pyobj, PyStrings::gDeref ) ) {
         PyObject* name = PyObject_CallMethod( (PyObject*)pyobj,
            const_cast< char* >( "GetName" ), const_cast< char* >( "" ) );

         if ( name ) {
            if ( PyString_GET_SIZE( name ) != 0 ) {
               PyObject* repr = PyString_FromFormat( "<ROOT.%s object (\"%s\") at %p>",
                  clName.c_str(), PyString_AS_STRING( name ), pyobj->fObject );
               Py_DECREF( name );
               return repr;
            }
            Py_DECREF( name );
         } else
            PyErr_Clear();
      }

   // get here if object has no method GetName() or name = ""
      return PyString_FromFormat( const_cast< char* >( "<ROOT.%s object at %p>" ),
         clName.c_str(), pyobj->fObject );
   }

//= PyROOT type number stubs to allow dynamic overrides ======================
#define PYROOT_STUB( name, op, pystring )                                     \
   PyObject* op_##name##_stub( PyObject* self, PyObject* other )              \
   {                                                                          \
   /* place holder to lazily install __name__ if a global overload is available */ \
      if ( ! Utility::AddBinaryOperator( self, other, #op, "__"#name"__" ) ) {\
         Py_INCREF( Py_NotImplemented );                                      \
         return Py_NotImplemented;                                            \
      }                                                                       \
                                                                              \
   /* redo the call, which will now go to the newly installed method */       \
      return PyObject_CallMethodObjArgs( self, pystring, other, NULL );       \
   }

PYROOT_STUB( add, +, PyStrings::gAdd )
PYROOT_STUB( sub, -, PyStrings::gSub )
PYROOT_STUB( mul, *, PyStrings::gMul )
PYROOT_STUB( div, /, PyStrings::gDiv )

//____________________________________________________________________________
   PyNumberMethods op_as_number = {
      (binaryfunc)op_add_stub,        // nb_add
      (binaryfunc)op_sub_stub,        // nb_subtract
      (binaryfunc)op_mul_stub,        // nb_multiply
      (binaryfunc)op_div_stub,        // nb_divide
      0,                              // nb_remainder
      0,                              // nb_divmod
      0,                              // nb_power
      0,                              // nb_negative
      0,                              // tp_positive
      0,                              // tp_absolute
      0,                              // tp_nonzero
      0,                              // nb_invert
      0,                              // nb_lshift
      0,                              // nb_rshift
      0,                              // nb_and
      0,                              // nb_xor
      0,                              // nb_or
      0,                              // nb_coerce
      0,                              // nb_int
      0,                              // nb_long
      0,                              // nb_float
      0,                              // nb_oct
      0,                              // nb_hex
      0,                              // nb_inplace_add
      0,                              // nb_inplace_subtract
      0,                              // nb_inplace_multiply
      0,                              // nb_inplace_divide
      0,                              // nb_inplace_remainder
      0,                              // nb_inplace_power
      0,                              // nb_inplace_lshift
      0,                              // nb_inplace_rshift
      0,                              // nb_inplace_and
      0,                              // nb_inplace_xor
      0,                              // nb_inplace_or
      0,                              // nb_floor_divide
      0,                              // nb_true_divide
      0,                              // nb_inplace_floor_divide
      0,                              // nb_inplace_true_divide
      0                               // nb_index
   };

} // unnamed namespace

//= PyROOT object proxy type =================================================
PyTypeObject ObjectProxy_Type = {
   PyObject_HEAD_INIT( &PyRootType_Type )
   0,                         // ob_size
   (char*)"ROOT.ObjectProxy", // tp_name
   sizeof(ObjectProxy),       // tp_basicsize
   0,                         // tp_itemsize
   (destructor)op_dealloc,    // tp_dealloc
   0,                         // tp_print
   0,                         // tp_getattr
   0,                         // tp_setattr
   0,                         // tp_compare
   (reprfunc)op_repr,         // tp_repr
   &op_as_number,             // tp_as_number
   0,                         // tp_as_sequence
   0,                         // tp_as_mapping
   0,                         // tp_hash
   0,                         // tp_call
   0,                         // tp_str
   0,                         // tp_getattro
   0,                         // tp_setattro
   0,                         // tp_as_buffer
   Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
      Py_TPFLAGS_HAVE_GC,                        // tp_flags
   (char*)"PyROOT object proxy (internal)",      // tp_doc
   0,                         // tp_traverse
   0,                         // tp_clear
   (richcmpfunc)op_richcompare,                  // tp_richcompare
   0,                         // tp_weaklistoffset
   0,                         // tp_iter
   0,                         // tp_iternext
   op_methods,                // tp_methods
   0,                         // tp_members
   0,                         // tp_getset
   0,                         // tp_base
   0,                         // tp_dict
   0,                         // tp_descr_get
   0,                         // tp_descr_set
   0,                         // tp_dictoffset
   0,                         // tp_init
   0,                         // tp_alloc
   (newfunc)op_new,           // tp_new
   0,                         // tp_free
   0,                         // tp_is_gc
   0,                         // tp_bases
   0,                         // tp_mro
   0,                         // tp_cache
   0,                         // tp_subclasses
   0                          // tp_weaklist
#if PY_MAJOR_VERSION >= 2 && PY_MINOR_VERSION >= 3
   , 0                        // tp_del
#endif
#if PY_MAJOR_VERSION >= 2 && PY_MINOR_VERSION >= 6
   , 0                        // tp_version_tag
#endif
};

} // namespace PyROOT
<commit_msg>a little too quick ...<commit_after>// @(#)root/pyroot:$Id$
// Author: Wim Lavrijsen, Jan 2005

// Bindings
#include "PyROOT.h"
#include "PyStrings.h"
#include "ObjectProxy.h"
#include "Utility.h"

// ROOT
#include "TObject.h"
#include "TBufferFile.h"      // for pickling

//- data _______________________________________________________________________
R__EXTERN PyObject* gRootModule;

//____________________________________________________________________________
void PyROOT::op_dealloc_nofree( ObjectProxy* pyobj ) {
   if ( pyobj->fObject && ( pyobj->fFlags & ObjectProxy::kIsOwner ) ) {
      pyobj->ObjectIsA()->Destructor( pyobj->fObject );
   }
}

//____________________________________________________________________________
namespace PyROOT {

namespace {

//= PyROOT object proxy nullness checking ====================================
   PyObject* op_nonzero( ObjectProxy* self, void* )
   {
      return PyInt_FromLong( self->GetObject() ? 1 : 0 );
   }

//= PyROOT object proxy pickle support =======================================
   PyObject* op_reduce( ObjectProxy* self )
   {
   // Turn the object proxy instance into a character stream and return for
   // pickle, together with the callable object that can restore the stream
   // into the object proxy instance.

   // keep a borrowed reference around to the callable function for expanding;
   // because it is borrowed, it means that there can be no pickling during the
   // shutdown of the libPyROOT module
      static PyObject* s_expand = PyDict_GetItemString(
         PyModule_GetDict( gRootModule ),  const_cast< char* >( "_ObjectProxy__expand__" ) );

   // TBuffer and its derived classes can't write themselves, but can be created
   // directly from the buffer, so handle them in a special case
      static TClassRef s_bfClass( "TBufferFile" );

      TBufferFile* buff = 0;
      if ( s_bfClass == self->ObjectIsA() ) {
         buff = (TBufferFile*)self->GetObject();
      } else {
      // no cast is needed, but WriteObject taking a TClass argument is protected,
      // so use WriteObjectAny()
         static TBufferFile s_buff( TBuffer::kWrite );
         s_buff.Reset();
         if ( s_buff.WriteObjectAny( self->GetObject(), self->ObjectIsA() ) != 1 ) {
            PyErr_Format( PyExc_IOError,
               "could not stream object of type %s", self->ObjectIsA()->GetName() );
            return 0;
         }
         buff = &s_buff;
      }

   // use a string for the serialized result, as a python buffer will not copy
   // the buffer contents; use a string for the class name, used when casting
   // on reading back in (see RootModule.cxx:TObjectExpand)
      PyObject* res2 = PyTuple_New( 2 );
      PyTuple_SET_ITEM( res2, 0, PyString_FromStringAndSize( buff->Buffer(), buff->Length() ) );
      PyTuple_SET_ITEM( res2, 1, PyString_FromString( self->ObjectIsA()->GetName() ) );

      PyObject* result = PyTuple_New( 2 );
      Py_INCREF( s_expand );
      PyTuple_SET_ITEM( result, 0, s_expand );
      PyTuple_SET_ITEM( result, 1, res2 );

      return result;
   }

//____________________________________________________________________________
   PyMethodDef op_methods[] = {
      { (char*)"__nonzero__", (PyCFunction)op_nonzero, METH_NOARGS, NULL },
      { (char*)"__reduce__",  (PyCFunction)op_reduce,  METH_NOARGS, NULL },
      { (char*)NULL, NULL, 0, NULL }
   };

//= PyROOT object proxy construction/destruction =============================
   ObjectProxy* op_new( PyTypeObject* subtype, PyObject*, PyObject* )
   {
      ObjectProxy* pyobj = (ObjectProxy*)subtype->tp_alloc( subtype, 0 );
      pyobj->fObject = NULL;
      pyobj->fFlags  = 0;

      return pyobj;
   }

//____________________________________________________________________________
   void op_dealloc( ObjectProxy* pyobj )
   {
      op_dealloc_nofree( pyobj );
      pyobj->ob_type->tp_free( (PyObject*)pyobj );
   }

//____________________________________________________________________________
   PyObject* op_richcompare( ObjectProxy* self, ObjectProxy* other, int op )
   {
      if ( op != Py_EQ && op != Py_NE ) {
         Py_INCREF( Py_NotImplemented );
         return Py_NotImplemented;
      }

      bool bIsEq = false;

   // special case for None to compare True to a null-pointer
      if ( (PyObject*)other == Py_None && ! self->fObject )
         bIsEq = true;

   // type + held pointer value defines identity (will cover if other is not
   // actually an ObjectProxy, as ob_type will be unequal)
      else if ( self->ob_type == other->ob_type && self->fObject == other->fObject )
         bIsEq = true;

      if ( ( op == Py_EQ && bIsEq ) || ( op == Py_NE && ! bIsEq ) ) {
         Py_INCREF( Py_True );
         return Py_True;
      }

      Py_INCREF( Py_False );
      return Py_False;
   }

//____________________________________________________________________________
   PyObject* op_repr( ObjectProxy* pyobj )
   {
      TClass* klass = pyobj->ObjectIsA();
      std::string clName = klass ? klass->GetName() : "<unknown>";
      if ( pyobj->fFlags & ObjectProxy::kIsReference )
         clName.append( "*" );

   // need to prevent accidental derefs when just printing (usually unsafe)
      if ( ! PyObject_HasAttr( (PyObject*)pyobj, PyStrings::gDeref ) ) {
         PyObject* name = PyObject_CallMethod( (PyObject*)pyobj,
            const_cast< char* >( "GetName" ), const_cast< char* >( "" ) );

         if ( name ) {
            if ( PyString_GET_SIZE( name ) != 0 ) {
               PyObject* repr = PyString_FromFormat( "<ROOT.%s object (\"%s\") at %p>",
                  clName.c_str(), PyString_AS_STRING( name ), pyobj->fObject );
               Py_DECREF( name );
               return repr;
            }
            Py_DECREF( name );
         } else
            PyErr_Clear();
      }

   // get here if object has no method GetName() or name = ""
      return PyString_FromFormat( const_cast< char* >( "<ROOT.%s object at %p>" ),
         clName.c_str(), pyobj->fObject );
   }

//= PyROOT type number stubs to allow dynamic overrides ======================
#define PYROOT_STUB( name, op, pystring )                                     \
   PyObject* op_##name##_stub( PyObject* self, PyObject* other )              \
   {                                                                          \
   /* place holder to lazily install __name__ if a global overload is available */ \
      if ( ! Utility::AddBinaryOperator( self, other, #op, "__"#name"__" ) ) {\
         Py_INCREF( Py_NotImplemented );                                      \
         return Py_NotImplemented;                                            \
      }                                                                       \
                                                                              \
   /* redo the call, which will now go to the newly installed method */       \
      return PyObject_CallMethodObjArgs( self, pystring, other, NULL );       \
   }

PYROOT_STUB( add, +, PyStrings::gAdd )
PYROOT_STUB( sub, -, PyStrings::gSub )
PYROOT_STUB( mul, *, PyStrings::gMul )
PYROOT_STUB( div, /, PyStrings::gDiv )

//____________________________________________________________________________
   PyNumberMethods op_as_number = {
      (binaryfunc)op_add_stub,        // nb_add
      (binaryfunc)op_sub_stub,        // nb_subtract
      (binaryfunc)op_mul_stub,        // nb_multiply
      (binaryfunc)op_div_stub,        // nb_divide
      0,                              // nb_remainder
      0,                              // nb_divmod
      0,                              // nb_power
      0,                              // nb_negative
      0,                              // tp_positive
      0,                              // tp_absolute
      0,                              // tp_nonzero
      0,                              // nb_invert
      0,                              // nb_lshift
      0,                              // nb_rshift
      0,                              // nb_and
      0,                              // nb_xor
      0,                              // nb_or
      0,                              // nb_coerce
      0,                              // nb_int
      0,                              // nb_long
      0,                              // nb_float
      0,                              // nb_oct
      0,                              // nb_hex
      0,                              // nb_inplace_add
      0,                              // nb_inplace_subtract
      0,                              // nb_inplace_multiply
      0,                              // nb_inplace_divide
      0,                              // nb_inplace_remainder
      0,                              // nb_inplace_power
      0,                              // nb_inplace_lshift
      0,                              // nb_inplace_rshift
      0,                              // nb_inplace_and
      0,                              // nb_inplace_xor
      0,                              // nb_inplace_or
      0,                              // nb_floor_divide
      0,                              // nb_true_divide
      0,                              // nb_inplace_floor_divide
      0,                              // nb_inplace_true_divide
      0                               // nb_index
   };

} // unnamed namespace

//= PyROOT object proxy type =================================================
PyTypeObject ObjectProxy_Type = {
   PyObject_HEAD_INIT( &PyRootType_Type )
   0,                         // ob_size
   (char*)"ROOT.ObjectProxy", // tp_name
   sizeof(ObjectProxy),       // tp_basicsize
   0,                         // tp_itemsize
   (destructor)op_dealloc,    // tp_dealloc
   0,                         // tp_print
   0,                         // tp_getattr
   0,                         // tp_setattr
   0,                         // tp_compare
   (reprfunc)op_repr,         // tp_repr
   0, //&op_as_number,             // tp_as_number
   0,                         // tp_as_sequence
   0,                         // tp_as_mapping
   0,                         // tp_hash
   0,                         // tp_call
   0,                         // tp_str
   0,                         // tp_getattro
   0,                         // tp_setattro
   0,                         // tp_as_buffer
   Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
      Py_TPFLAGS_HAVE_GC,                        // tp_flags
   (char*)"PyROOT object proxy (internal)",      // tp_doc
   0,                         // tp_traverse
   0,                         // tp_clear
   (richcmpfunc)op_richcompare,                  // tp_richcompare
   0,                         // tp_weaklistoffset
   0,                         // tp_iter
   0,                         // tp_iternext
   op_methods,                // tp_methods
   0,                         // tp_members
   0,                         // tp_getset
   0,                         // tp_base
   0,                         // tp_dict
   0,                         // tp_descr_get
   0,                         // tp_descr_set
   0,                         // tp_dictoffset
   0,                         // tp_init
   0,                         // tp_alloc
   (newfunc)op_new,           // tp_new
   0,                         // tp_free
   0,                         // tp_is_gc
   0,                         // tp_bases
   0,                         // tp_mro
   0,                         // tp_cache
   0,                         // tp_subclasses
   0                          // tp_weaklist
#if PY_MAJOR_VERSION >= 2 && PY_MINOR_VERSION >= 3
   , 0                        // tp_del
#endif
#if PY_MAJOR_VERSION >= 2 && PY_MINOR_VERSION >= 6
   , 0                        // tp_version_tag
#endif
};

} // namespace PyROOT
<|endoftext|>


<commit_before><commit_msg>relocate num2bin and clean up comments<commit_after><|endoftext|>


<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.

Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.

Bohrium is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the
GNU Lesser General Public License along with Bohrium.

If not, see <http://www.gnu.org/licenses/>.
*/

#pragma once

#include "BhBase.hpp"
#include "SVector.hpp"
#include <ostream>
#include <vector>

namespace bhxx {

/** Class which enqueues an BhBase object for deletion
 *  with the Bohrium Runtime, but does not actually delete
 *  it straight away.
 *
 *  \note This is needed to ensure that all BhBase objects
 *  are still around until the list of instructions has
 *  been emptied.
 */
struct RuntimeDeleter {
    void operator()(BhBase* ptr) const;
};

/** Helper function to make shared pointers to BhBase,
 *  which use the RuntimeDeleter as their deleter */
template <typename... Args>
std::shared_ptr<BhBase> make_base_ptr(Args... args) {
    return std::shared_ptr<BhBase>(new BhBase(std::forward<Args>(args)...),
                                   RuntimeDeleter{});
}

template <typename T>
class BhArray {
  public:
    // The data type of each array element
    typedef T scalar_type;
    // The array offset (from the start of the base in number of elements)
    size_t offset;
    // The array shape (size of each dimension in number of elements)
    Shape shape;
    // The array stride (the absolute stride of each dimension in number of elements)
    Stride stride;
    // Pointer to the base of this array
    std::shared_ptr<BhBase> base;

    /** Create a new view */
    BhArray(Shape shape_, Stride stride_, const size_t offset_ = 0)
          : offset(offset_),
            shape(shape_),
            stride(std::move(stride_)),
            base(make_base_ptr(T(0), shape_.prod())) {
        assert(shape.size() == stride.size());
    }

    /** Create a new view (contiguous stride, row-major) */
    BhArray(Shape shape) : BhArray(shape, contiguous_stride(shape), 0) {}

    /** Create a view that points to the given base
     *
     *  \note The caller should make sure that the shared pointer
     *        uses the RuntimeDeleter as its deleter, since this is
     *        implicitly assumed throughout, i.e. if one wants to
     *        construct a BhBase object, use the make_base_ptr
     *        helper function.
     */
    BhArray(std::shared_ptr<BhBase> base_, Shape shape_, Stride stride_,
            const size_t offset_ = 0)
          : offset(offset_),
            shape(std::move(shape_)),
            stride(std::move(stride_)),
            base(std::move(base_)) {
        assert(shape.size() == stride.size());
    }

    /** Create a view that points to the given base (contiguous stride, row-major)
     *
     *  \note The caller should make sure that the shared pointer
     *        uses the RuntimeDeleter as its deleter, since this is
     *        implicitly assumed throughout, i.e. if one wants to
     *        construct a BhBase object, use the make_base_ptr
     *        helper function.
     */
    BhArray(std::shared_ptr<BhBase> base, Shape shape)
          : BhArray(std::move(base), shape, contiguous_stride(shape), 0) {
        assert(n_elem() == shape.prod());
    }

    //
    // Information
    //

    /** Return the rank of the BhArray */
    size_t rank() const {
        assert(shape.size() == stride.size());
        return shape.size();
    }

    /** Return the number of elements */
    size_t n_elem() const { return shape.prod(); }

    /** Return whether the view is contiguous and row-major */
    bool is_contiguous() const;

    //
    // Data access
    //
    /** Is the data referenced by this view's base array already
     *  allocated, i.e. initialised */
    bool is_data_initialised() const { return base->data != nullptr; }

    //@{
    /** Obtain the data pointer of the base array, not taking
     *  ownership of any kind.
     *
     *  \note This pointer might be a nullptr if the data in
     *        the base data is not initialised.
     *
     *  \note No flush is done automatically. The data might be
     *        out of sync with Bohrium.
     */
    const T* data() const { return static_cast<T*>(base->data); }
    T*       data() { return static_cast<T*>(base->data); }
    //@}

    //
    // Routines
    //

    // Pretty printing the content of the array
    // TODO: for now it always print the flatten array
    void pprint(std::ostream& os) const;
};

template <typename T>
std::ostream& operator<<(std::ostream& os, const BhArray<T>& ary) {
    ary.pprint(os);
    return os;
}

}  // namespace bhxx
<commit_msg>Do not allow Arrays with a zero dimension<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.

Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.

Bohrium is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the
GNU Lesser General Public License along with Bohrium.

If not, see <http://www.gnu.org/licenses/>.
*/

#pragma once

#include "BhBase.hpp"
#include "SVector.hpp"
#include <ostream>
#include <vector>

namespace bhxx {

/** Class which enqueues an BhBase object for deletion
 *  with the Bohrium Runtime, but does not actually delete
 *  it straight away.
 *
 *  \note This is needed to ensure that all BhBase objects
 *  are still around until the list of instructions has
 *  been emptied.
 */
struct RuntimeDeleter {
    void operator()(BhBase* ptr) const;
};

/** Helper function to make shared pointers to BhBase,
 *  which use the RuntimeDeleter as their deleter */
template <typename... Args>
std::shared_ptr<BhBase> make_base_ptr(Args... args) {
    return std::shared_ptr<BhBase>(new BhBase(std::forward<Args>(args)...),
                                   RuntimeDeleter{});
}

template <typename T>
class BhArray {
  public:
    // The data type of each array element
    typedef T scalar_type;
    // The array offset (from the start of the base in number of elements)
    size_t offset;
    // The array shape (size of each dimension in number of elements)
    Shape shape;
    // The array stride (the absolute stride of each dimension in number of elements)
    Stride stride;
    // Pointer to the base of this array
    std::shared_ptr<BhBase> base;

    /** Create a new view */
    BhArray(Shape shape_, Stride stride_, const size_t offset_ = 0)
          : offset(offset_),
            shape(shape_),
            stride(std::move(stride_)),
            base(make_base_ptr(T(0), shape_.prod())) {
        assert(shape.size() == stride.size());
        assert(shape.prod() > 0);
    }

    /** Create a new view (contiguous stride, row-major) */
    BhArray(Shape shape) : BhArray(shape, contiguous_stride(shape), 0) {}

    /** Create a view that points to the given base
     *
     *  \note The caller should make sure that the shared pointer
     *        uses the RuntimeDeleter as its deleter, since this is
     *        implicitly assumed throughout, i.e. if one wants to
     *        construct a BhBase object, use the make_base_ptr
     *        helper function.
     */
    BhArray(std::shared_ptr<BhBase> base_, Shape shape_, Stride stride_,
            const size_t offset_ = 0)
          : offset(offset_),
            shape(std::move(shape_)),
            stride(std::move(stride_)),
            base(std::move(base_)) {
        assert(shape.size() == stride.size());
        assert(shape.prod() > 0);
    }

    /** Create a view that points to the given base (contiguous stride, row-major)
     *
     *  \note The caller should make sure that the shared pointer
     *        uses the RuntimeDeleter as its deleter, since this is
     *        implicitly assumed throughout, i.e. if one wants to
     *        construct a BhBase object, use the make_base_ptr
     *        helper function.
     */
    BhArray(std::shared_ptr<BhBase> base, Shape shape)
          : BhArray(std::move(base), shape, contiguous_stride(shape), 0) {
        assert(base->nelem == shape.prod());
    }

    //
    // Information
    //

    /** Return the rank of the BhArray */
    size_t rank() const {
        assert(shape.size() == stride.size());
        return shape.size();
    }

    /** Return the number of elements */
    size_t n_elem() const { return shape.prod(); }

    /** Return whether the view is contiguous and row-major */
    bool is_contiguous() const;

    //
    // Data access
    //
    /** Is the data referenced by this view's base array already
     *  allocated, i.e. initialised */
    bool is_data_initialised() const { return base->data != nullptr; }

    //@{
    /** Obtain the data pointer of the base array, not taking
     *  ownership of any kind.
     *
     *  \note This pointer might be a nullptr if the data in
     *        the base data is not initialised.
     *
     *  \note No flush is done automatically. The data might be
     *        out of sync with Bohrium.
     */
    const T* data() const { return static_cast<T*>(base->data); }
    T*       data() { return static_cast<T*>(base->data); }
    //@}

    //
    // Routines
    //

    // Pretty printing the content of the array
    // TODO: for now it always print the flatten array
    void pprint(std::ostream& os) const;
};

template <typename T>
std::ostream& operator<<(std::ostream& os, const BhArray<T>& ary) {
    ary.pprint(os);
    return os;
}

}  // namespace bhxx
<|endoftext|>


<commit_before>#include "fountain.h"
#include "TestApplication.h"

using namespace fei;

Texture tex;
Camera cam;
TestApplication testApp;
Clock mainClock;
ShaderProgram shader;
Image *image, *image2;
ImagePool testPool;

void test()
{
	cam.setCameraSize(Render::getInstance()->getViewport().getSize());
	auto *joystick = fei::Control::getInstance()->getJoystick();
	if (joystick) {
		Vec2 speed = joystick->getAxes() * 500.0f * (float)mainClock.getDeltaTime();
		image->setAngle(speed.getAngle());
		speed = joystick->getDirection() * 50.0f * (float)mainClock.getDeltaTime();
		tex.rotate(-speed.x);
	}
	cam.update();
	tex.draw();
	image->draw();
	image2->draw();
	mainClock.tick();
}

void TestApplication::engineSetting(fei::Engine *eg)
{
	if (!eg) return;
	eg->window->setSize(800, 600);
	eg->window->setTitle("fountain-tests");
	eg->window->setResizable(false);

	eg->setFrameFunc(test);

	Render::getInstance()->setViewport(fei::Rect(0, 0, 800, 600));

	cam.setCameraSize(fei::Vec2(800, 600));
	tex.loadFile("test.png");
	//image = tex.getImage(fei::Vec2(100.0f), fei::Vec2(200.0f));
	//image2 = image.getImage(fei::Vec2(0.0f), fei::Vec2(100.0f));
	shader.loadFile("vs.vert", "fs.frag");
	tex.setScale(0.4f);
	tex.setAnchor(Vec2(0.0f, -256.0f));
	tex.setShader(&shader);
	testPool.load(tex, "test.sip");
	image = testPool.getImage(0);
	image->setPosition(fei::Vec2(0.0f, 256.0f));
	image2 = testPool.getImage(1);

	//Math::getInstance()->setRandomSeed(9312);
	//Render::getInstance()->setClearColor(FEI_Blue);
	//Scene::getInstance()->gotoScene(new TestScene());
}

int main()
{
	testApp.run();
	return 0;
}
<commit_msg>edit fountain-test<commit_after>#include "fountain.h"
#include "TestApplication.h"

using namespace fei;

Texture tex;
Camera cam;
TestApplication testApp;
Clock mainClock;
Image *image, *image2;
ImagePool testPool;

void test()
{
	cam.setCameraSize(Render::getInstance()->getViewport().getSize());
	auto *joystick = fei::Control::getInstance()->getJoystick();
	if (joystick) {
		Vec2 speed = joystick->getAxes() * 500.0f * (float)mainClock.getDeltaTime();
		image->setAngle(speed.getAngle());
		speed = joystick->getDirection() * 50.0f * (float)mainClock.getDeltaTime();
		tex.rotate(-speed.x);
	}
	cam.update();
	tex.draw();
	image->draw();
	image2->draw();
	mainClock.tick();
}

void TestApplication::engineSetting(fei::Engine *eg)
{
	if (!eg) return;
	eg->window->setSize(800, 600);
	eg->window->setTitle("fountain-tests");
	eg->window->setResizable(false);

	eg->setFrameFunc(test);

	cam.setCameraSize(fei::Vec2(800, 600));
	tex.loadFile("test.png");

	testPool.load(tex, "test.sip");
	image = testPool.getImage(0);
	image2 = testPool.getImage(1);
	image->setPosition(fei::Vec2(0.0f, 256.0f));

	//Math::getInstance()->setRandomSeed(9312);
	//Render::getInstance()->setClearColor(FEI_Blue);
	//Scene::getInstance()->gotoScene(new TestScene());
}

int main()
{
	testApp.run();
	return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/renderer/extensions/experimental.app_custom_bindings.h"

#include "base/string_number_conversions.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebBlob.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebSerializedScriptValue.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h"

using WebKit::WebBlob;
using WebKit::WebSerializedScriptValue;
using WebKit::WebString;

namespace {

v8::Handle<v8::Value> DeserializeString(const v8::Arguments &args) {
  DCHECK(args.Length() == 1);
  DCHECK(args[0]->IsString());

  std::string data_v8(*v8::String::Utf8Value(args[0]));
  WebString data_webstring = WebString::fromUTF8(data_v8);
  WebSerializedScriptValue serialized =
      WebSerializedScriptValue::fromString(data_webstring);
  return serialized.deserialize();
}

v8::Handle<v8::Value> CreateBlob(const v8::Arguments &args) {
  DCHECK(args.Length() == 2);
  DCHECK(args[0]->IsString());
  DCHECK(args[1]->IsNumber());

  std::string blob_file_path(*v8::String::Utf8Value(args[0]));
  std::string blob_length_string(*v8::String::Utf8Value(args[1]));
  int64 blob_length;
  DCHECK(base::StringToInt64(blob_length_string, &blob_length));
  WebKit::WebBlob web_blob = WebBlob::createFromFile(
      WebString::fromUTF8(blob_file_path), blob_length);
  return web_blob.toV8Value();
}

}  // namespace

namespace extensions {

ExperimentalAppCustomBindings::ExperimentalAppCustomBindings()
    : ChromeV8Extension(NULL) {
  RouteStaticFunction("DeserializeString", &DeserializeString);
  RouteStaticFunction("CreateBlob", &CreateBlob);
}

}  // namespace extensions
<commit_msg>Fix a build break on official builders. This change initializes a variable 'blob_length' to fix build breaks on the "Google Chrome Mac" bot, the "Google Chrome Linux x86" bot, the "Google Chrome Linux x64" bot.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/renderer/extensions/experimental.app_custom_bindings.h"

#include "base/string_number_conversions.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebBlob.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebSerializedScriptValue.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h"

using WebKit::WebBlob;
using WebKit::WebSerializedScriptValue;
using WebKit::WebString;

namespace {

v8::Handle<v8::Value> DeserializeString(const v8::Arguments &args) {
  DCHECK(args.Length() == 1);
  DCHECK(args[0]->IsString());

  std::string data_v8(*v8::String::Utf8Value(args[0]));
  WebString data_webstring = WebString::fromUTF8(data_v8);
  WebSerializedScriptValue serialized =
      WebSerializedScriptValue::fromString(data_webstring);
  return serialized.deserialize();
}

v8::Handle<v8::Value> CreateBlob(const v8::Arguments &args) {
  DCHECK(args.Length() == 2);
  DCHECK(args[0]->IsString());
  DCHECK(args[1]->IsNumber());

  std::string blob_file_path(*v8::String::Utf8Value(args[0]));
  std::string blob_length_string(*v8::String::Utf8Value(args[1]));
  int64 blob_length = 0;
  DCHECK(base::StringToInt64(blob_length_string, &blob_length));
  WebKit::WebBlob web_blob = WebBlob::createFromFile(
      WebString::fromUTF8(blob_file_path), blob_length);
  return web_blob.toV8Value();
}

}  // namespace

namespace extensions {

ExperimentalAppCustomBindings::ExperimentalAppCustomBindings()
    : ChromeV8Extension(NULL) {
  RouteStaticFunction("DeserializeString", &DeserializeString);
  RouteStaticFunction("CreateBlob", &CreateBlob);
}

}  // namespace extensions
<|endoftext|>


<commit_before>/*
 * FrameProcessorPlugin.cpp
 *
 *  Created on: 2 Jun 2016
 *      Author: gnx91527
 */

#include "FrameProcessorPlugin.h"

namespace FrameProcessor
{
  const std::string FrameProcessorPlugin::META_RX_INTERFACE        = "inproc://meta_rx";

  /**
   * Constructor, initialises name_.
   */
  FrameProcessorPlugin::FrameProcessorPlugin() :
      name_(""),
	  metaChannel_(ZMQ_PUSH)
  {
    logger_ = log4cxx::Logger::getLogger("FW.FrameProcessorPlugin");
  }

  /**
   * Destructor
   */
  FrameProcessorPlugin::~FrameProcessorPlugin()
  {
    // TODO Auto-generated destructor stub
  }

  /**
   * Set the name of this plugin
   *
   * \param[in] name - The name.
   */
  void FrameProcessorPlugin::setName(const std::string& name)
  {
    // Record our name
    name_ = name;
  }

  /**
   * Get the name of this plugin
   *
   * \return The name.
   */
  std::string FrameProcessorPlugin::getName()
  {
    // Return our name
    return name_;
  }

  /** Configure the plugin.
   *
   * In this abstract class the configure method does perform any
   * actions, this should be overridden by subclasses.
   *
   * \param[in] config - IpcMessage containing configuration data.
   * \param[out] reply - Response IpcMessage.
   */
  void FrameProcessorPlugin::configure(OdinData::IpcMessage& config, OdinData::IpcMessage& reply)
  {
    // Default method simply does nothing
  }

  /**
   * Collate status information for the plugin.
   *
   * The status is added to the status IpcMessage object.
   * In this abstract class the status method does perform any
   * actions, this should be overridden by subclasses.
   *
   * \param[out] status - Reference to an IpcMessage value to store the status.
   */
  void FrameProcessorPlugin::status(OdinData::IpcMessage& status)
  {
    // Default method simply does nothing
  }

  /**
   * Registers another plugin for frame callbacks from this plugin.
   *
   * The callback interface (which will be another plugin) is stored in
   * our map, indexed by name.  If the callback already exists within our
   * map then this is a no-op.
   *
   * \param[in] name - Index of the callback (plugin index).
   * \param[in] cb - Pointer to an IFrameCallback interface (plugin).
   */
  void FrameProcessorPlugin::registerCallback(const std::string& name, boost::shared_ptr<IFrameCallback> cb, bool blocking)
  {
    if (blocking) {
      if (callbacks_.count(name) != 0) {
        LOG4CXX_WARN(logger_, "Non-blocking callback " << name << " already registered with " << name_ << ". Must be removed before adding blocking callback");
      }
      // Check if we own the callback already
      else if (blockingCallbacks_.count(name) == 0) {
        LOG4CXX_DEBUG(logger_, "Registering blocking callback " << name << " with " << name_);
        // Record the callback pointer
        blockingCallbacks_[name] = cb;
        // Confirm registration
        cb->confirmRegistration(name_);
      }
    }
    else {
      if (blockingCallbacks_.count(name) != 0) {
        LOG4CXX_WARN(logger_, "Blocking callback " << name << " already registered with " << name_ << ". Must be removed before adding non-blocking callback");
      }
      // Check if we own the callback already
      else if (callbacks_.count(name) == 0) {
        LOG4CXX_DEBUG(logger_, "Registering non-blocking callback " << name << " with " << name_);
        // Record the callback pointer
        callbacks_[name] = cb;
        // Confirm registration
        cb->confirmRegistration(name_);
      }
    }
  }

  /**
   * Remove a plugin from our callback map.
   *
   * \param[in] name - Index of the callback (plugin index) to remove.
   */
  void FrameProcessorPlugin::removeCallback(const std::string& name)
  {
    boost::shared_ptr<IFrameCallback> cb;
    if (callbacks_.count(name) > 0){
      // Get the pointer
      cb = callbacks_[name];
      // Remove the callback from the map
      callbacks_.erase(name);
      // Confirm removal
      cb->confirmRemoval(name_);
    }
    else if (blockingCallbacks_.count(name) > 0) {
      // Get the pointer
      cb = blockingCallbacks_[name];
      // Remove the callback from the map
      blockingCallbacks_.erase(name);
      // Confirm removal
      cb->confirmRemoval(name_);
    }
  }

  void FrameProcessorPlugin::connectMetaChannel()
  {
    metaChannel_.connect(META_RX_INTERFACE.c_str());
  }

  /** Publish meta data from this plugin.
   *
   * \param[in] item - Name of the meta data item to publish.
   * \param[in] value - The value of the meta data item to publish.
   * \param[in] header - Optional additional header data to publish.
   */
  void FrameProcessorPlugin::publishMeta(const std::string& item, int32_t value, const std::string &header)
  {
	  // Create a new MetaMessage object and send to the consumer
	  FrameProcessor::MetaMessage *meta = new FrameProcessor::MetaMessage(name_, item, "integer", header, sizeof(int32_t), &value);
	  // We need the pointer to the object cast to be able to pass it through ZMQ
	  uintptr_t addr = reinterpret_cast<uintptr_t>(&(*meta));
	  // Send the pointer value to the listener
	  metaChannel_.send(sizeof(uintptr_t), &addr);
  }

  /**
   * Publish meta data from this plugin.
   *
   * \param[in] item - Name of the meta data item to publish.
   * \param[in] value - The value of the meta data item to publish.
   * \param[in] header - Optional additional header data to publish.
   */
  void FrameProcessorPlugin::publishMeta(const std::string& item, double value, const std::string& header)
  {
	  // Create a new MetaMessage object and send to the consumer
	  FrameProcessor::MetaMessage *meta = new FrameProcessor::MetaMessage(name_, item, "double", header, sizeof(double), &value);
	  // We need the pointer to the object cast to be able to pass it through ZMQ
	  uintptr_t addr = reinterpret_cast<uintptr_t>(&(*meta));
	  // Send the pointer value to the listener
	  metaChannel_.send(sizeof(uintptr_t), &addr);
  }

  /**
   * Publish meta data from this plugin.
   *
   * \param[in] item - Name of the meta data item to publish.
   * \param[in] value - The value of the meta data item to publish.
   * \param[in] header - Optional additional header data to publish.
   */
  void FrameProcessorPlugin::publishMeta(const std::string& item, const std::string& value, const std::string& header)
  {
	  // Create a new MetaMessage object and send to the consumer
	  FrameProcessor::MetaMessage *meta = new FrameProcessor::MetaMessage(name_, item, "string", header, value.length(), value.c_str());
	  // We need the pointer to the object cast to be able to pass it through ZMQ
	  uintptr_t addr = reinterpret_cast<uintptr_t>(&(*meta));
	  // Send the pointer value to the listener
	  metaChannel_.send(sizeof(uintptr_t), &addr);
  }

  /**
   * Publish meta data from this plugin.
   *
   * \param[in] item - Name of the meta data item to publish.
   * \param[in] pValue - A pointer to the meta data value.  The memory will be copied.
   * \param[in] length - The size (in bytes) of the meta data value.
   * \param[in] header - Optional additional header data to publish.
   */
  void FrameProcessorPlugin::publishMeta(const std::string& item, const void *pValue, size_t length, const std::string& header)
  {
	  // Create a new MetaMessage object and send to the consumer
	  FrameProcessor::MetaMessage *meta = new FrameProcessor::MetaMessage(name_, item, "raw", header, length, pValue);
	  // We need the pointer to the object cast to be able to pass it through ZMQ
	  uintptr_t addr = reinterpret_cast<uintptr_t>(&(*meta));
	  // Send the pointer value to the listener
	  metaChannel_.send(sizeof(uintptr_t), &addr);
  }

  /**
   * We have been called back with a frame from a plugin that we registered
   * with.  This method calls the processFrame pure virtual method that
   * must be overridden by any children of this abstract class.
   *
   * \param[in] frame - Pointer to the frame.
   */
  void FrameProcessorPlugin::callback(boost::shared_ptr<Frame> frame)
  {
    // Calls process frame
    this->processFrame(frame);
  }

  /** Push the supplied frame to any registered callbacks.
   *
   * This method loops over the map of registered callbacks and places
   * the frame pointer on their worker queue (see IFrameCallback).
   *
   * \param[in] frame - Pointer to the frame.
   */
  void FrameProcessorPlugin::push(boost::shared_ptr<Frame> frame)
  {
    // Loop over blocking callbacks, calling each function and waiting for return
    std::map<std::string, boost::shared_ptr<IFrameCallback> >::iterator bcbIter;
    for (bcbIter = blockingCallbacks_.begin(); bcbIter != blockingCallbacks_.end(); ++bcbIter) {
      bcbIter->second->callback(frame);
    }
    // Loop over non-blocking callbacks, placing frame onto each queue
    std::map<std::string, boost::shared_ptr<IFrameCallback> >::iterator cbIter;
    for (cbIter = callbacks_.begin(); cbIter != callbacks_.end(); ++cbIter) {
      cbIter->second->getWorkQueue()->add(frame);
    }
  }

} /* namespace FrameProcessor */
<commit_msg>Added ZMQ_DONTWAIT to inproc meta data channel<commit_after>/*
 * FrameProcessorPlugin.cpp
 *
 *  Created on: 2 Jun 2016
 *      Author: gnx91527
 */

#include "FrameProcessorPlugin.h"

namespace FrameProcessor
{
  const std::string FrameProcessorPlugin::META_RX_INTERFACE        = "inproc://meta_rx";

  /**
   * Constructor, initialises name_.
   */
  FrameProcessorPlugin::FrameProcessorPlugin() :
      name_(""),
	  metaChannel_(ZMQ_PUSH)
  {
    logger_ = log4cxx::Logger::getLogger("FW.FrameProcessorPlugin");
  }

  /**
   * Destructor
   */
  FrameProcessorPlugin::~FrameProcessorPlugin()
  {
    // TODO Auto-generated destructor stub
  }

  /**
   * Set the name of this plugin
   *
   * \param[in] name - The name.
   */
  void FrameProcessorPlugin::setName(const std::string& name)
  {
    // Record our name
    name_ = name;
  }

  /**
   * Get the name of this plugin
   *
   * \return The name.
   */
  std::string FrameProcessorPlugin::getName()
  {
    // Return our name
    return name_;
  }

  /** Configure the plugin.
   *
   * In this abstract class the configure method does perform any
   * actions, this should be overridden by subclasses.
   *
   * \param[in] config - IpcMessage containing configuration data.
   * \param[out] reply - Response IpcMessage.
   */
  void FrameProcessorPlugin::configure(OdinData::IpcMessage& config, OdinData::IpcMessage& reply)
  {
    // Default method simply does nothing
  }

  /**
   * Collate status information for the plugin.
   *
   * The status is added to the status IpcMessage object.
   * In this abstract class the status method does perform any
   * actions, this should be overridden by subclasses.
   *
   * \param[out] status - Reference to an IpcMessage value to store the status.
   */
  void FrameProcessorPlugin::status(OdinData::IpcMessage& status)
  {
    // Default method simply does nothing
  }

  /**
   * Registers another plugin for frame callbacks from this plugin.
   *
   * The callback interface (which will be another plugin) is stored in
   * our map, indexed by name.  If the callback already exists within our
   * map then this is a no-op.
   *
   * \param[in] name - Index of the callback (plugin index).
   * \param[in] cb - Pointer to an IFrameCallback interface (plugin).
   */
  void FrameProcessorPlugin::registerCallback(const std::string& name, boost::shared_ptr<IFrameCallback> cb, bool blocking)
  {
    if (blocking) {
      if (callbacks_.count(name) != 0) {
        LOG4CXX_WARN(logger_, "Non-blocking callback " << name << " already registered with " << name_ << ". Must be removed before adding blocking callback");
      }
      // Check if we own the callback already
      else if (blockingCallbacks_.count(name) == 0) {
        LOG4CXX_DEBUG(logger_, "Registering blocking callback " << name << " with " << name_);
        // Record the callback pointer
        blockingCallbacks_[name] = cb;
        // Confirm registration
        cb->confirmRegistration(name_);
      }
    }
    else {
      if (blockingCallbacks_.count(name) != 0) {
        LOG4CXX_WARN(logger_, "Blocking callback " << name << " already registered with " << name_ << ". Must be removed before adding non-blocking callback");
      }
      // Check if we own the callback already
      else if (callbacks_.count(name) == 0) {
        LOG4CXX_DEBUG(logger_, "Registering non-blocking callback " << name << " with " << name_);
        // Record the callback pointer
        callbacks_[name] = cb;
        // Confirm registration
        cb->confirmRegistration(name_);
      }
    }
  }

  /**
   * Remove a plugin from our callback map.
   *
   * \param[in] name - Index of the callback (plugin index) to remove.
   */
  void FrameProcessorPlugin::removeCallback(const std::string& name)
  {
    boost::shared_ptr<IFrameCallback> cb;
    if (callbacks_.count(name) > 0){
      // Get the pointer
      cb = callbacks_[name];
      // Remove the callback from the map
      callbacks_.erase(name);
      // Confirm removal
      cb->confirmRemoval(name_);
    }
    else if (blockingCallbacks_.count(name) > 0) {
      // Get the pointer
      cb = blockingCallbacks_[name];
      // Remove the callback from the map
      blockingCallbacks_.erase(name);
      // Confirm removal
      cb->confirmRemoval(name_);
    }
  }

  void FrameProcessorPlugin::connectMetaChannel()
  {
    metaChannel_.connect(META_RX_INTERFACE.c_str());
  }

  /** Publish meta data from this plugin.
   *
   * \param[in] item - Name of the meta data item to publish.
   * \param[in] value - The value of the meta data item to publish.
   * \param[in] header - Optional additional header data to publish.
   */
  void FrameProcessorPlugin::publishMeta(const std::string& item, int32_t value, const std::string &header)
  {
	  // Create a new MetaMessage object and send to the consumer
	  FrameProcessor::MetaMessage *meta = new FrameProcessor::MetaMessage(name_, item, "integer", header, sizeof(int32_t), &value);
	  // We need the pointer to the object cast to be able to pass it through ZMQ
	  uintptr_t addr = reinterpret_cast<uintptr_t>(&(*meta));
	  // Send the pointer value to the listener
	  metaChannel_.send(sizeof(uintptr_t), &addr, ZMQ_DONTWAIT);
  }

  /**
   * Publish meta data from this plugin.
   *
   * \param[in] item - Name of the meta data item to publish.
   * \param[in] value - The value of the meta data item to publish.
   * \param[in] header - Optional additional header data to publish.
   */
  void FrameProcessorPlugin::publishMeta(const std::string& item, double value, const std::string& header)
  {
	  // Create a new MetaMessage object and send to the consumer
	  FrameProcessor::MetaMessage *meta = new FrameProcessor::MetaMessage(name_, item, "double", header, sizeof(double), &value);
	  // We need the pointer to the object cast to be able to pass it through ZMQ
	  uintptr_t addr = reinterpret_cast<uintptr_t>(&(*meta));
	  // Send the pointer value to the listener
	  metaChannel_.send(sizeof(uintptr_t), &addr, ZMQ_DONTWAIT);
  }

  /**
   * Publish meta data from this plugin.
   *
   * \param[in] item - Name of the meta data item to publish.
   * \param[in] value - The value of the meta data item to publish.
   * \param[in] header - Optional additional header data to publish.
   */
  void FrameProcessorPlugin::publishMeta(const std::string& item, const std::string& value, const std::string& header)
  {
	  // Create a new MetaMessage object and send to the consumer
	  FrameProcessor::MetaMessage *meta = new FrameProcessor::MetaMessage(name_, item, "string", header, value.length(), value.c_str());
	  // We need the pointer to the object cast to be able to pass it through ZMQ
	  uintptr_t addr = reinterpret_cast<uintptr_t>(&(*meta));
	  // Send the pointer value to the listener
	  metaChannel_.send(sizeof(uintptr_t), &addr, ZMQ_DONTWAIT);
  }

  /**
   * Publish meta data from this plugin.
   *
   * \param[in] item - Name of the meta data item to publish.
   * \param[in] pValue - A pointer to the meta data value.  The memory will be copied.
   * \param[in] length - The size (in bytes) of the meta data value.
   * \param[in] header - Optional additional header data to publish.
   */
  void FrameProcessorPlugin::publishMeta(const std::string& item, const void *pValue, size_t length, const std::string& header)
  {
	  // Create a new MetaMessage object and send to the consumer
	  FrameProcessor::MetaMessage *meta = new FrameProcessor::MetaMessage(name_, item, "raw", header, length, pValue);
	  // We need the pointer to the object cast to be able to pass it through ZMQ
	  uintptr_t addr = reinterpret_cast<uintptr_t>(&(*meta));
	  // Send the pointer value to the listener
	  metaChannel_.send(sizeof(uintptr_t), &addr, ZMQ_DONTWAIT);
  }

  /**
   * We have been called back with a frame from a plugin that we registered
   * with.  This method calls the processFrame pure virtual method that
   * must be overridden by any children of this abstract class.
   *
   * \param[in] frame - Pointer to the frame.
   */
  void FrameProcessorPlugin::callback(boost::shared_ptr<Frame> frame)
  {
    // Calls process frame
    this->processFrame(frame);
  }

  /** Push the supplied frame to any registered callbacks.
   *
   * This method loops over the map of registered callbacks and places
   * the frame pointer on their worker queue (see IFrameCallback).
   *
   * \param[in] frame - Pointer to the frame.
   */
  void FrameProcessorPlugin::push(boost::shared_ptr<Frame> frame)
  {
    // Loop over blocking callbacks, calling each function and waiting for return
    std::map<std::string, boost::shared_ptr<IFrameCallback> >::iterator bcbIter;
    for (bcbIter = blockingCallbacks_.begin(); bcbIter != blockingCallbacks_.end(); ++bcbIter) {
      bcbIter->second->callback(frame);
    }
    // Loop over non-blocking callbacks, placing frame onto each queue
    std::map<std::string, boost::shared_ptr<IFrameCallback> >::iterator cbIter;
    for (cbIter = callbacks_.begin(); cbIter != callbacks_.end(); ++cbIter) {
      cbIter->second->getWorkQueue()->add(frame);
    }
  }

} /* namespace FrameProcessor */
<|endoftext|>


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

#ifndef __FRAMEWORK_DISPATCH_DISPATCHPROVIDER_HXX_
#define __FRAMEWORK_DISPATCH_DISPATCHPROVIDER_HXX_

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_SERVICES_FRAME_HXX_
#include <services/frame.hxx>
#endif

#include <classes/protocolhandlercache.hxx>

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

#ifndef __FRAMEWORK_THREADHELP_TRANSACTIONBASE_HXX_
#include <threadhelp/transactionbase.hxx>
#endif

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

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

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

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

#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

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

#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif

#ifndef _COM_SUN_STAR_UTIL_URL_HPP_
#include <com/sun/star/util/URL.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_DISPATCHDESCRIPTOR_HPP_
#include <com/sun/star/frame/DispatchDescriptor.hpp>
#endif

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

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

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

#ifndef _CPPUHELPER_WEAKREF_HXX_
#include <cppuhelper/weakref.hxx>
#endif

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

namespace framework{

//_________________________________________________________________________________________________________________

/**
    @descr          We know some special dispatch objects with diffrent functionality.
                    The can be created internaly by the following DispatchProvider.
                    Here we define some identifier to force creation of the right one.

    @modified       20.08.2003 08:34, as96863
*/
enum EDispatchHelper
{
    E_DEFAULTDISPATCHER     ,
    E_MENUDISPATCHER        ,
    E_HELPAGENTDISPATCHER   ,
    E_CREATEDISPATCHER      ,
    E_BLANKDISPATCHER       ,
    E_SELFDISPATCHER        ,
    E_CLOSEDISPATCHER
};

//_________________________________________________________________________________________________________________

/**
    @short          implement a helper for XDispatchProvider interface
    @descr          The result of a queryDispatch() call depends from the owner, which use an instance of this class.
                    (frame, desktop) All of them must provides different functionality.
                    E.g:    - task can be created by the desktop only
                            - a task can have a beamer as direct child
                            - a normal frame never can create a new one by himself

    @attention      Use this class as member only! Never use it as baseclass.
                    XInterface will be ambigous and we hold a weakreference to ouer OWNER - not to ouer SUPERCLASS!

    @base           ThreadHelpBase
                        supports threadsafe mechanism
    @base           OWeakObject
                        provides ref count and weak mechanism

    @devstatus      ready to use
    @threadsafe     yes
    @modified       17.05.2002 07:56, as96863
*/
class DispatchProvider  :   // interfaces
                            public  css::lang::XTypeProvider            ,
                            public  css::frame::XDispatchProvider       ,
                            // baseclasses
                            // Order is neccessary for right initialization!
                            private ThreadHelpBase                      ,
                            private TransactionBase                     ,
                            public  ::cppu::OWeakObject
{
    /* member */
    private:
        /// reference to global service manager to create new services
        css::uno::Reference< css::lang::XMultiServiceFactory > m_xFactory;
        /// weakreference to owner frame (Don't use a hard reference. Owner can't delete us then!)
        css::uno::WeakReference< css::frame::XFrame > m_xFrame;
        /// different dispatcher to handle special dispatch calls, protocols or URLs (they will be created on demand.)
        css::uno::Reference< css::frame::XDispatch > m_xMenuDispatcher     ;
        css::uno::Reference< css::frame::XDispatch > m_xHelpAgentDispatcher;
/*      css::uno::Reference< css::frame::XDispatch > m_xBlankDispatcher    ;
        css::uno::Reference< css::frame::XDispatch > m_xSelfDispatcher     ;
        css::uno::Reference< css::frame::XDispatch > m_xDefaultDispatcher  ;*/
        /// cache of some other dispatch provider which are registered inside configuration to handle special URL protocols
        HandlerCache m_aProtocolHandlerCache;

    /* interface */
    public:
        DECLARE_XINTERFACE
        DECLARE_XTYPEPROVIDER

        DispatchProvider( const css::uno::Reference< css::lang::XMultiServiceFactory >& xFactory ,
                          const css::uno::Reference< css::frame::XFrame >&              xFrame   );

        virtual css::uno::Reference< css::frame::XDispatch > SAL_CALL                       queryDispatch  ( const css::util::URL&                                       aURL             ,
                                                                                const ::rtl::OUString&                                      sTargetFrameName ,
                                                                                sal_Int32                                             nSearchFlags     ) throw( css::uno::RuntimeException );
        virtual css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > SAL_CALL queryDispatches( const css::uno::Sequence< css::frame::DispatchDescriptor >& lDescriptions    ) throw( css::uno::RuntimeException );

    /* helper */
    protected:
        // Let him protected! So nobody can use us as base ...
        virtual ~DispatchProvider();

    private:
        css::uno::Reference< css::frame::XDispatch > implts_getOrCreateDispatchHelper   (       EDispatchHelper                            eHelper                       ,
                                                                                const css::uno::Reference< css::frame::XFrame >& xOwner                        ,
                                                                                const ::rtl::OUString&                           sTarget = ::rtl::OUString()   ,
                                                                                sal_Int32                                  nSearchFlags = 0              );
        sal_Bool                                     implts_isLoadableContent           ( const css::util::URL&                            aURL                          );
        css::uno::Reference< css::frame::XDispatch > implts_queryDesktopDispatch        ( const css::uno::Reference< css::frame::XFrame >  xDesktop                      ,
                                                                                const css::util::URL&                            aURL                          ,
                                                                                const ::rtl::OUString&                           sTargetFrameName              ,
                                                                                sal_Int32                                  nSearchFlags                  );
        css::uno::Reference< css::frame::XDispatch > implts_queryFrameDispatch          ( const css::uno::Reference< css::frame::XFrame >  xFrame                        ,
                                                                                const css::util::URL&                            aURL                          ,
                                                                                const ::rtl::OUString&                           sTargetFrameName              ,
                                                                                sal_Int32                                  nSearchFlags                  );
        css::uno::Reference< css::frame::XDispatch > implts_searchProtocolHandler       ( const css::util::URL&                            aURL                          );

}; // class DispatchProvider

} // namespace framework

#endif // #ifndef __FRAMEWORK_DISPATCH_DISPATCHPROVIDER_HXX_
<commit_msg>INTEGRATION: CWS warnings01 (1.12.32); FILE MERGED 2005/10/28 14:48:07 cd 1.12.32.1: #i55991# Warning free code changes for gcc<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dispatchprovider.hxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 10:50:27 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef __FRAMEWORK_DISPATCH_DISPATCHPROVIDER_HXX_
#define __FRAMEWORK_DISPATCH_DISPATCHPROVIDER_HXX_

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_SERVICES_FRAME_HXX_
#include <services/frame.hxx>
#endif

#include <classes/protocolhandlercache.hxx>

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

#ifndef __FRAMEWORK_THREADHELP_TRANSACTIONBASE_HXX_
#include <threadhelp/transactionbase.hxx>
#endif

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

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

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

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

#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

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

#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif

#ifndef _COM_SUN_STAR_UTIL_URL_HPP_
#include <com/sun/star/util/URL.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_DISPATCHDESCRIPTOR_HPP_
#include <com/sun/star/frame/DispatchDescriptor.hpp>
#endif

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

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

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

#ifndef _CPPUHELPER_WEAKREF_HXX_
#include <cppuhelper/weakref.hxx>
#endif

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

namespace framework{

//_________________________________________________________________________________________________________________

/**
    @descr          We know some special dispatch objects with diffrent functionality.
                    The can be created internaly by the following DispatchProvider.
                    Here we define some identifier to force creation of the right one.

    @modified       20.08.2003 08:34, as96863
*/
enum EDispatchHelper
{
    E_DEFAULTDISPATCHER     ,
    E_MENUDISPATCHER        ,
    E_HELPAGENTDISPATCHER   ,
    E_CREATEDISPATCHER      ,
    E_BLANKDISPATCHER       ,
    E_SELFDISPATCHER        ,
    E_CLOSEDISPATCHER
};

//_________________________________________________________________________________________________________________

/**
    @short          implement a helper for XDispatchProvider interface
    @descr          The result of a queryDispatch() call depends from the owner, which use an instance of this class.
                    (frame, desktop) All of them must provides different functionality.
                    E.g:    - task can be created by the desktop only
                            - a task can have a beamer as direct child
                            - a normal frame never can create a new one by himself

    @attention      Use this class as member only! Never use it as baseclass.
                    XInterface will be ambigous and we hold a weakreference to ouer OWNER - not to ouer SUPERCLASS!

    @base           ThreadHelpBase
                        supports threadsafe mechanism
    @base           OWeakObject
                        provides ref count and weak mechanism

    @devstatus      ready to use
    @threadsafe     yes
    @modified       17.05.2002 07:56, as96863
*/
class DispatchProvider  :   // interfaces
                            public  css::lang::XTypeProvider            ,
                            public  css::frame::XDispatchProvider       ,
                            // baseclasses
                            // Order is neccessary for right initialization!
                            private ThreadHelpBase                      ,
                            private TransactionBase                     ,
                            public  ::cppu::OWeakObject
{
    /* member */
    private:
        /// reference to global service manager to create new services
        css::uno::Reference< css::lang::XMultiServiceFactory > m_xFactory;
        /// weakreference to owner frame (Don't use a hard reference. Owner can't delete us then!)
        css::uno::WeakReference< css::frame::XFrame > m_xFrame;
        /// different dispatcher to handle special dispatch calls, protocols or URLs (they will be created on demand.)
        css::uno::Reference< css::frame::XDispatch > m_xMenuDispatcher     ;
        css::uno::Reference< css::frame::XDispatch > m_xHelpAgentDispatcher;
/*      css::uno::Reference< css::frame::XDispatch > m_xBlankDispatcher    ;
        css::uno::Reference< css::frame::XDispatch > m_xSelfDispatcher     ;
        css::uno::Reference< css::frame::XDispatch > m_xDefaultDispatcher  ;*/
        /// cache of some other dispatch provider which are registered inside configuration to handle special URL protocols
        HandlerCache m_aProtocolHandlerCache;

    /* interface */
    public:
        FWK_DECLARE_XINTERFACE
        FWK_DECLARE_XTYPEPROVIDER

        DispatchProvider( const css::uno::Reference< css::lang::XMultiServiceFactory >& xFactory ,
                          const css::uno::Reference< css::frame::XFrame >&              xFrame   );

        virtual css::uno::Reference< css::frame::XDispatch > SAL_CALL                       queryDispatch  ( const css::util::URL&                                       aURL             ,
                                                                                const ::rtl::OUString&                                      sTargetFrameName ,
                                                                                sal_Int32                                             nSearchFlags     ) throw( css::uno::RuntimeException );
        virtual css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > SAL_CALL queryDispatches( const css::uno::Sequence< css::frame::DispatchDescriptor >& lDescriptions    ) throw( css::uno::RuntimeException );

    /* helper */
    protected:
        // Let him protected! So nobody can use us as base ...
        virtual ~DispatchProvider();

    private:
        css::uno::Reference< css::frame::XDispatch > implts_getOrCreateDispatchHelper   (       EDispatchHelper                            eHelper                       ,
                                                                                const css::uno::Reference< css::frame::XFrame >& xOwner                        ,
                                                                                const ::rtl::OUString&                           sTarget = ::rtl::OUString()   ,
                                                                                sal_Int32                                  nSearchFlags = 0              );
        sal_Bool                                     implts_isLoadableContent           ( const css::util::URL&                            aURL                          );
        css::uno::Reference< css::frame::XDispatch > implts_queryDesktopDispatch        ( const css::uno::Reference< css::frame::XFrame >  xDesktop                      ,
                                                                                const css::util::URL&                            aURL                          ,
                                                                                const ::rtl::OUString&                           sTargetFrameName              ,
                                                                                sal_Int32                                  nSearchFlags                  );
        css::uno::Reference< css::frame::XDispatch > implts_queryFrameDispatch          ( const css::uno::Reference< css::frame::XFrame >  xFrame                        ,
                                                                                const css::util::URL&                            aURL                          ,
                                                                                const ::rtl::OUString&                           sTargetFrameName              ,
                                                                                sal_Int32                                  nSearchFlags                  );
        css::uno::Reference< css::frame::XDispatch > implts_searchProtocolHandler       ( const css::util::URL&                            aURL                          );

}; // class DispatchProvider

} // namespace framework

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


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

#ifndef __FRAMEWORK_XML_EVENTSDOCUMENTHANDLER_HXX_
#define __FRAMEWORK_XML_EVENTSDOCUMENTHANDLER_HXX_

#ifndef __FRAMEWORK_XML_TOOLBOXCONFIGURATION_HXX_
#include <xml/eventsconfiguration.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef __COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP_
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

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

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

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

#include <hash_map>

#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

namespace framework{

//*****************************************************************************************************************
// Hash code function for using in all hash maps of follow implementation.

class OReadEventsDocumentHandler :  public ::com::sun::star::xml::sax::XDocumentHandler,
                                    private ThreadHelpBase, // Struct for right initalization of lock member! Must be first of baseclasses.
                                    public ::cppu::OWeakObject
{
    public:
        enum Events_XML_Entry
        {
            EV_ELEMENT_EVENTS,
            EV_ELEMENT_EVENT,
            EV_ATTRIBUTE_TYPE,
            EV_ATTRIBUTE_NAME,
            XL_ATTRIBUTE_HREF,
            XL_ATTRIBUTE_TYPE,
            EV_ATTRIBUTE_MACRONAME,
            EV_ATTRIBUTE_LIBRARY,
            EV_XML_ENTRY_COUNT
        };

        enum Event_XML_Namespace
        {
            EV_NS_EVENT,
            EV_NS_XLINK,
            EV_XML_NAMESPACES_COUNT
        };

        OReadEventsDocumentHandler( EventsConfig& aItems );
        virtual ~OReadEventsDocumentHandler();

        // XInterface
        virtual void SAL_CALL acquire() throw()
            { OWeakObject::acquire(); }
        virtual void SAL_CALL release() throw()
            { OWeakObject::release(); }
        virtual ::com::sun::star::uno::Any SAL_CALL queryInterface(
            const ::com::sun::star::uno::Type & rType ) throw( ::com::sun::star::uno::RuntimeException );

        // XDocumentHandler
        virtual void SAL_CALL startDocument(void)
        throw ( ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

        virtual void SAL_CALL endDocument(void)
        throw(  ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

        virtual void SAL_CALL startElement(
            const rtl::OUString& aName,
            const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > &xAttribs)
        throw(  ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

        virtual void SAL_CALL endElement(const rtl::OUString& aName)
        throw(  ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

        virtual void SAL_CALL characters(const rtl::OUString& aChars)
        throw(  ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

        virtual void SAL_CALL ignorableWhitespace(const rtl::OUString& aWhitespaces)
        throw(  ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

        virtual void SAL_CALL processingInstruction(const rtl::OUString& aTarget,
                                                    const rtl::OUString& aData)
        throw(  ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

        virtual void SAL_CALL setDocumentLocator(
            const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator > &xLocator)
        throw(  ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

    private:
        ::rtl::OUString getErrorLineString();

        class EventsHashMap : public ::std::hash_map<   ::rtl::OUString                 ,
                                                        Events_XML_Entry                ,
                                                        OUStringHashCode                ,
                                                        ::std::equal_to< ::rtl::OUString >  >
        {
            public:
                inline void free()
                {
                    EventsHashMap().swap( *this );
                }
        };

        sal_Bool                                                                    m_bEventsStartFound;
        sal_Bool                                                                    m_bEventsEndFound;
        sal_Bool                                                                    m_bEventStartFound;
        EventsHashMap                                                               m_aEventsMap;
        EventsConfig&                                                               m_aEventItems;
        ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator >    m_xLocator;
};

class OWriteEventsDocumentHandler : private ThreadHelpBase // Struct for right initalization of lock member! Must be first of baseclasses.
{
    public:
        OWriteEventsDocumentHandler(
            const EventsConfig& aItems,
            ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler > );
        virtual ~OWriteEventsDocumentHandler();

        void WriteEventsDocument() throw
            ( ::com::sun::star::xml::sax::SAXException,
              ::com::sun::star::uno::RuntimeException );

    protected:
        virtual void WriteEvent(
                const ::rtl::OUString& aEventName,
                const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aPropertyValue ) throw
            ( ::com::sun::star::xml::sax::SAXException,
              ::com::sun::star::uno::RuntimeException );

        const EventsConfig&                                                                 m_aItems;
        ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler >    m_xWriteDocumentHandler;
        ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >      m_xEmptyList;
        ::rtl::OUString                                                                     m_aXMLEventNS;
        ::rtl::OUString                                                                     m_aXMLXlinkNS;
        ::rtl::OUString                                                                     m_aAttributeType;
        ::rtl::OUString                                                                     m_aAttributeURL;
        ::rtl::OUString                                                                     m_aAttributeLanguage;
        ::rtl::OUString                                                                     m_aAttributeLinkType;
        ::rtl::OUString                                                                     m_aAttributeMacroName;
        ::rtl::OUString                                                                     m_aAttributeLibrary;
        ::rtl::OUString                                                                     m_aAttributeName;
};

} // namespace framework

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.4.458); FILE MERGED 2008/04/01 15:18:31 thb 1.4.458.3: #i85898# Stripping all external header guards 2008/04/01 10:58:00 thb 1.4.458.2: #i85898# Stripping all external header guards 2008/03/28 15:34:59 rt 1.4.458.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: eventsdocumenthandler.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef __FRAMEWORK_XML_EVENTSDOCUMENTHANDLER_HXX_
#define __FRAMEWORK_XML_EVENTSDOCUMENTHANDLER_HXX_

#ifndef __FRAMEWORK_XML_TOOLBOXCONFIGURATION_HXX_
#include <xml/eventsconfiguration.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef __COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP_
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________
#include <threadhelp/threadhelpbase.hxx>
#include <rtl/ustring.hxx>
#include <cppuhelper/weak.hxx>

#include <hash_map>
#include <stdtypes.h>

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

namespace framework{

//*****************************************************************************************************************
// Hash code function for using in all hash maps of follow implementation.

class OReadEventsDocumentHandler :  public ::com::sun::star::xml::sax::XDocumentHandler,
                                    private ThreadHelpBase, // Struct for right initalization of lock member! Must be first of baseclasses.
                                    public ::cppu::OWeakObject
{
    public:
        enum Events_XML_Entry
        {
            EV_ELEMENT_EVENTS,
            EV_ELEMENT_EVENT,
            EV_ATTRIBUTE_TYPE,
            EV_ATTRIBUTE_NAME,
            XL_ATTRIBUTE_HREF,
            XL_ATTRIBUTE_TYPE,
            EV_ATTRIBUTE_MACRONAME,
            EV_ATTRIBUTE_LIBRARY,
            EV_XML_ENTRY_COUNT
        };

        enum Event_XML_Namespace
        {
            EV_NS_EVENT,
            EV_NS_XLINK,
            EV_XML_NAMESPACES_COUNT
        };

        OReadEventsDocumentHandler( EventsConfig& aItems );
        virtual ~OReadEventsDocumentHandler();

        // XInterface
        virtual void SAL_CALL acquire() throw()
            { OWeakObject::acquire(); }
        virtual void SAL_CALL release() throw()
            { OWeakObject::release(); }
        virtual ::com::sun::star::uno::Any SAL_CALL queryInterface(
            const ::com::sun::star::uno::Type & rType ) throw( ::com::sun::star::uno::RuntimeException );

        // XDocumentHandler
        virtual void SAL_CALL startDocument(void)
        throw ( ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

        virtual void SAL_CALL endDocument(void)
        throw(  ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

        virtual void SAL_CALL startElement(
            const rtl::OUString& aName,
            const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > &xAttribs)
        throw(  ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

        virtual void SAL_CALL endElement(const rtl::OUString& aName)
        throw(  ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

        virtual void SAL_CALL characters(const rtl::OUString& aChars)
        throw(  ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

        virtual void SAL_CALL ignorableWhitespace(const rtl::OUString& aWhitespaces)
        throw(  ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

        virtual void SAL_CALL processingInstruction(const rtl::OUString& aTarget,
                                                    const rtl::OUString& aData)
        throw(  ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

        virtual void SAL_CALL setDocumentLocator(
            const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator > &xLocator)
        throw(  ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

    private:
        ::rtl::OUString getErrorLineString();

        class EventsHashMap : public ::std::hash_map<   ::rtl::OUString                 ,
                                                        Events_XML_Entry                ,
                                                        OUStringHashCode                ,
                                                        ::std::equal_to< ::rtl::OUString >  >
        {
            public:
                inline void free()
                {
                    EventsHashMap().swap( *this );
                }
        };

        sal_Bool                                                                    m_bEventsStartFound;
        sal_Bool                                                                    m_bEventsEndFound;
        sal_Bool                                                                    m_bEventStartFound;
        EventsHashMap                                                               m_aEventsMap;
        EventsConfig&                                                               m_aEventItems;
        ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator >    m_xLocator;
};

class OWriteEventsDocumentHandler : private ThreadHelpBase // Struct for right initalization of lock member! Must be first of baseclasses.
{
    public:
        OWriteEventsDocumentHandler(
            const EventsConfig& aItems,
            ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler > );
        virtual ~OWriteEventsDocumentHandler();

        void WriteEventsDocument() throw
            ( ::com::sun::star::xml::sax::SAXException,
              ::com::sun::star::uno::RuntimeException );

    protected:
        virtual void WriteEvent(
                const ::rtl::OUString& aEventName,
                const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aPropertyValue ) throw
            ( ::com::sun::star::xml::sax::SAXException,
              ::com::sun::star::uno::RuntimeException );

        const EventsConfig&                                                                 m_aItems;
        ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler >    m_xWriteDocumentHandler;
        ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >      m_xEmptyList;
        ::rtl::OUString                                                                     m_aXMLEventNS;
        ::rtl::OUString                                                                     m_aXMLXlinkNS;
        ::rtl::OUString                                                                     m_aAttributeType;
        ::rtl::OUString                                                                     m_aAttributeURL;
        ::rtl::OUString                                                                     m_aAttributeLanguage;
        ::rtl::OUString                                                                     m_aAttributeLinkType;
        ::rtl::OUString                                                                     m_aAttributeMacroName;
        ::rtl::OUString                                                                     m_aAttributeLibrary;
        ::rtl::OUString                                                                     m_aAttributeName;
};

} // namespace framework

#endif
<|endoftext|>