<commit_before>//===-- sdbcoreC.cpp ----------------------------------------------------------------*- C++ -*-===//
//
//                                    S E R I A L B O X
//
// This file is distributed under terms of BSD license.
// See LICENSE.txt for more information
//
//===------------------------------------------------------------------------------------------===//
//
/// \file
/// This file contains utility functions for the sdb core library
///
//===------------------------------------------------------------------------------------------===//

#include <Python.h>

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

#include <vector>
#include <iostream>
#include <cmath>

namespace {

template <class T>
class NumpyArray {
public:
  NumpyArray(PyArrayObject* array)
      : data_((T*)PyArray_DATA(array)), size_(PyArray_SIZE(array)),
        shape_(PyArray_DIMS(array), PyArray_DIMS(array) + PyArray_NDIM(array)) {}

  /// \brief Access data pointer
  const T* data() const noexcept { return data_; }
  T* data() noexcept { return data_; }

  /// \brief Shape of the numpy array
  const std::vector<npy_intp>& shape() const noexcept { return shape_; }

  /// \brief Size of the array
  npy_intp size() const noexcept { return size_; }

  /// \brief Convert to string
  friend std::ostream& operator<<(std::ostream& stream, const NumpyArray& array) {
    stream << "shape = [ ";
    for(const auto& s : array.shape())
      stream << s << " ";
    stream << "], size = " << array.size() << ", data = " << array.data();
    return stream;
  }

private:
  T* data_;
  npy_intp size_;
  std::vector<npy_intp> shape_;
};

template <class T>
struct ErrorList {
  std::vector<int> index;
  T input_value;
  T reference_value;
};

/// \brief Compute positions of errors of input and reference fields
///
/// The error_position field is set to True if
///
///   absolute(input - reference) <= (atol + rtol * absolute(reference))
///
/// evaluates to False.
template <class T>
inline int compute_error_positions(const NumpyArray<T>& input, const NumpyArray<T>& reference,
                                   NumpyArray<bool>& error_positions, const double& atol,
                                   const double& rtol) noexcept {
  const int size = input.size();
  const T* input_ptr = input.data();
  const T* reference_ptr = reference.data();
  bool* error_positions_ptr = error_positions.data();

  int num_errors = 0;

  for(int i = 0; i < size; ++i) {

    const T a = input_ptr[i];
    const T b = reference_ptr[i];

    const bool res = !(std::abs(a - b) <= (atol + rtol * std::abs(b)));

    num_errors += res;
    error_positions_ptr[i] = res;
  }

  return num_errors;
}

inline void increment_index(std::vector<int>& index, const std::vector<npy_intp>& shape) noexcept {

  const int size = index.size();
  for(int i = 0; i < size; ++i)
    if(++index[i] < shape[i])
      break;
    else
      index[i] = 0;
}

/// \brief Compute list of errors with elements (index, input_value, reference_value)
template <class T>
inline void compute_error_list(const NumpyArray<T>& input, const NumpyArray<T>& reference,
                               const NumpyArray<bool>& error_positions,
                               std::vector<ErrorList<T>>& error_list) noexcept {
  const int size = input.size();
  const T* input_ptr = input.data();
  const T* reference_ptr = reference.data();
  const bool* error_positions_ptr = error_positions.data();

  const std::vector<npy_intp>& shape = input.shape();
  std::vector<int> index(input.shape().size(), 0);
  int error_list_idx = 0;

  for(int i = 0; i < size; ++i, increment_index(index, shape)) {
    if(error_positions_ptr[i]) {
      error_list[error_list_idx].index = index;
      error_list[error_list_idx].input_value = input_ptr[i];
      error_list[error_list_idx].reference_value = reference_ptr[i];
      error_list_idx++;
    }
  }
}

} // anonymous namespace

/// \brief Compute the list of errors and positions
static PyObject* sdbcoreC_make_error_list_c(PyObject* self, PyObject* args) {
  PyObject* input_field;
  PyArrayObject* input_array;

  PyObject* reference_field;
  PyArrayObject* reference_array;

  PyArrayObject* error_positions_array = NULL;
  PyObject* error_list_object = NULL;

  double atol;
  double rtol;

  //
  // Parse arguments
  //
  if(!PyArg_ParseTuple(args, "OOdd", &input_field, &reference_field, &atol, &rtol))
    return NULL;

  try {

    //
    // Extract numpy arrays
    //
    if(!(input_array =
             (PyArrayObject*)PyArray_FROM_OTF(input_field, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY)))
      throw std::runtime_error("internal error: failed to extract input array");

    if(!(reference_array =
             (PyArrayObject*)PyArray_FROM_OTF(reference_field, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY)))
      throw std::runtime_error("internal error: failed to extract reference array");

    NumpyArray<double> input(input_array);
    NumpyArray<double> reference(reference_array);

    if(input.shape() != reference.shape())
      throw std::runtime_error("internal error: dimension mismatch");

    //
    // Allocate error positions array (boolean array)
    //
    error_positions_array = (PyArrayObject*)PyArray_SimpleNew(PyArray_NDIM(input_array),
                                                              PyArray_DIMS(input_array), NPY_BOOL);
    NumpyArray<bool> error_positions(error_positions_array);

    //
    // Compute error positions
    //
    int num_errors = compute_error_positions(input, reference, error_positions, atol, rtol);

    //
    // Allocate list of errors
    //
    std::vector<ErrorList<double>> error_list(num_errors);
    error_list_object = PyList_New(error_list.size());

    //
    // Compute list of errors
    //
    compute_error_list(input, reference, error_positions, error_list);

    //
    // Prepare return
    //
    for(int i = 0; i < error_list.size(); ++i) {

      PyObject* list_element = PyList_New(3);

      PyObject* index_list = PyList_New(error_list[i].index.size());

      const int index_size = error_list[i].index.size();
      for(int ii = 0; ii < error_list[i].index.size(); ++ii)
        PyList_SetItem(index_list, ii, PyLong_FromLong(error_list[i].index[index_size - 1 - ii]));

      PyList_SetItem(list_element, 0, index_list);
      PyList_SetItem(list_element, 1, PyFloat_FromDouble(error_list[i].input_value));
      PyList_SetItem(list_element, 2, PyFloat_FromDouble(error_list[i].reference_value));

      PyList_SetItem(error_list_object, i, list_element);
    }

  } catch(std::runtime_error& e) {
    PyErr_SetString(PyExc_RuntimeError, e.what());

    Py_XDECREF(input_array);
    Py_XDECREF(reference_array);

    if(error_list_object)
      Py_XDECREF(error_list_object);

    if(error_positions_array)
      Py_XDECREF(error_positions_array);

    return NULL;
  }

  return Py_BuildValue("OO", error_list_object, error_positions_array);
}

//===------------------------------------------------------------------------------------------===//
//     Module definitions
//===------------------------------------------------------------------------------------------===//

// Method specification
static PyMethodDef module_methods[] = {
    {"make_error_list_c", sdbcoreC_make_error_list_c, METH_VARARGS, ""}, {NULL, NULL, 0, NULL}};

// Module specification
static struct PyModuleDef sdbcoreC_module_definition = {
    PyModuleDef_HEAD_INIT, "sdbcoreC", "This module provides C extensions to the sdbcore module.",
    -1, module_methods};

// Initialize the sdbcoreC module
PyMODINIT_FUNC PyInit_sdbcoreC(void) {
  Py_Initialize();
  import_array();
  return PyModule_Create(&sdbcoreC_module_definition);
}
<commit_msg>clang format<commit_after>//===-- sdbcoreC.cpp ----------------------------------------------------------------*- C++ -*-===//
//
//                                    S E R I A L B O X
//
// This file is distributed under terms of BSD license.
// See LICENSE.txt for more information
//
//===------------------------------------------------------------------------------------------===//
//
/// \file
/// This file contains utility functions for the sdb core library
///
//===------------------------------------------------------------------------------------------===//

#include <Python.h>

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

#include <cmath>
#include <iostream>
#include <vector>

namespace {

template <class T>
class NumpyArray {
public:
  NumpyArray(PyArrayObject* array)
      : data_((T*)PyArray_DATA(array)), size_(PyArray_SIZE(array)),
        shape_(PyArray_DIMS(array), PyArray_DIMS(array) + PyArray_NDIM(array)) {}

  /// \brief Access data pointer
  const T* data() const noexcept { return data_; }
  T* data() noexcept { return data_; }

  /// \brief Shape of the numpy array
  const std::vector<npy_intp>& shape() const noexcept { return shape_; }

  /// \brief Size of the array
  npy_intp size() const noexcept { return size_; }

  /// \brief Convert to string
  friend std::ostream& operator<<(std::ostream& stream, const NumpyArray& array) {
    stream << "shape = [ ";
    for(const auto& s : array.shape())
      stream << s << " ";
    stream << "], size = " << array.size() << ", data = " << array.data();
    return stream;
  }

private:
  T* data_;
  npy_intp size_;
  std::vector<npy_intp> shape_;
};

template <class T>
struct ErrorList {
  std::vector<int> index;
  T input_value;
  T reference_value;
};

/// \brief Compute positions of errors of input and reference fields
///
/// The error_position field is set to True if
///
///   absolute(input - reference) <= (atol + rtol * absolute(reference))
///
/// evaluates to False.
template <class T>
inline int compute_error_positions(const NumpyArray<T>& input, const NumpyArray<T>& reference,
                                   NumpyArray<bool>& error_positions, const double& atol,
                                   const double& rtol) noexcept {
  const int size = input.size();
  const T* input_ptr = input.data();
  const T* reference_ptr = reference.data();
  bool* error_positions_ptr = error_positions.data();

  int num_errors = 0;

  for(int i = 0; i < size; ++i) {

    const T a = input_ptr[i];
    const T b = reference_ptr[i];

    const bool res = !(std::abs(a - b) <= (atol + rtol * std::abs(b)));

    num_errors += res;
    error_positions_ptr[i] = res;
  }

  return num_errors;
}

inline void increment_index(std::vector<int>& index, const std::vector<npy_intp>& shape) noexcept {

  const int size = index.size();
  for(int i = 0; i < size; ++i)
    if(++index[i] < shape[i])
      break;
    else
      index[i] = 0;
}

/// \brief Compute list of errors with elements (index, input_value, reference_value)
template <class T>
inline void compute_error_list(const NumpyArray<T>& input, const NumpyArray<T>& reference,
                               const NumpyArray<bool>& error_positions,
                               std::vector<ErrorList<T>>& error_list) noexcept {
  const int size = input.size();
  const T* input_ptr = input.data();
  const T* reference_ptr = reference.data();
  const bool* error_positions_ptr = error_positions.data();

  const std::vector<npy_intp>& shape = input.shape();
  std::vector<int> index(input.shape().size(), 0);
  int error_list_idx = 0;

  for(int i = 0; i < size; ++i, increment_index(index, shape)) {
    if(error_positions_ptr[i]) {
      error_list[error_list_idx].index = index;
      error_list[error_list_idx].input_value = input_ptr[i];
      error_list[error_list_idx].reference_value = reference_ptr[i];
      error_list_idx++;
    }
  }
}

} // anonymous namespace

/// \brief Compute the list of errors and positions
static PyObject* sdbcoreC_make_error_list_c(PyObject* self, PyObject* args) {
  PyObject* input_field;
  PyArrayObject* input_array;

  PyObject* reference_field;
  PyArrayObject* reference_array;

  PyArrayObject* error_positions_array = NULL;
  PyObject* error_list_object = NULL;

  double atol;
  double rtol;

  //
  // Parse arguments
  //
  if(!PyArg_ParseTuple(args, "OOdd", &input_field, &reference_field, &atol, &rtol))
    return NULL;

  try {

    //
    // Extract numpy arrays
    //
    if(!(input_array =
             (PyArrayObject*)PyArray_FROM_OTF(input_field, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY)))
      throw std::runtime_error("internal error: failed to extract input array");

    if(!(reference_array =
             (PyArrayObject*)PyArray_FROM_OTF(reference_field, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY)))
      throw std::runtime_error("internal error: failed to extract reference array");

    NumpyArray<double> input(input_array);
    NumpyArray<double> reference(reference_array);

    if(input.shape() != reference.shape())
      throw std::runtime_error("internal error: dimension mismatch");

    //
    // Allocate error positions array (boolean array)
    //
    error_positions_array = (PyArrayObject*)PyArray_SimpleNew(PyArray_NDIM(input_array),
                                                              PyArray_DIMS(input_array), NPY_BOOL);
    NumpyArray<bool> error_positions(error_positions_array);

    //
    // Compute error positions
    //
    int num_errors = compute_error_positions(input, reference, error_positions, atol, rtol);

    //
    // Allocate list of errors
    //
    std::vector<ErrorList<double>> error_list(num_errors);
    error_list_object = PyList_New(error_list.size());

    //
    // Compute list of errors
    //
    compute_error_list(input, reference, error_positions, error_list);

    //
    // Prepare return
    //
    for(int i = 0; i < error_list.size(); ++i) {

      PyObject* list_element = PyList_New(3);

      PyObject* index_list = PyList_New(error_list[i].index.size());

      const int index_size = error_list[i].index.size();
      for(int ii = 0; ii < error_list[i].index.size(); ++ii)
        PyList_SetItem(index_list, ii, PyLong_FromLong(error_list[i].index[index_size - 1 - ii]));

      PyList_SetItem(list_element, 0, index_list);
      PyList_SetItem(list_element, 1, PyFloat_FromDouble(error_list[i].input_value));
      PyList_SetItem(list_element, 2, PyFloat_FromDouble(error_list[i].reference_value));

      PyList_SetItem(error_list_object, i, list_element);
    }

  } catch(std::runtime_error& e) {
    PyErr_SetString(PyExc_RuntimeError, e.what());

    Py_XDECREF(input_array);
    Py_XDECREF(reference_array);

    if(error_list_object)
      Py_XDECREF(error_list_object);

    if(error_positions_array)
      Py_XDECREF(error_positions_array);

    return NULL;
  }

  return Py_BuildValue("OO", error_list_object, error_positions_array);
}

//===------------------------------------------------------------------------------------------===//
//     Module definitions
//===------------------------------------------------------------------------------------------===//

// Method specification
static PyMethodDef module_methods[] = {
    {"make_error_list_c", sdbcoreC_make_error_list_c, METH_VARARGS, ""}, {NULL, NULL, 0, NULL}};

// Module specification
static struct PyModuleDef sdbcoreC_module_definition = {
    PyModuleDef_HEAD_INIT, "sdbcoreC", "This module provides C extensions to the sdbcore module.",
    -1, module_methods};

// Initialize the sdbcoreC module
PyMODINIT_FUNC PyInit_sdbcoreC(void) {
  Py_Initialize();
  import_array();
  return PyModule_Create(&sdbcoreC_module_definition);
}
<|endoftext|>


<commit_before>#include "net/RawSocket.h"
#include "common/RhodesApp.h"

#include <algorithm>

#if !defined(OS_WINDOWS) && !defined(OS_WINCE)
#include <arpa/inet.h>
#endif

#if !defined(OS_WINCE)
#include <common/stat.h>

#ifdef EAGAIN
#undef EAGAIN
#endif
#define EAGAIN EWOULDBLOCK

#else

#include "CompatWince.h"

#if defined(OS_WINDOWS) || defined(OS_WINCE)
typedef unsigned __int16 uint16_t;

#  ifndef S_ISDIR
#    define S_ISDIR(m) ((_S_IFDIR & m) == _S_IFDIR)
#  endif

#  ifndef S_ISREG
#    define S_ISREG(m) ((_S_IFREG & m) == _S_IFREG)
#  endif

#  ifndef EAGAIN
#    define EAGAIN WSAEWOULDBLOCK
#  endif
#endif

#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "RawSocket"

namespace rho
{
namespace net
{

bool RawSocket::init()
{
    RAWTRACE("Init raw socket");
    m_isInit = create();
    return m_isInit;
}

bool RawSocket::create()
{
    RAWTRACE("Start create raw socket");
    cleanup();

    int iResult;
    addrinfo *addrInfo = NULL, hints;

    memset( &hints, 0, sizeof(hints) );
    hints.ai_family   = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    RAWTRACE("Get host adress");

    // Resolve the server address and port
    iResult = getaddrinfo(m_hostName.c_str(), m_hostPort.c_str(), &hints, &addrInfo);

    if (iResult != 0) {
        RAWTRACE2("Unable to get addres info for host %s, port %s", m_hostName.c_str(), m_hostPort.c_str());
        return false;
    }

    RAWTRACE("Create socket");
    // Create a SOCKET for connecting to server
    m_clientSocket = socket(addrInfo->ai_family, addrInfo->ai_socktype, addrInfo->ai_protocol);

    if (m_clientSocket == INVALID_SOCKET) {
        RAWTRACE2("Socket can`t create for host %s, port %s", m_hostName.c_str(), m_hostPort.c_str());
        freeaddrinfo(addrInfo);
        return false;
    }

    // Connect to server.
    RAWTRACE("Connect to server");
    iResult = connect(m_clientSocket, addrInfo->ai_addr, (int)addrInfo->ai_addrlen);

    if (iResult == SOCKET_ERROR) {
        RAWTRACE2("Can`t connect to host %s, port %s ", m_hostName.c_str(), m_hostPort.c_str());
        cleanup();
        return false;
    }

    freeaddrinfo(addrInfo);

    RAWTRACE("End of socket creating");

    return true;
}

bool RawSocket::send(const String& sendData)
{
    int iResult = 0;

    // Send an initial buffer
    iResult = ::send(m_clientSocket, sendData.c_str(), (int) sendData.size(), 0);

    if (iResult == SOCKET_ERROR)
    {
        RAWTRACE2("Data not send for host %s, port %s", m_hostName.c_str(), m_hostPort.c_str());
        cleanup();
        return false;
    }

    return true;
}

void RawSocket::cleanup()
{
    m_isInit = false;
    closesocket(m_clientSocket);
    m_clientSocket = INVALID_SOCKET;
}

} // namespace net
} // namespace rho

#endif<commit_msg>fix raw socket<commit_after>#include "net/RawSocket.h"
#include "common/RhodesApp.h"

#include <algorithm>

#if !defined(OS_WINDOWS) && !defined(OS_WINCE)
#include <arpa/inet.h>
#endif

#if !defined(OS_WINCE)
#include <common/stat.h>

#ifdef EAGAIN
#undef EAGAIN
#endif
#define EAGAIN EWOULDBLOCK

#else

#include "CompatWince.h"

#if defined(OS_WINDOWS) || defined(OS_WINCE)
typedef unsigned __int16 uint16_t;

#  ifndef S_ISDIR
#    define S_ISDIR(m) ((_S_IFDIR & m) == _S_IFDIR)
#  endif

#  ifndef S_ISREG
#    define S_ISREG(m) ((_S_IFREG & m) == _S_IFREG)
#  endif

#  ifndef EAGAIN
#    define EAGAIN WSAEWOULDBLOCK
#  endif
#endif

#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "RawSocket"

namespace rho
{
namespace net
{

bool RawSocket::init()
{
    //RAWTRACE("Init raw socket");
    m_isInit = create();
    return m_isInit;
}

bool RawSocket::create()
{
    //RAWTRACE("Start create raw socket");
    cleanup();

    int iResult;
    addrinfo *addrInfo = NULL, hints;

    memset( &hints, 0, sizeof(hints) );
    hints.ai_family   = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    //RAWTRACE("Get host adress");

    // Resolve the server address and port
    iResult = getaddrinfo(m_hostName.c_str(), m_hostPort.c_str(), &hints, &addrInfo);

    if (iResult != 0) {
        //RAWTRACE2("Unable to get addres info for host %s, port %s", m_hostName.c_str(), m_hostPort.c_str());
        return false;
    }

    //RAWTRACE("Create socket");
    // Create a SOCKET for connecting to server
    m_clientSocket = socket(addrInfo->ai_family, addrInfo->ai_socktype, addrInfo->ai_protocol);

    if (m_clientSocket == INVALID_SOCKET) {
        //RAWTRACE2("Socket can`t create for host %s, port %s", m_hostName.c_str(), m_hostPort.c_str());
        freeaddrinfo(addrInfo);
        return false;
    }

    // Connect to server.
    //RAWTRACE("Connect to server");
    iResult = connect(m_clientSocket, addrInfo->ai_addr, (int)addrInfo->ai_addrlen);

    if (iResult == SOCKET_ERROR) {
        //RAWTRACE2("Can`t connect to host %s, port %s ", m_hostName.c_str(), m_hostPort.c_str());
        cleanup();
        return false;
    }

    freeaddrinfo(addrInfo);

    //RAWTRACE("End of socket creating");

    return true;
}

bool RawSocket::send(const String& sendData)
{
    int iResult = 0;

    // Send an initial buffer
    iResult = ::send(m_clientSocket, sendData.c_str(), (int) sendData.size(), 0);

    if (iResult == SOCKET_ERROR)
    {
        //RAWTRACE2("Data not send for host %s, port %s", m_hostName.c_str(), m_hostPort.c_str());
        cleanup();
        return false;
    }

    return true;
}

void RawSocket::cleanup()
{
    m_isInit = false;
    closesocket(m_clientSocket);
    m_clientSocket = INVALID_SOCKET;
}

} // namespace net
} // namespace rho

#endif<|endoftext|>


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

#include "SurgSim/Graphics/OsgManager.h"

#include <vector>

#include "SurgSim/Framework/Log.h"
#include "SurgSim/Framework/Scene.h"
#include "SurgSim/Framework/Runtime.h"

#include "SurgSim/Graphics/OsgRepresentation.h"
#include "SurgSim/Graphics/OsgCamera.h"
#include "SurgSim/Graphics/OsgGroup.h"
#include "SurgSim/Graphics/OsgView.h"
#include "SurgSim/Graphics/OsgScreenSpacePass.h"

#include <osgViewer/Scene>
#include <osgDB/WriteFile>

using SurgSim::Graphics::OsgRepresentation;
using SurgSim::Graphics::OsgCamera;
using SurgSim::Graphics::OsgGroup;
using SurgSim::Graphics::OsgManager;

namespace SurgSim
{
namespace Graphics
{
OsgManager::OsgManager() : SurgSim::Graphics::Manager(),
	m_viewer(new osgViewer::CompositeViewer())
{
}

OsgManager::~OsgManager()
{
}

std::shared_ptr<Group> OsgManager::getOrCreateGroup(const std::string& name)
{
	std::shared_ptr<Group> result;
	auto groups = getGroups();

	auto group = groups.find(name);

	if (group == std::end(groups))
	{
		auto newGroup = std::make_shared<OsgGroup>(name);
		addGroup(newGroup);
		result = newGroup;
	}
	else
	{
		result = group->second;
	}

	return result;
}

bool OsgManager::addRepresentation(std::shared_ptr<SurgSim::Graphics::Representation> representation)
{
	std::shared_ptr<OsgRepresentation> osgRepresentation = std::dynamic_pointer_cast<OsgRepresentation>(representation);
	bool result;
	if (osgRepresentation)
	{
		result = Manager::addRepresentation(osgRepresentation);
	}
	else
	{
		SURGSIM_LOG_INFO(getLogger())
				<< __FUNCTION__ << " Representation is not a subclass of OsgRepresentation "
				<< representation->getName();
		result = false;
	}
	return result;
}

bool OsgManager::addView(std::shared_ptr<SurgSim::Graphics::View> view)
{
	std::shared_ptr<OsgView> osgView = std::dynamic_pointer_cast<OsgView>(view);

	bool result = true;
	if (osgView == nullptr)
	{
		SURGSIM_LOG_WARNING(getLogger()) << __FUNCTION__ << " View is not a subclass of OsgView " << view->getName();
		result = false;
	}
	else
	{
		SURGSIM_ASSERT(view->getCamera() != nullptr) << "View should have a camera when added to the manager.";
		if (Manager::addView(view))
		{
			m_viewer->addView(osgView->getOsgView());
		}
	}

	return result;
}

bool OsgManager::removeView(std::shared_ptr<SurgSim::Graphics::View> view)
{
	std::shared_ptr<OsgView> osgView = std::dynamic_pointer_cast<OsgView>(view);
	if (osgView)
	{
		m_viewer->removeView(osgView->getOsgView());
	}

	return Manager::removeView(view);
}

bool OsgManager::doInitialize()
{
	m_hudElement = std::make_shared<OsgScreenSpacePass>(Representation::DefaultHudGroupName);
	return true;
}

bool OsgManager::doStartUp()
{
	return true;
}

bool OsgManager::doUpdate(double dt)
{

	// There is a bug in the scene initialisation where addSceneElement() will not be correctly executed if
	// performed inside of doInitialize(), this needs to be fixed
	// HS-2014-dec-12
	// #workaround
	if (!m_hudElement->isInitialized())
	{
		getRuntime()->getScene()->addSceneElement(m_hudElement);
	}

	if (Manager::doUpdate(dt))
	{
		m_viewer->frame();

		// \note HS-2013-dec-12 This will work as long as we deal with one view, when we move to stereoscopic
		//	     we might have to revise things. Or just assume that most views have the same size
		if (m_viewer->getNumViews() > 0)
		{
			auto dimensions = getViews()[0]->getDimensions();
			m_hudElement->setViewPort(dimensions[0], dimensions[1]);
		}
		return true;
	}
	else
	{
		return false;
	}
}

void OsgManager::doBeforeStop()
{
	dumpDebugInfo();
	// Delete the viewer so that the graphics context will be released in the manager's thread
	m_viewer = nullptr;
}

osg::ref_ptr<osgViewer::CompositeViewer> OsgManager::getOsgCompositeViewer() const
{
	return m_viewer;
}

void SurgSim::Graphics::OsgManager::dumpDebugInfo() const
{
	osgDB::writeNodeFile(*m_viewer->getView(0)->getCamera(), "viewer_zero_camera.osgt");
}

}
}

<commit_msg>Prevent OsgManager from dumping out its scenegraph automatically when not in debug<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "SurgSim/Graphics/OsgManager.h"

#include <vector>

#include "SurgSim/Framework/Log.h"
#include "SurgSim/Framework/Scene.h"
#include "SurgSim/Framework/Runtime.h"

#include "SurgSim/Graphics/OsgRepresentation.h"
#include "SurgSim/Graphics/OsgCamera.h"
#include "SurgSim/Graphics/OsgGroup.h"
#include "SurgSim/Graphics/OsgView.h"
#include "SurgSim/Graphics/OsgScreenSpacePass.h"

#include <osgViewer/Scene>
#include <osgDB/WriteFile>

using SurgSim::Graphics::OsgRepresentation;
using SurgSim::Graphics::OsgCamera;
using SurgSim::Graphics::OsgGroup;
using SurgSim::Graphics::OsgManager;

namespace SurgSim
{
namespace Graphics
{
OsgManager::OsgManager() : SurgSim::Graphics::Manager(),
	m_viewer(new osgViewer::CompositeViewer())
{
}

OsgManager::~OsgManager()
{
}

std::shared_ptr<Group> OsgManager::getOrCreateGroup(const std::string& name)
{
	std::shared_ptr<Group> result;
	auto groups = getGroups();

	auto group = groups.find(name);

	if (group == std::end(groups))
	{
		auto newGroup = std::make_shared<OsgGroup>(name);
		addGroup(newGroup);
		result = newGroup;
	}
	else
	{
		result = group->second;
	}

	return result;
}

bool OsgManager::addRepresentation(std::shared_ptr<SurgSim::Graphics::Representation> representation)
{
	std::shared_ptr<OsgRepresentation> osgRepresentation = std::dynamic_pointer_cast<OsgRepresentation>(representation);
	bool result;
	if (osgRepresentation)
	{
		result = Manager::addRepresentation(osgRepresentation);
	}
	else
	{
		SURGSIM_LOG_INFO(getLogger())
				<< __FUNCTION__ << " Representation is not a subclass of OsgRepresentation "
				<< representation->getName();
		result = false;
	}
	return result;
}

bool OsgManager::addView(std::shared_ptr<SurgSim::Graphics::View> view)
{
	std::shared_ptr<OsgView> osgView = std::dynamic_pointer_cast<OsgView>(view);

	bool result = true;
	if (osgView == nullptr)
	{
		SURGSIM_LOG_WARNING(getLogger()) << __FUNCTION__ << " View is not a subclass of OsgView " << view->getName();
		result = false;
	}
	else
	{
		SURGSIM_ASSERT(view->getCamera() != nullptr) << "View should have a camera when added to the manager.";
		if (Manager::addView(view))
		{
			m_viewer->addView(osgView->getOsgView());
		}
	}

	return result;
}

bool OsgManager::removeView(std::shared_ptr<SurgSim::Graphics::View> view)
{
	std::shared_ptr<OsgView> osgView = std::dynamic_pointer_cast<OsgView>(view);
	if (osgView)
	{
		m_viewer->removeView(osgView->getOsgView());
	}

	return Manager::removeView(view);
}

bool OsgManager::doInitialize()
{
	m_hudElement = std::make_shared<OsgScreenSpacePass>(Representation::DefaultHudGroupName);
	return true;
}

bool OsgManager::doStartUp()
{
	return true;
}

bool OsgManager::doUpdate(double dt)
{

	// There is a bug in the scene initialisation where addSceneElement() will not be correctly executed if
	// performed inside of doInitialize(), this needs to be fixed
	// HS-2014-dec-12
	// #workaround
	if (!m_hudElement->isInitialized())
	{
		getRuntime()->getScene()->addSceneElement(m_hudElement);
	}

	if (Manager::doUpdate(dt))
	{
		m_viewer->frame();

		// \note HS-2013-dec-12 This will work as long as we deal with one view, when we move to stereoscopic
		//	     we might have to revise things. Or just assume that most views have the same size
		if (m_viewer->getNumViews() > 0)
		{
			auto dimensions = getViews()[0]->getDimensions();
			m_hudElement->setViewPort(dimensions[0], dimensions[1]);
		}
		return true;
	}
	else
	{
		return false;
	}
}

void OsgManager::doBeforeStop()
{
#ifdef OSS_DEBUG
	dumpDebugInfo();
#endif
	// Delete the viewer so that the graphics context will be released in the manager's thread
	m_viewer = nullptr;
}

osg::ref_ptr<osgViewer::CompositeViewer> OsgManager::getOsgCompositeViewer() const
{
	return m_viewer;
}

void SurgSim::Graphics::OsgManager::dumpDebugInfo() const
{
	osgDB::writeNodeFile(*m_viewer->getView(0)->getCamera(), "viewer_zero_camera.osgt");
}

}
}

<|endoftext|>


<commit_before>#ifndef ITERTOOLS_HPP
#define ITERTOOLS_HPP

#include "chain.hpp"
#include "combinations.hpp"
#include "combinations_with_replacement.hpp"
#include "compress.hpp"
#include "count.hpp"
#include "cycle.hpp"
#include "dropwhile.hpp"
#include "enumerate.hpp"
#include "filter.hpp"
#include "filterfalse.hpp"
#include "groupby.hpp"
#include "grouper.hpp"
#include "imap.hpp"
#include "iterator_range.hpp"
#include "sliding_window.hpp"
#include "permutations.hpp"
#include "powerset.hpp"
#include "product.hpp"
#include "range.hpp"
#include "repeat.hpp"
#include "reverse.hpp"
#include "slice.hpp"
#include "sorted.hpp"
#include "takewhile.hpp"
#include "unique_everseen.hpp"
#include "unique_justseen.hpp"
#include "wrap_iter.hpp"
#include "zip.hpp"
#include "zip_longest.hpp"
//not sure if should include "iterator_range.hpp"
//since it's already in everything

#endif

<commit_msg>Renames reverse to reversed in itertools.hpp<commit_after>#ifndef ITERTOOLS_HPP
#define ITERTOOLS_HPP

#include "chain.hpp"
#include "combinations.hpp"
#include "combinations_with_replacement.hpp"
#include "compress.hpp"
#include "count.hpp"
#include "cycle.hpp"
#include "dropwhile.hpp"
#include "enumerate.hpp"
#include "filter.hpp"
#include "filterfalse.hpp"
#include "groupby.hpp"
#include "grouper.hpp"
#include "imap.hpp"
#include "iterator_range.hpp"
#include "sliding_window.hpp"
#include "permutations.hpp"
#include "powerset.hpp"
#include "product.hpp"
#include "range.hpp"
#include "repeat.hpp"
#include "reversed.hpp"
#include "slice.hpp"
#include "sorted.hpp"
#include "takewhile.hpp"
#include "unique_everseen.hpp"
#include "unique_justseen.hpp"
#include "wrap_iter.hpp"
#include "zip.hpp"
#include "zip_longest.hpp"
//not sure if should include "iterator_range.hpp"
//since it's already in everything

#endif

<|endoftext|>


<commit_before>/*
 * D-Bus AT-SPI, Qt Adaptor
 *
 * Copyright 2009-2011 Nokia Corporation and/or its subsidiary(-ies).
 *
 * This library 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 2.1 of the License, or (at your option) any later version.
 *
 * 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, see <http://www.gnu.org/licenses/>.
 */

#include "accessible.h"

#include <QDBusPendingReply>
#include <QDebug>
#include <QtGui/QWidget>

#include <QAccessibleValueInterface>

#include "adaptor.h"
#include "bridge.h"
#include "cache.h"

#include "generated/accessible_adaptor.h"
#include "generated/action_adaptor.h"
#include "generated/component_adaptor.h"
#include "generated/editable_text_adaptor.h"
#include "generated/event_adaptor.h"
#include "generated/socket_proxy.h"
#include "generated/table_adaptor.h"
#include "generated/text_adaptor.h"
#include "generated/value_adaptor.h"

#define ACCESSIBLE_CREATION_DEBUG

#define QSPI_REGISTRY_NAME "org.a11y.atspi.Registry"

QString QSpiAccessible::pathForObject(QObject *object)
{
    Q_ASSERT(object);
    return QSPI_OBJECT_PATH_PREFIX + QString::number(reinterpret_cast<size_t>(object));
}

QString QSpiAccessible::pathForInterface(QAccessibleInterface *interface, int childIndex)
{
    QString path;
    QAccessibleInterface* interfaceWithObject = interface;
    while(!interfaceWithObject->object()) {
        QAccessibleInterface* parentInterface;
        interfaceWithObject->navigate(QAccessible::Ancestor, 1, &parentInterface);
        Q_ASSERT(parentInterface->isValid());
        int index = parentInterface->indexOfChild(interfaceWithObject);
        //Q_ASSERT(index >= 0);
        // FIXME: This should never happen!
        if (index < 0) {

            index = 999;
            path.prepend("/BROKEN_OBJECT_HIERARCHY");
            qWarning() << "Object claims to have child that we cannot navigate to. FIX IT!" << parentInterface->object();

            qDebug() << "Original interface: " << interface->object() << index;
            qDebug() << "Parent interface: " << parentInterface->object() << " childcount:" << parentInterface->childCount();
            QObject* p = parentInterface->object();
            qDebug() << p->children();

            QAccessibleInterface* tttt;
            int id = parentInterface->navigate(QAccessible::Child, 1, &tttt);
            qDebug() << "Nav child: " << id << tttt->object();
        }
        path.prepend('/' + QString::number(index));
        interfaceWithObject = parentInterface;
    }
    path.prepend(QSPI_OBJECT_PATH_PREFIX + QString::number(reinterpret_cast<quintptr>(interfaceWithObject->object())));

    if (childIndex > 0) {
        path.append('/' + QString::number(childIndex));
    }
    return path;
}

QPair<QAccessibleInterface*, int> QSpiAccessible::interfaceFromPath(const QString& dbusPath)
{
    QStringList parts = dbusPath.split('/');

    Q_ASSERT(parts.size() > 5);

    // ignore the first /org/a11y/atspi/accessible/
    QString objectString = parts.at(5);

    quintptr uintptr = objectString.toULongLong();

    if (!uintptr)
        return QPair<QAccessibleInterface*, int>(0, 0);

    QObject* object = reinterpret_cast<QObject*>(uintptr);

    qDebug() << object;
    QAccessibleInterface* inter = QAccessible::queryAccessibleInterface(object);
    QAccessibleInterface* childInter;

    int index = 0;

    for (int i = 6; i < parts.size(); ++i) {
        index = inter->navigate(QAccessible::Child, parts.at(i).toInt(), &childInter);
        if (index == 0) {
            delete inter;
            inter = childInter;
        }
    }

    return QPair<QAccessibleInterface*, int>(inter, index);
}

QSpiAccessible::QSpiAccessible(QAccessibleInterface *interface, int index)
    : QSpiAdaptor(interface, index)
{
    QString path = pathForInterface(interface, index);
    QDBusObjectPath dbusPath = QDBusObjectPath(path);

    reference = QSpiObjectReference(spiBridge->dBusConnection(),
                                               dbusPath);
#ifdef ACCESSIBLE_CREATION_DEBUG
    qDebug() << "ACCESSIBLE: " << interface->object() << reference.path.path() << interface->text(QAccessible::Name, index);
#endif

    new AccessibleAdaptor(this);
    supportedInterfaces << QSPI_INTERFACE_ACCESSIBLE;

    if (    (!interface->rect(index).isEmpty()) ||
            (interface->object() && interface->object()->isWidgetType()) ||
            (interface->role(index) == QAccessible::ListItem) ||
            (interface->role(index) == QAccessible::Cell) ||
            (interface->role(index) == QAccessible::TreeItem) ||
            (interface->role(index) == QAccessible::Row) ||
            (interface->object() && interface->object()->inherits("QSGItem"))
            ) {
        new ComponentAdaptor(this);
        supportedInterfaces << QSPI_INTERFACE_COMPONENT;

        if (interface->object() && interface->object()->isWidgetType()) {
            QWidget *w = qobject_cast<QWidget*>(interface->object());
            if (w->isWindow()) {
                new WindowAdaptor(this);
#ifdef ACCESSIBLE_CREATION_DEBUG
                qDebug() << " IS a window";
#endif
            }
        }
    }
#ifdef ACCESSIBLE_CREATION_DEBUG
    else {
        qDebug() << " IS NOT a component";
    }
#endif

    new ObjectAdaptor(this);
    new FocusAdaptor(this);

    if (interface->actionInterface())
    {
        new ActionAdaptor(this);
        supportedInterfaces << QSPI_INTERFACE_ACTION;
    }
    if (interface->textInterface())
    {
        new TextAdaptor(this);
        supportedInterfaces << QSPI_INTERFACE_TEXT;
        oldText = interface->textInterface()->text(0, interface->textInterface()->characterCount());
    }
    if (interface->editableTextInterface())
    {
        new EditableTextAdaptor(this);
        supportedInterfaces << QSPI_INTERFACE_EDITABLE_TEXT;
    }
    if (interface->valueInterface())
    {
        new ValueAdaptor(this);
        supportedInterfaces << QSPI_INTERFACE_VALUE;
    }
    if (interface->table2Interface())
    {
        new TableAdaptor(this);
        supportedInterfaces << QSPI_INTERFACE_TABLE;
    }

    spiBridge->dBusConnection().registerObject(reference.path.path(),
                                  this, QDBusConnection::ExportAdaptors);
    state = interface->state(childIndex());
}

QSpiObjectReference QSpiAccessible::getParentReference() const
{
    Q_ASSERT(interface);

    if (interface->isValid()) {
        QAccessibleInterface *parentInterface = 0;
        interface->navigate(QAccessible::Ancestor, 1, &parentInterface);
        if (parentInterface) {
            QSpiAdaptor *parent = spiBridge->objectToAccessible(parentInterface->object());
            delete parentInterface;
            if (parent)
                return parent->getReference();
        }
    }
    qWarning() << "Invalid parent: " << interface << interface->object();
    return QSpiObjectReference();
}

void QSpiAccessible::accessibleEvent(QAccessible::Event event)
{
    Q_ASSERT(interface);
    if (!interface->isValid()) {
        spiBridge->removeAdaptor(this);
        return;
    }

    switch (event) {
    case QAccessible::NameChanged: {
        QSpiObjectReference r = getReference();
        QDBusVariant data;
        data.setVariant(QVariant::fromValue(r));
        emit PropertyChange("accessible-name", 0, 0, data, spiBridge->getRootReference());
        break;
    }
    case QAccessible::DescriptionChanged: {
        QSpiObjectReference r = getReference();
        QDBusVariant data;
        data.setVariant(QVariant::fromValue(r));
        emit PropertyChange("accessible-description", 0, 0, data, spiBridge->getRootReference());
        break;
    }
    case QAccessible::Focus: {

        qDebug() << "Focus: " << getReference().path.path() << interface->object();

        QDBusVariant data;
        data.setVariant(QVariant::fromValue(getReference()));
        emit StateChanged("focused", 1, 0, data, spiBridge->getRootReference());
        emit Focus("", 0, 0, data, spiBridge->getRootReference());
        break;
    }
#if (QT_VERSION >= QT_VERSION_CHECK(4, 8, 0))
    case QAccessible::TextUpdated: {
        Q_ASSERT(interface->textInterface());

        // at-spi doesn't have a proper text updated/changed, so remove all and re-add the new text
        qDebug() << "Text changed: " << interface->object();
        QDBusVariant data;
        data.setVariant(QVariant::fromValue(oldText));
        emit TextChanged("delete", 0, oldText.length(), data, spiBridge->getRootReference());

        QString text = interface->textInterface()->text(0, interface->textInterface()->characterCount());
        data.setVariant(QVariant::fromValue(text));
        emit TextChanged("insert", 0, text.length(), data, spiBridge->getRootReference());
        oldText = text;

        QDBusVariant cursorData;
        int pos = interface->textInterface()->cursorPosition();
        cursorData.setVariant(QVariant::fromValue(pos));
        emit TextCaretMoved(QString(), pos ,0, cursorData, spiBridge->getRootReference());
        break;
    }
    case QAccessible::TextCaretMoved: {
        Q_ASSERT(interface->textInterface());
        qDebug() << "Text caret moved: " << interface->object();
        QDBusVariant data;
        int pos = interface->textInterface()->cursorPosition();
        data.setVariant(QVariant::fromValue(pos));
        emit TextCaretMoved(QString(), pos ,0, data, spiBridge->getRootReference());
        break;
    }
#endif
    case QAccessible::ValueChanged: {
        Q_ASSERT(interface->valueInterface());
        QDBusVariant data;
        data.setVariant(QVariant::fromValue(getReference()));
        emit PropertyChange("accessible-value", 0, 0, data, spiBridge->getRootReference());
        break;
    }
    case QAccessible::ObjectShow:
        break;
    case QAccessible::ObjectHide:
        // TODO - send status changed
//        qWarning() << "Object hide";
        break;
    case QAccessible::ObjectDestroyed:
        // TODO - maybe send children-changed and cache Removed
//        qWarning() << "Object destroyed";
        break;
    case QAccessible::StateChanged: {
        QAccessible::State newState = interface->state(childIndex());
//        qDebug() << "StateChanged: old: " << state << " new: " << newState << " xor: " << (state^newState);
        if ((state^newState) & QAccessible::Checked) {
            int checked = (newState & QAccessible::Checked) ? 1 : 0;
            QDBusVariant data;
            data.setVariant(QVariant::fromValue(getReference()));
            emit StateChanged("checked", checked, 0, data, spiBridge->getRootReference());
        }
        state = newState;
        break;
    }
    case QAccessible::TableModelChanged: {
        // FIXME: react to table layout changes - added rows etc
//        QAccessible2::TableModelChange change = interface->table2Interface()->modelChange();
//        QDBusVariant data;
//        data.setVariant(QVariant::fromValue(getReference()));
//        signalChildrenChanged("add", interface->childCount(), 0, data);
//        // model-changed
//         emit ChildrenChanged(type, detail1, detail2, data, spiBridge->getRootReference());
        break;
    }
    case QAccessible::ParentChanged:
        // TODO - send parent changed
    default:
//        qWarning() << "QSpiAccessible::accessibleEvent not handled: " << QString::number(event, 16)
//                   << " obj: " << interface->object()
//                   << (interface->isValid() ? interface->object()->objectName() : " invalid interface!");
        break;
    }
}

void QSpiAccessible::windowActivated()
{
    QDBusVariant data;
    data.setVariant(QString());
    emit Create("", 0, 0, data, spiBridge->getRootReference());
    emit Restore("", 0, 0, data, spiBridge->getRootReference());
    emit Activate("", 0, 0, data, spiBridge->getRootReference());
}
<commit_msg>Improve tables adding cells slightly.<commit_after>/*
 * D-Bus AT-SPI, Qt Adaptor
 *
 * Copyright 2009-2011 Nokia Corporation and/or its subsidiary(-ies).
 *
 * This library 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 2.1 of the License, or (at your option) any later version.
 *
 * 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, see <http://www.gnu.org/licenses/>.
 */

#include "accessible.h"

#include <QDBusPendingReply>
#include <QDebug>
#include <QtGui/QWidget>

#include <QAccessibleValueInterface>

#include "adaptor.h"
#include "bridge.h"
#include "cache.h"

#include "generated/accessible_adaptor.h"
#include "generated/action_adaptor.h"
#include "generated/component_adaptor.h"
#include "generated/editable_text_adaptor.h"
#include "generated/event_adaptor.h"
#include "generated/socket_proxy.h"
#include "generated/table_adaptor.h"
#include "generated/text_adaptor.h"
#include "generated/value_adaptor.h"

#define ACCESSIBLE_CREATION_DEBUG

#define QSPI_REGISTRY_NAME "org.a11y.atspi.Registry"

QString QSpiAccessible::pathForObject(QObject *object)
{
    Q_ASSERT(object);
    return QSPI_OBJECT_PATH_PREFIX + QString::number(reinterpret_cast<size_t>(object));
}

QString QSpiAccessible::pathForInterface(QAccessibleInterface *interface, int childIndex)
{
    QString path;
    QAccessibleInterface* interfaceWithObject = interface;
    while(!interfaceWithObject->object()) {
        QAccessibleInterface* parentInterface;
        interfaceWithObject->navigate(QAccessible::Ancestor, 1, &parentInterface);
        Q_ASSERT(parentInterface->isValid());
        int index = parentInterface->indexOfChild(interfaceWithObject);
        //Q_ASSERT(index >= 0);
        // FIXME: This should never happen!
        if (index < 0) {

            index = 999;
            path.prepend("/BROKEN_OBJECT_HIERARCHY");
            qWarning() << "Object claims to have child that we cannot navigate to. FIX IT!" << parentInterface->object();

            qDebug() << "Original interface: " << interface->object() << index;
            qDebug() << "Parent interface: " << parentInterface->object() << " childcount:" << parentInterface->childCount();
            QObject* p = parentInterface->object();
            qDebug() << p->children();

            QAccessibleInterface* tttt;
            int id = parentInterface->navigate(QAccessible::Child, 1, &tttt);
            qDebug() << "Nav child: " << id << tttt->object();
        }
        path.prepend('/' + QString::number(index));
        interfaceWithObject = parentInterface;
    }
    path.prepend(QSPI_OBJECT_PATH_PREFIX + QString::number(reinterpret_cast<quintptr>(interfaceWithObject->object())));

    if (childIndex > 0) {
        path.append('/' + QString::number(childIndex));
    }
    return path;
}

QPair<QAccessibleInterface*, int> QSpiAccessible::interfaceFromPath(const QString& dbusPath)
{
    QStringList parts = dbusPath.split('/');

    Q_ASSERT(parts.size() > 5);

    // ignore the first /org/a11y/atspi/accessible/
    QString objectString = parts.at(5);

    quintptr uintptr = objectString.toULongLong();

    if (!uintptr)
        return QPair<QAccessibleInterface*, int>(0, 0);

    QObject* object = reinterpret_cast<QObject*>(uintptr);

    qDebug() << object;
    QAccessibleInterface* inter = QAccessible::queryAccessibleInterface(object);
    QAccessibleInterface* childInter;

    int index = 0;

    for (int i = 6; i < parts.size(); ++i) {
        index = inter->navigate(QAccessible::Child, parts.at(i).toInt(), &childInter);
        if (index == 0) {
            delete inter;
            inter = childInter;
        }
    }

    return QPair<QAccessibleInterface*, int>(inter, index);
}

QSpiAccessible::QSpiAccessible(QAccessibleInterface *interface, int index)
    : QSpiAdaptor(interface, index)
{
    QString path = pathForInterface(interface, index);
    QDBusObjectPath dbusPath = QDBusObjectPath(path);

    reference = QSpiObjectReference(spiBridge->dBusConnection(),
                                               dbusPath);
#ifdef ACCESSIBLE_CREATION_DEBUG
    qDebug() << "ACCESSIBLE: " << interface->object() << reference.path.path() << interface->text(QAccessible::Name, index);
#endif

    new AccessibleAdaptor(this);
    supportedInterfaces << QSPI_INTERFACE_ACCESSIBLE;

    if (    (!interface->rect(index).isEmpty()) ||
            (interface->object() && interface->object()->isWidgetType()) ||
            (interface->role(index) == QAccessible::ListItem) ||
            (interface->role(index) == QAccessible::Cell) ||
            (interface->role(index) == QAccessible::TreeItem) ||
            (interface->role(index) == QAccessible::Row) ||
            (interface->object() && interface->object()->inherits("QSGItem"))
            ) {
        new ComponentAdaptor(this);
        supportedInterfaces << QSPI_INTERFACE_COMPONENT;

        if (interface->object() && interface->object()->isWidgetType()) {
            QWidget *w = qobject_cast<QWidget*>(interface->object());
            if (w->isWindow()) {
                new WindowAdaptor(this);
#ifdef ACCESSIBLE_CREATION_DEBUG
                qDebug() << " IS a window";
#endif
            }
        }
    }
#ifdef ACCESSIBLE_CREATION_DEBUG
    else {
        qDebug() << " IS NOT a component";
    }
#endif

    new ObjectAdaptor(this);
    new FocusAdaptor(this);

    if (interface->actionInterface())
    {
        new ActionAdaptor(this);
        supportedInterfaces << QSPI_INTERFACE_ACTION;
    }
    if (interface->textInterface())
    {
        new TextAdaptor(this);
        supportedInterfaces << QSPI_INTERFACE_TEXT;
        oldText = interface->textInterface()->text(0, interface->textInterface()->characterCount());
    }
    if (interface->editableTextInterface())
    {
        new EditableTextAdaptor(this);
        supportedInterfaces << QSPI_INTERFACE_EDITABLE_TEXT;
    }
    if (interface->valueInterface())
    {
        new ValueAdaptor(this);
        supportedInterfaces << QSPI_INTERFACE_VALUE;
    }
    if (interface->table2Interface())
    {
        new TableAdaptor(this);
        supportedInterfaces << QSPI_INTERFACE_TABLE;
    }

    spiBridge->dBusConnection().registerObject(reference.path.path(),
                                  this, QDBusConnection::ExportAdaptors);
    state = interface->state(childIndex());
}

QSpiObjectReference QSpiAccessible::getParentReference() const
{
    Q_ASSERT(interface);

    if (interface->isValid()) {
        QAccessibleInterface *parentInterface = 0;
        interface->navigate(QAccessible::Ancestor, 1, &parentInterface);
        if (parentInterface) {
            QSpiAdaptor *parent = spiBridge->objectToAccessible(parentInterface->object());
            delete parentInterface;
            if (parent)
                return parent->getReference();
        }
    }
    qWarning() << "Invalid parent: " << interface << interface->object();
    return QSpiObjectReference();
}

void QSpiAccessible::accessibleEvent(QAccessible::Event event)
{
    Q_ASSERT(interface);
    if (!interface->isValid()) {
        spiBridge->removeAdaptor(this);
        return;
    }

    switch (event) {
    case QAccessible::NameChanged: {
        QSpiObjectReference r = getReference();
        QDBusVariant data;
        data.setVariant(QVariant::fromValue(r));
        emit PropertyChange("accessible-name", 0, 0, data, spiBridge->getRootReference());
        break;
    }
    case QAccessible::DescriptionChanged: {
        QSpiObjectReference r = getReference();
        QDBusVariant data;
        data.setVariant(QVariant::fromValue(r));
        emit PropertyChange("accessible-description", 0, 0, data, spiBridge->getRootReference());
        break;
    }
    case QAccessible::Focus: {

        qDebug() << "Focus: " << getReference().path.path() << interface->object();

        QDBusVariant data;
        data.setVariant(QVariant::fromValue(getReference()));
        emit StateChanged("focused", 1, 0, data, spiBridge->getRootReference());
        emit Focus("", 0, 0, data, spiBridge->getRootReference());
        break;
    }
#if (QT_VERSION >= QT_VERSION_CHECK(4, 8, 0))
    case QAccessible::TextUpdated: {
        Q_ASSERT(interface->textInterface());

        // at-spi doesn't have a proper text updated/changed, so remove all and re-add the new text
        qDebug() << "Text changed: " << interface->object();
        QDBusVariant data;
        data.setVariant(QVariant::fromValue(oldText));
        emit TextChanged("delete", 0, oldText.length(), data, spiBridge->getRootReference());

        QString text = interface->textInterface()->text(0, interface->textInterface()->characterCount());
        data.setVariant(QVariant::fromValue(text));
        emit TextChanged("insert", 0, text.length(), data, spiBridge->getRootReference());
        oldText = text;

        QDBusVariant cursorData;
        int pos = interface->textInterface()->cursorPosition();
        cursorData.setVariant(QVariant::fromValue(pos));
        emit TextCaretMoved(QString(), pos ,0, cursorData, spiBridge->getRootReference());
        break;
    }
    case QAccessible::TextCaretMoved: {
        Q_ASSERT(interface->textInterface());
        qDebug() << "Text caret moved: " << interface->object();
        QDBusVariant data;
        int pos = interface->textInterface()->cursorPosition();
        data.setVariant(QVariant::fromValue(pos));
        emit TextCaretMoved(QString(), pos ,0, data, spiBridge->getRootReference());
        break;
    }
#endif
    case QAccessible::ValueChanged: {
        Q_ASSERT(interface->valueInterface());
        QDBusVariant data;
        data.setVariant(QVariant::fromValue(getReference()));
        emit PropertyChange("accessible-value", 0, 0, data, spiBridge->getRootReference());
        break;
    }
    case QAccessible::ObjectShow:
        break;
    case QAccessible::ObjectHide:
        // TODO - send status changed
//        qWarning() << "Object hide";
        break;
    case QAccessible::ObjectDestroyed:
        // TODO - maybe send children-changed and cache Removed
//        qWarning() << "Object destroyed";
        break;
    case QAccessible::StateChanged: {
        QAccessible::State newState = interface->state(childIndex());
//        qDebug() << "StateChanged: old: " << state << " new: " << newState << " xor: " << (state^newState);
        if ((state^newState) & QAccessible::Checked) {
            int checked = (newState & QAccessible::Checked) ? 1 : 0;
            QDBusVariant data;
            data.setVariant(QVariant::fromValue(getReference()));
            emit StateChanged("checked", checked, 0, data, spiBridge->getRootReference());
        }
        state = newState;
        break;
    }
    case QAccessible::TableModelChanged: {
        // This is rather evil. We don't send data and hope that at-spi fetches the right child.
        // This hack fails when a row gets removed and a different one added in its place.
        QDBusVariant data;
        emit ChildrenChanged("add", 0, 0, data, spiBridge->getRootReference());
        break;
    }
    case QAccessible::ParentChanged:
        // TODO - send parent changed
    default:
//        qWarning() << "QSpiAccessible::accessibleEvent not handled: " << QString::number(event, 16)
//                   << " obj: " << interface->object()
//                   << (interface->isValid() ? interface->object()->objectName() : " invalid interface!");
        break;
    }
}

void QSpiAccessible::windowActivated()
{
    QDBusVariant data;
    data.setVariant(QString());
    emit Create("", 0, 0, data, spiBridge->getRootReference());
    emit Restore("", 0, 0, data, spiBridge->getRootReference());
    emit Activate("", 0, 0, data, spiBridge->getRootReference());
}
<|endoftext|>


<commit_before>#include "..\header\Game.h"
#include "..\header\Border.h"

Border::Border(game_state* GameState){
	LogManager& log = LogManager::getInstance();
	log.writeLog("[Border] Initializing Border.");
	GraphicsManager& g = GraphicsManager::getInstance();
	WorldManager& world = WorldManager::getInstance();
	ResourceManager& resource = ResourceManager::getInstance();
	if (!resource.isStarted() || !g.isStarted() || !world.isStarted()){
		log.writeLog("[Border] Something is wrong with manager startups. Order: %s %s %s", BoolToString(resource.isStarted()), BoolToString(g.isStarted()), BoolToString(world.isStarted()));
		world.markForDelete(this);
		return;
	}

	Sprite* tempSprite = resource.getSprite("border");
	if (tempSprite){
		log.writeLog("[Border] Successfully loaded Border sprite.");
		setSprite(tempSprite);
		setSpriteSlowdown(5);
		setTransparency();
		setSolidness(Solidness::HARD);
		setType(TYPE_BORDER);
		registerInterest(DF_STEP_EVENT);
		setVisible(true);

		int w = g.getHorizontal() / 2;
		int h = g.getVertical() / 2;
		Position pos(w, h);
		setPosition(pos);

		this->width = tempSprite->getWidth();
		this->height = tempSprite->getHeight();
		GameState->PlayerState.minX = w - (tempSprite->getWidth() / 2);
		GameState->PlayerState.minX = h - (tempSprite->getHeight() / 2);
		GameState->PlayerState.maxX = w + (tempSprite->getWidth() / 2);
		GameState->PlayerState.maxY = h + (tempSprite->getHeight() / 2);
	}
	else {
		log.writeLog("[Border] Something is wrong with loading the sprite. Aborting.");
	}
	return;
}

int Border::eventHandler(Event* e){
	if (e->getType() == DF_STEP_EVENT){
		return 1;
	}
	return 0;
}

void Border::draw(){
	Object::draw();
}

int Border::getWidth(){
	return this->width;
}

int Border::getHeight(){
	return this->height;
}<commit_msg>Adding notes about borders and layouts.<commit_after>#include "..\header\Game.h"
#include "..\header\Border.h"

Border::Border(game_state* GameState){
	LogManager& log = LogManager::getInstance();
	log.writeLog("[Border] Initializing Border.");
	GraphicsManager& g = GraphicsManager::getInstance();
	WorldManager& world = WorldManager::getInstance();
	ResourceManager& resource = ResourceManager::getInstance();
	if (!resource.isStarted() || !g.isStarted() || !world.isStarted()){
		log.writeLog("[Border] Something is wrong with manager startups. Order: %s %s %s", BoolToString(resource.isStarted()), BoolToString(g.isStarted()), BoolToString(world.isStarted()));
		world.markForDelete(this);
		return;
	}

	Sprite* tempSprite = resource.getSprite("border");
	if (tempSprite){
		log.writeLog("[Border] Successfully loaded Border sprite.");
		setSprite(tempSprite);
		setSpriteSlowdown(5);
		setTransparency();
		setSolidness(Solidness::HARD);
		setType(TYPE_BORDER);
		registerInterest(DF_STEP_EVENT);
		setVisible(true);

		int w = g.getHorizontal() / 2;
		int h = g.getVertical() / 2;
		Position pos(w, h);
		setPosition(pos);

		this->width = tempSprite->getWidth();
		this->height = tempSprite->getHeight();

		//Border is 15x15.
		//Layout is 13x13.

		GameState->PlayerState.minX = w - (tempSprite->getWidth() / 2);
		GameState->PlayerState.minX = h - (tempSprite->getHeight() / 2);
		GameState->PlayerState.maxX = w + (tempSprite->getWidth() / 2);
		GameState->PlayerState.maxY = h + (tempSprite->getHeight() / 2);
	}
	else {
		log.writeLog("[Border] Something is wrong with loading the sprite. Aborting.");
	}
	return;
}

int Border::eventHandler(Event* e){
	if (e->getType() == DF_STEP_EVENT){
		return 1;
	}
	return 0;
}

void Border::draw(){
	Object::draw();
}

int Border::getWidth(){
	return this->width;
}

int Border::getHeight(){
	return this->height;
}<|endoftext|>


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

#include <pcl/common/time_trigger.h>
#include <pcl/common/time.h>
#include <iostream>

//////////////////////////////////////////////////////////////////////////////////////////////
pcl::TimeTrigger::TimeTrigger (double interval, const callback_type& callback)
: callbacks_ ()
, interval_ (interval)
, quit_ (false)
, running_ (false)
, timer_thread_ ()
, condition_ ()
, condition_mutex_ ()
{
  timer_thread_ = boost::thread (boost::bind (&TimeTrigger::thread_function, this));
  registerCallback (callback);
}

//////////////////////////////////////////////////////////////////////////////////////////////
pcl::TimeTrigger::TimeTrigger (double interval)
: callbacks_ ()
, interval_ (interval)
, quit_ (false)
, running_ (false)
, timer_thread_ ()
, condition_ ()
, condition_mutex_ ()
{
  timer_thread_ = boost::thread (boost::bind (&TimeTrigger::thread_function, this));
}

//////////////////////////////////////////////////////////////////////////////////////////////
pcl::TimeTrigger::~TimeTrigger ()
{
  boost::unique_lock<boost::mutex> lock (condition_mutex_);
  quit_ = true;
  condition_.notify_all ();
  lock.unlock ();

  timer_thread_.join ();
}

//////////////////////////////////////////////////////////////////////////////////////////////
boost::signals2::connection
pcl::TimeTrigger::registerCallback (const callback_type& callback)
{
  boost::unique_lock<boost::mutex> lock (condition_mutex_);
  return (callbacks_.connect (callback));
}

//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::TimeTrigger::setInterval (double interval_seconds)
{
  boost::unique_lock<boost::mutex> lock (condition_mutex_);
  interval_ = interval_seconds;
  // notify, since we could switch from a large interval to a shorter one -> interrupt waiting for timeout!
  condition_.notify_all ();
}

//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::TimeTrigger::start ()
{
  boost::unique_lock<boost::mutex> lock (condition_mutex_);
  if (!running_)
  {
    running_ = true;
    condition_.notify_all ();
  }
}

//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::TimeTrigger::stop ()
{
  boost::unique_lock<boost::mutex> lock (condition_mutex_);
  if (running_)
  {
    running_ = false;
    condition_.notify_all ();
  }
}

//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::TimeTrigger::thread_function ()
{
  double time = 0;
  while (!quit_)
  {
    time = getTime ();
    boost::unique_lock<boost::mutex> lock (condition_mutex_);
    if (!running_)
      condition_.wait (lock); // wait util start is called or destructor is called
    else
    {
      callbacks_();
      double rest = interval_ + time - getTime ();
      if (rest > 0.0) // without a deadlock is possible, until notify() is called
        condition_.timed_wait (lock, boost::posix_time::microseconds (static_cast<int64_t> ((rest * 1000000))));
    }
  }
}

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

#include <pcl/common/time_trigger.h>
#include <pcl/common/time.h>
#include <iostream>

//////////////////////////////////////////////////////////////////////////////////////////////
pcl::TimeTrigger::TimeTrigger (double interval, const callback_type& callback)
: callbacks_ ()
, interval_ (interval)
, quit_ (false)
, running_ (false)
, timer_thread_ ()
, condition_ ()
, condition_mutex_ ()
{
  timer_thread_ = boost::thread (boost::bind (&TimeTrigger::thread_function, this));
  registerCallback (callback);
}

//////////////////////////////////////////////////////////////////////////////////////////////
pcl::TimeTrigger::TimeTrigger (double interval)
: callbacks_ ()
, interval_ (interval)
, quit_ (false)
, running_ (false)
, timer_thread_ ()
, condition_ ()
, condition_mutex_ ()
{
  timer_thread_ = boost::thread (boost::bind (&TimeTrigger::thread_function, this));
}

//////////////////////////////////////////////////////////////////////////////////////////////
pcl::TimeTrigger::~TimeTrigger ()
{
  boost::unique_lock<boost::mutex> lock (condition_mutex_);
  quit_ = true;
  condition_.notify_all ();
  lock.unlock ();

  timer_thread_.join ();
}

//////////////////////////////////////////////////////////////////////////////////////////////
boost::signals2::connection
pcl::TimeTrigger::registerCallback (const callback_type& callback)
{
  return (callbacks_.connect (callback));
}

//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::TimeTrigger::setInterval (double interval_seconds)
{
  boost::unique_lock<boost::mutex> lock (condition_mutex_);
  interval_ = interval_seconds;
  // notify, since we could switch from a large interval to a shorter one -> interrupt waiting for timeout!
  condition_.notify_all ();
}

//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::TimeTrigger::start ()
{
  boost::unique_lock<boost::mutex> lock (condition_mutex_);
  if (!running_)
  {
    running_ = true;
    condition_.notify_all ();
  }
}

//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::TimeTrigger::stop ()
{
  boost::unique_lock<boost::mutex> lock (condition_mutex_);
  if (running_)
  {
    running_ = false;
    condition_.notify_all ();
  }
}

//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::TimeTrigger::thread_function ()
{
  double time = 0;
  while (!quit_)
  {
    time = getTime ();
    boost::unique_lock<boost::mutex> lock (condition_mutex_);
    if (!running_)
      condition_.wait (lock); // wait util start is called or destructor is called
    else
    {
      callbacks_();
      double rest = interval_ + time - getTime ();
      if (rest > 0.0) // without a deadlock is possible, until notify() is called
        condition_.timed_wait (lock, boost::posix_time::microseconds (static_cast<int64_t> ((rest * 1000000))));
    }
  }
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: functiondescription.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 17:32:18 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_stoc.hxx"

#include "functiondescription.hxx"

#include "com/sun/star/container/NoSuchElementException.hpp"
#include "com/sun/star/container/XHierarchicalNameAccess.hpp"
#include "com/sun/star/reflection/XCompoundTypeDescription.hpp"
#include "com/sun/star/uno/Any.hxx"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/RuntimeException.hpp"
#include "com/sun/star/uno/Sequence.hxx"
#include "com/sun/star/uno/TypeClass.hpp"
#include "com/sun/star/uno/XInterface.hpp"
#include "cppuhelper/implbase1.hxx"
#include "osl/diagnose.h"
#include "osl/mutex.hxx"
#include "registry/reader.hxx"
#include "registry/version.h"
#include "rtl/ustring.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"

namespace css = com::sun::star;

using stoc::registry_tdprovider::FunctionDescription;

FunctionDescription::FunctionDescription(
    css::uno::Reference< css::container::XHierarchicalNameAccess > const &
        manager,
    com::sun::star::uno::Sequence< sal_Int8 > const & bytes,
    sal_uInt16 index):
    m_manager(manager), m_bytes(bytes), m_index(index), m_exceptionsInit(false)
{}

FunctionDescription::~FunctionDescription() {}

css::uno::Sequence<
    css::uno::Reference< css::reflection::XCompoundTypeDescription > >
FunctionDescription::getExceptions() const {
    {
        osl::MutexGuard guard(m_mutex);
        if (m_exceptionsInit) {
            return m_exceptions;
        }
    }
    typereg::Reader reader(getReader());
    sal_uInt16 n = reader.getMethodExceptionCount(m_index);
    css::uno::Sequence<
        css::uno::Reference< css::reflection::XCompoundTypeDescription > >
            exceptions(n);
    for (sal_uInt16 i = 0; i < n; ++i) {
        rtl::OUString name(
            reader.getMethodExceptionTypeName(m_index, i).replace('/', '.'));
        css::uno::Any any;
        try {
            any = m_manager->getByHierarchicalName(name);
        } catch (css::container::NoSuchElementException & e) {
            throw new css::uno::RuntimeException(
                (rtl::OUString(
                    RTL_CONSTASCII_USTRINGPARAM(
                        "com.sun.star.container.NoSuchElementException: "))
                 + e.Message),
                css::uno::Reference< css::uno::XInterface >()); //TODO
        }
        if (!(any >>= exceptions[i])
            || exceptions[i]->getTypeClass() != css::uno::TypeClass_EXCEPTION)
        {
            throw new css::uno::RuntimeException(
                (rtl::OUString(
                    RTL_CONSTASCII_USTRINGPARAM("not an exception type: "))
                 + name),
                css::uno::Reference< css::uno::XInterface >()); //TODO
        }
        OSL_ASSERT(exceptions[i].is());
    }
    osl::MutexGuard guard(m_mutex);
    if (!m_exceptionsInit) {
        m_exceptions = exceptions;
        m_exceptionsInit = true;
    }
    return m_exceptions;
}

typereg::Reader FunctionDescription::getReader() const {
    return typereg::Reader(
        m_bytes.getConstArray(), m_bytes.getLength(), false, TYPEREG_VERSION_1);
}
<commit_msg>INTEGRATION: CWS changefileheader (1.6.56); FILE MERGED 2008/03/31 07:26:11 rt 1.6.56.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: functiondescription.cxx,v $
 * $Revision: 1.7 $
 *
 * 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.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_stoc.hxx"

#include "functiondescription.hxx"

#include "com/sun/star/container/NoSuchElementException.hpp"
#include "com/sun/star/container/XHierarchicalNameAccess.hpp"
#include "com/sun/star/reflection/XCompoundTypeDescription.hpp"
#include "com/sun/star/uno/Any.hxx"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/RuntimeException.hpp"
#include "com/sun/star/uno/Sequence.hxx"
#include "com/sun/star/uno/TypeClass.hpp"
#include "com/sun/star/uno/XInterface.hpp"
#include "cppuhelper/implbase1.hxx"
#include "osl/diagnose.h"
#include "osl/mutex.hxx"
#include "registry/reader.hxx"
#include "registry/version.h"
#include "rtl/ustring.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"

namespace css = com::sun::star;

using stoc::registry_tdprovider::FunctionDescription;

FunctionDescription::FunctionDescription(
    css::uno::Reference< css::container::XHierarchicalNameAccess > const &
        manager,
    com::sun::star::uno::Sequence< sal_Int8 > const & bytes,
    sal_uInt16 index):
    m_manager(manager), m_bytes(bytes), m_index(index), m_exceptionsInit(false)
{}

FunctionDescription::~FunctionDescription() {}

css::uno::Sequence<
    css::uno::Reference< css::reflection::XCompoundTypeDescription > >
FunctionDescription::getExceptions() const {
    {
        osl::MutexGuard guard(m_mutex);
        if (m_exceptionsInit) {
            return m_exceptions;
        }
    }
    typereg::Reader reader(getReader());
    sal_uInt16 n = reader.getMethodExceptionCount(m_index);
    css::uno::Sequence<
        css::uno::Reference< css::reflection::XCompoundTypeDescription > >
            exceptions(n);
    for (sal_uInt16 i = 0; i < n; ++i) {
        rtl::OUString name(
            reader.getMethodExceptionTypeName(m_index, i).replace('/', '.'));
        css::uno::Any any;
        try {
            any = m_manager->getByHierarchicalName(name);
        } catch (css::container::NoSuchElementException & e) {
            throw new css::uno::RuntimeException(
                (rtl::OUString(
                    RTL_CONSTASCII_USTRINGPARAM(
                        "com.sun.star.container.NoSuchElementException: "))
                 + e.Message),
                css::uno::Reference< css::uno::XInterface >()); //TODO
        }
        if (!(any >>= exceptions[i])
            || exceptions[i]->getTypeClass() != css::uno::TypeClass_EXCEPTION)
        {
            throw new css::uno::RuntimeException(
                (rtl::OUString(
                    RTL_CONSTASCII_USTRINGPARAM("not an exception type: "))
                 + name),
                css::uno::Reference< css::uno::XInterface >()); //TODO
        }
        OSL_ASSERT(exceptions[i].is());
    }
    osl::MutexGuard guard(m_mutex);
    if (!m_exceptionsInit) {
        m_exceptions = exceptions;
        m_exceptionsInit = true;
    }
    return m_exceptions;
}

typereg::Reader FunctionDescription::getReader() const {
    return typereg::Reader(
        m_bytes.getConstArray(), m_bytes.getLength(), false, TYPEREG_VERSION_1);
}
<|endoftext|>


<commit_before>/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
 * Copyright (c) 2011-2015  Regents of the University of California.
 *
 * This file is part of ndnSIM. See AUTHORS for complete list of ndnSIM authors and
 * contributors.
 *
 * ndnSIM is free software: you can redistribute it and/or modify it under the terms
 * of the GNU General Public License as published by the Free Software Foundation,
 * either version 3 of the License, or (at your option) any later version.
 *
 * ndnSIM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 * PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * ndnSIM, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
 **/

// test-mobility.cpp

#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h"
#include "ns3/wifi-module.h"
#include "ns3/config-store-module.h"
#include "ns3/mobility-module.h"
#include "ns3/athstats-helper.h"
#include "ns3/internet-module.h"

#include "ns3/ndnSIM-module.h"

#include <iostream>

using namespace std;
namespace ns3 {

NS_LOG_COMPONENT_DEFINE("ndn.TestMobility");

/**
 * This scenario simulates a very simple network topology:
 *
 *
 *      +----------+     1Mbps      +--------+     1Mbps      +----------+
 *      | consumer | <------------> | router | <------------> | producer |
 *      +----------+         10ms   +--------+          10ms  +----------+
 *
 *
 * Consumer requests data from producer with frequency 10 interests per second
 * (interests contain constantly increasing sequence number).
 *
 * For every received interest, producer replies with a data packet, containing
 * 1024 bytes of virtual payload.
 *
 * To run scenario and see what is happening, use the following command:
 *
 *     NS_LOG=ndn.Consumer:ndn.Producer ./waf --run=test-example
 */

static void
SetPosition (Ptr<Node> node, Vector position)
{
  Ptr<MobilityModel> mobility = node->GetObject<MobilityModel> ();
  mobility->SetPosition (position);
}

static Vector
GetPosition (Ptr<Node> node)
{
  Ptr<MobilityModel> mobility = node->GetObject<MobilityModel> ();
  return mobility->GetPosition ();
}

static void
AdvancePosition (Ptr<Node> node)
{
  Vector pos = GetPosition (node);
  pos.x += 5.0;
  pos.y += 5.0;
  if (pos.x >= 210.0)
    {
      return;
    }
  SetPosition (node, pos);

  Simulator::Schedule (Seconds (1.0), &AdvancePosition, node);
}

int
main(int argc, char* argv[])
{
  // setting default parameters for Wifi
  // enable rts cts all the time.
  Config::SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold", StringValue ("0"));
  // disable fragmentation
  Config::SetDefault ("ns3::WifiRemoteStationManager::FragmentationThreshold", StringValue ("2200"));
  Config::SetDefault("ns3::WifiRemoteStationManager::NonUnicastMode",
                     StringValue("OfdmRate24Mbps"));

  // Read optional command-line parameters (e.g., enable visualizer with ./waf --run=<> --visualize
  CommandLine cmd;
  cmd.Parse(argc, argv);

Packet::EnablePrinting ();

  // Mobility config

  MobilityHelper mobility;

  Ptr<UniformRandomVariable> randomizer = CreateObject<UniformRandomVariable>();
  randomizer->SetAttribute("Min", DoubleValue(10));
  randomizer->SetAttribute("Max", DoubleValue(100));

  mobility.SetPositionAllocator ("ns3::RandomBoxPositionAllocator",
    "X", StringValue ("ns3::UniformRandomVariable[Min=0|Max=100]"),
    "Y", StringValue ("ns3::UniformRandomVariable[Min=0|Max=100]"));

/*
  mobility.SetPositionAllocator("ns3::RandomBoxPositionAllocator", "X", PointerValue(randomizer),
                                "Y", PointerValue(randomizer), "Z", PointerValue(randomizer));
*/
  mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");

  // Wifi config

WifiHelper wifi = WifiHelper::Default ();

  NodeContainer stas;
  NodeContainer ap;
  NetDeviceContainer staDevs;
  PacketSocketHelper packetSocket;

  stas.Create (3);
  ap.Create (2);

  // give packet socket powers to nodes.
  packetSocket.Install (stas);
  packetSocket.Install (ap);

  NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default ();
  YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();
  YansWifiChannelHelper wifiChannel = YansWifiChannelHelper::Default ();
  wifiPhy.SetChannel (wifiChannel.Create ());
  wifiPhy.Set("TxPowerStart", DoubleValue(5));
  wifiPhy.Set("TxPowerEnd", DoubleValue(5));
  Ssid ssid = Ssid ("wifi-default");
  wifi.SetRemoteStationManager ("ns3::ArfWifiManager");
  // setup stas.
  wifiMac.SetType ("ns3::StaWifiMac",
                   "Ssid", SsidValue (ssid),
                   "ActiveProbing", BooleanValue (false));
  staDevs = wifi.Install (wifiPhy, wifiMac, stas);
  // setup ap.
  wifiMac.SetType ("ns3::ApWifiMac",
                   "Ssid", SsidValue (ssid));
  wifi.Install (wifiPhy, wifiMac, ap);

  // Install mobility
  mobility.Install (stas);
  mobility.Install (ap);

  // Install NDN stack on all nodes
  ndn::StackHelper ndnHelper;
  ndnHelper.SetDefaultRoutes(true);
  ndnHelper.SetOldContentStore("ns3::ndn::cs::Splitcache",
							   "NormalPolicy", "ns3::ndn::cs::Lru",
							   "SpecialPolicy", "ns3::ndn::cs::Lru",
							   "TotalCacheSize", "500",
							   "Configure", "40");
  //                       Percentage Special^
  ndnHelper.Install(ap);
  ndnHelper.SetOldContentStore("ns3::ndn::cs::Nocache");
  ndnHelper.Install(stas);

  // Choosing forwarding strategy
  ndn::StrategyChoiceHelper::Install(stas, "/", "/localhost/nfd/strategy/best-route");
  ndn::StrategyChoiceHelper::Install(ap, "/", "/localhost/nfd/strategy/best-route");

  // Installing applications

  // Consumer (basic and special data)
  ndn::AppHelper consumerHelper("ns3::ndn::ConsumerZipfMandelbrot");
  consumerHelper.SetAttribute("NumberOfContents", StringValue("10")); // 10 different contents
  // Consumer will request /prefix/0, /prefix/1, ...
  consumerHelper.SetPrefix("data/basic");
  consumerHelper.SetAttribute("Frequency", StringValue("1")); // 1 interests a second
  consumerHelper.Install(stas.Get(0));

  consumerHelper.SetPrefix("data/special");
  consumerHelper.SetAttribute("Frequency", StringValue("2")); //  2 interests a second
  consumerHelper.Install(stas.Get(2));

  consumerHelper.SetPrefix("data/basic");
  consumerHelper.SetAttribute("Frequency", StringValue("1")); // 1 interests a second
  consumerHelper.Install(stas.Get(1));

  // Producer
  ndn::AppHelper producerHelper("ns3::ndn::Producer");
  // Producer will reply to all requests starting with /prefix
  producerHelper.SetPrefix("/data");
  producerHelper.SetAttribute("PayloadSize", StringValue("1024"));
  producerHelper.SetAttribute("Freshness", TimeValue(Seconds(-1.0))); // unlimited freshness
  producerHelper.Install(ap.Get(0)); // first node
  producerHelper.Install(ap.Get(1)); // second node

  Simulator::Schedule (Seconds (1.0), &AdvancePosition, stas.Get (0));

//  Simulator::Schedule (Seconds (1.0), &AdvancePosition, stas.Get (1));

//  Simulator::Schedule (Seconds (2.0), &AdvancePosition, stas.Get (2));

//  PacketSocketAddress socket;
//  socket.SetSingleDevice (staDevs.Get (0)->GetIfIndex ());
//  socket.SetPhysicalAddress (staDevs.Get (1)->GetAddress ());
//  socket.SetProtocol (1);

//  OnOffHelper onoff ("ns3::PacketSocketFactory", Address (socket));
//  onoff.SetConstantRate (DataRate ("500kb/s"));

//  ApplicationContainer apps = onoff.Install (stas.Get (0));
//  apps.Start (Seconds (0.5));
//  apps.Stop (Seconds (43.0));

//  Config::Connect ("/NodeList/*/DeviceList/*/Mac/MacTx", MakeCallback (&DevTxTrace));
//  Config::Connect ("/NodeList/*/DeviceList/*/Mac/MacRx", MakeCallback (&DevRxTrace));
//  Config::Connect ("/NodeList/*/DeviceList/*/Phy/State/RxOk", MakeCallback (&PhyRxOkTrace));
//  Config::Connect ("/NodeList/*/DeviceList/*/Phy/State/RxError", MakeCallback (&PhyRxErrorTrace));
//  Config::Connect ("/NodeList/*/DeviceList/*/Phy/State/Tx", MakeCallback (&PhyTxTrace));
//  Config::Connect ("/NodeList/*/DeviceList/*/Phy/State/State", MakeCallback (&PhyStateTrace));

  AthstatsHelper athstats;
  athstats.EnableAthstats ("athstats-sta", stas);
  athstats.EnableAthstats ("athstats-ap", ap);

  ndn::AppDelayTracer::InstallAll("app-delays-trace.txt");
  ndn::CsTracer::InstallAll("cs-trace.txt", Seconds(1));

  Simulator::Stop(Seconds(20.0));

  Simulator::Run();
  Simulator::Destroy();

  return 0;
}

} // namespace ns3

int
main(int argc, char* argv[])
{
  return ns3::main(argc, argv);
}
<commit_msg>mobility working<commit_after>/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
 * Copyright (c) 2011-2015  Regents of the University of California.
 *
 * This file is part of ndnSIM. See AUTHORS for complete list of ndnSIM authors and
 * contributors.
 *
 * ndnSIM is free software: you can redistribute it and/or modify it under the terms
 * of the GNU General Public License as published by the Free Software Foundation,
 * either version 3 of the License, or (at your option) any later version.
 *
 * ndnSIM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 * PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * ndnSIM, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
 **/

// test-mobility.cpp

#include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/applications-module.h"
#include "ns3/wifi-module.h"
#include "ns3/config-store-module.h"
#include "ns3/mobility-module.h"
#include "ns3/athstats-helper.h"
#include "ns3/internet-module.h"

#include "ns3/ndnSIM-module.h"

#include <iostream>

using namespace std;
namespace ns3 {

NS_LOG_COMPONENT_DEFINE("ndn.TestMobility");

/**
 * This scenario simulates a very simple network topology:
 *
 *
 *      +----------+     1Mbps      +--------+     1Mbps      +----------+
 *      | consumer | <------------> | router | <------------> | producer |
 *      +----------+         10ms   +--------+          10ms  +----------+
 *
 *
 * Consumer requests data from producer with frequency 10 interests per second
 * (interests contain constantly increasing sequence number).
 *
 * For every received interest, producer replies with a data packet, containing
 * 1024 bytes of virtual payload.
 *
 * To run scenario and see what is happening, use the following command:
 *
 *     NS_LOG=ndn.Consumer:ndn.Producer ./waf --run=test-example
 */

static void
SetPosition (Ptr<Node> node, Vector position)
{
  Ptr<MobilityModel> mobility = node->GetObject<MobilityModel> ();
  mobility->SetPosition (position);
}

static Vector
GetPosition (Ptr<Node> node)
{
  Ptr<MobilityModel> mobility = node->GetObject<MobilityModel> ();
  return mobility->GetPosition ();
}

static void
AdvancePosition (Ptr<Node> node)
{
  Vector pos = GetPosition (node);
  pos.x += 5.0;
  pos.y += 5.0;
  if (pos.x >= 210.0)
    {
      return;
    }
  SetPosition (node, pos);

  Simulator::Schedule (Seconds (1.0), &AdvancePosition, node);
}

int
main(int argc, char* argv[])
{
  // setting default parameters for Wifi
  // enable rts cts all the time.
  Config::SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold", StringValue ("0"));
  // disable fragmentation
  Config::SetDefault ("ns3::WifiRemoteStationManager::FragmentationThreshold", StringValue ("2200"));
  Config::SetDefault("ns3::WifiRemoteStationManager::NonUnicastMode",
                     StringValue("OfdmRate24Mbps"));

  // Read optional command-line parameters (e.g., enable visualizer with ./waf --run=<> --visualize
  CommandLine cmd;
  cmd.Parse(argc, argv);

Packet::EnablePrinting ();

  // Mobility config

  MobilityHelper mobility;

  Ptr<UniformRandomVariable> randomizer = CreateObject<UniformRandomVariable>();
  randomizer->SetAttribute("Min", DoubleValue(10));
  randomizer->SetAttribute("Max", DoubleValue(100));

  mobility.SetPositionAllocator ("ns3::RandomBoxPositionAllocator",
    "X", StringValue ("ns3::UniformRandomVariable[Min=0|Max=10]"),
    "Y", StringValue ("ns3::UniformRandomVariable[Min=0|Max=10]"));

/*
  mobility.SetPositionAllocator("ns3::RandomBoxPositionAllocator", "X", PointerValue(randomizer),
                                "Y", PointerValue(randomizer), "Z", PointerValue(randomizer));
*/
  mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");

  // Wifi config

WifiHelper wifi = WifiHelper::Default ();

  NodeContainer stas;
  NodeContainer ap;
  NetDeviceContainer staDevs;
  PacketSocketHelper packetSocket;

  stas.Create (3);
  ap.Create (2);

  // give packet socket powers to nodes.
  packetSocket.Install (stas);
  packetSocket.Install (ap);

  NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default ();
  YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();
  YansWifiChannelHelper wifiChannel = YansWifiChannelHelper::Default ();
  wifiPhy.SetChannel (wifiChannel.Create ());
  wifiPhy.Set("TxPowerStart", DoubleValue(5));
  wifiPhy.Set("TxPowerEnd", DoubleValue(5));
  Ssid ssid = Ssid ("wifi-default");
  wifi.SetRemoteStationManager ("ns3::ArfWifiManager");
  // setup stas.
  wifiMac.SetType ("ns3::StaWifiMac",
                   "Ssid", SsidValue (ssid),
                   "ActiveProbing", BooleanValue (false));
  staDevs = wifi.Install (wifiPhy, wifiMac, stas);
  // setup ap.
  wifiMac.SetType ("ns3::ApWifiMac",
                   "Ssid", SsidValue (ssid));
  wifi.Install (wifiPhy, wifiMac, ap);

  // Install mobility
  mobility.Install (stas);
//  mobility.Install (ap);
  mobility.Install (ap.Get(0));

  mobility.SetPositionAllocator ("ns3::RandomBoxPositionAllocator",
    "X", StringValue ("ns3::UniformRandomVariable[Min=100|Max=110]"),
    "Y", StringValue ("ns3::UniformRandomVariable[Min=100|Max=110]"));

  mobility.Install (ap.Get(1));

  // Install NDN stack on all nodes
  ndn::StackHelper ndnHelper;
  ndnHelper.SetDefaultRoutes(true);
  ndnHelper.SetOldContentStore("ns3::ndn::cs::Splitcache",
							   "NormalPolicy", "ns3::ndn::cs::Lru",
							   "SpecialPolicy", "ns3::ndn::cs::Lru",
							   "TotalCacheSize", "500",
							   "Configure", "40");
  //                       Percentage Special^
  ndnHelper.Install(ap);
  ndnHelper.SetOldContentStore("ns3::ndn::cs::Nocache");
  ndnHelper.Install(stas);

  // Choosing forwarding strategy
  ndn::StrategyChoiceHelper::Install(stas, "/", "/localhost/nfd/strategy/best-route");
  ndn::StrategyChoiceHelper::Install(ap, "/", "/localhost/nfd/strategy/best-route");

  // Installing applications

  // Consumer (basic and special data)
  ndn::AppHelper consumerHelper("ns3::ndn::ConsumerZipfMandelbrot");
  consumerHelper.SetAttribute("NumberOfContents", StringValue("10")); // 10 different contents
  // Consumer will request /prefix/0, /prefix/1, ...
  consumerHelper.SetPrefix("data/basic");
  consumerHelper.SetAttribute("Frequency", StringValue("1")); // 1 interests a second
  consumerHelper.Install(stas.Get(0));

  consumerHelper.SetPrefix("data/special");
  consumerHelper.SetAttribute("Frequency", StringValue("2")); //  2 interests a second
  consumerHelper.Install(stas.Get(2));

  consumerHelper.SetPrefix("data/basic");
  consumerHelper.SetAttribute("Frequency", StringValue("1")); // 1 interests a second
  consumerHelper.Install(stas.Get(1));

  // Producer
  ndn::AppHelper producerHelper("ns3::ndn::Producer");
  // Producer will reply to all requests starting with /prefix
  producerHelper.SetPrefix("/data");
  producerHelper.SetAttribute("PayloadSize", StringValue("1024"));
  producerHelper.SetAttribute("Freshness", TimeValue(Seconds(-1.0))); // unlimited freshness
  producerHelper.Install(ap.Get(0)); // first node
  producerHelper.Install(ap.Get(1)); // second node

  Simulator::Schedule (Seconds (1.0), &AdvancePosition, stas.Get (0));

//  Simulator::Schedule (Seconds (1.0), &AdvancePosition, stas.Get (1));

//  Simulator::Schedule (Seconds (2.0), &AdvancePosition, stas.Get (2));

//  PacketSocketAddress socket;
//  socket.SetSingleDevice (staDevs.Get (0)->GetIfIndex ());
//  socket.SetPhysicalAddress (staDevs.Get (1)->GetAddress ());
//  socket.SetProtocol (1);

//  OnOffHelper onoff ("ns3::PacketSocketFactory", Address (socket));
//  onoff.SetConstantRate (DataRate ("500kb/s"));

//  ApplicationContainer apps = onoff.Install (stas.Get (0));
//  apps.Start (Seconds (0.5));
//  apps.Stop (Seconds (43.0));

//  Config::Connect ("/NodeList/*/DeviceList/*/Mac/MacTx", MakeCallback (&DevTxTrace));
//  Config::Connect ("/NodeList/*/DeviceList/*/Mac/MacRx", MakeCallback (&DevRxTrace));
//  Config::Connect ("/NodeList/*/DeviceList/*/Phy/State/RxOk", MakeCallback (&PhyRxOkTrace));
//  Config::Connect ("/NodeList/*/DeviceList/*/Phy/State/RxError", MakeCallback (&PhyRxErrorTrace));
//  Config::Connect ("/NodeList/*/DeviceList/*/Phy/State/Tx", MakeCallback (&PhyTxTrace));
//  Config::Connect ("/NodeList/*/DeviceList/*/Phy/State/State", MakeCallback (&PhyStateTrace));

  AthstatsHelper athstats;
  athstats.EnableAthstats ("athstats-sta", stas);
  athstats.EnableAthstats ("athstats-ap", ap);

  ndn::AppDelayTracer::InstallAll("app-delays-trace.txt");
  ndn::CsTracer::InstallAll("cs-trace.txt", Seconds(1));

  Simulator::Stop(Seconds(20.0));

  Simulator::Run();
  Simulator::Destroy();

  return 0;
}

} // namespace ns3

int
main(int argc, char* argv[])
{
  return ns3::main(argc, argv);
}
<|endoftext|>