<commit_before>//! \file
/*
**  Copyright (C) - Triton
**
**  This program is under the terms of the BSD License.
*/

#include <vector>
#include <boost/multiprecision/cpp_int/import_export.hpp>
#include <triton/pythonBindings.hpp>
#include <triton/pythonUtils.hpp>
#include <triton/exceptions.hpp>
#include <triton/tritonTypes.hpp>

namespace triton {
  namespace bindings {
    namespace python {

      bool PyLong_AsBool(PyObject* obj) {
        return (PyObject_IsTrue(obj) != 0);
      }

      triton::__uint PyLong_AsUint(PyObject* vv) {
        PyLongObject* v;
        triton::__uint x, prev;
        Py_ssize_t i;

        if (vv == NULL || !PyLong_Check(vv)) {
          if (vv != NULL && PyInt_Check(vv)) {
              triton::__uint val = PyInt_AsLong(vv);
              return val;
          }
          throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUint(): Bad internal call.");
        }

        v = reinterpret_cast<PyLongObject*>(vv);
        i = Py_SIZE(v);
        x = 0;
        if (i < 0)
          throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUint(): Cannot convert negative value to unsigned long.");

        while (--i >= 0) {
            prev = x;
            x = (x << PyLong_SHIFT) | v->ob_digit[i];
            if ((x >> PyLong_SHIFT) != prev)
                throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUint(): long int too large to convert.");
        }

        return x;
      }

      triton::usize PyLong_AsUsize(PyObject* vv) {
        PyLongObject* v;
        triton::usize x, prev;
        Py_ssize_t i;

        if (vv == NULL || !PyLong_Check(vv)) {
          if (vv != NULL && PyInt_Check(vv)) {
              triton::usize val = PyInt_AsLong(vv);
              return val;
          }
          throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUsize(): Bad internal call.");
        }

        v = reinterpret_cast<PyLongObject*>(vv);
        i = Py_SIZE(v);
        x = 0;
        if (i < 0)
          throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUsize(): Cannot convert negative value to unsigned long.");

        while (--i >= 0) {
            prev = x;
            x = (x << PyLong_SHIFT) | v->ob_digit[i];
            if ((x >> PyLong_SHIFT) != prev)
                throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUsize(): long int too large to convert.");
        }

        return x;
      }

      triton::uint32 PyLong_AsUint32(PyObject* vv) {
        PyLongObject* v;
        triton::uint32 x, prev;
        Py_ssize_t i;

        if (vv == NULL || !PyLong_Check(vv)) {
          if (vv != NULL && PyInt_Check(vv)) {
              triton::uint32 val = PyInt_AsLong(vv);
              return val;
          }
          throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUint32(): Bad internal call.");
        }

        v = reinterpret_cast<PyLongObject*>(vv);
        i = Py_SIZE(v);
        x = 0;
        if (i < 0)
          throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUint32(): Cannot convert negative value to unsigned long.");

        while (--i >= 0) {
            prev = x;
            x = (x << PyLong_SHIFT) | v->ob_digit[i];
            if ((x >> PyLong_SHIFT) != prev)
                throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUint32(): long int too large to convert.");
        }

        return x;
      }

      triton::uint64 PyLong_AsUint64(PyObject* vv) {
        PyLongObject* v;
        triton::uint64 x, prev;
        Py_ssize_t i;

        if (vv == NULL || !PyLong_Check(vv)) {
          if (vv != NULL && PyInt_Check(vv)) {
              triton::uint64 val = PyInt_AsLong(vv);
              return val;
          }
          throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUint64(): Bad internal call.");
        }

        v = reinterpret_cast<PyLongObject*>(vv);
        i = Py_SIZE(v);
        x = 0;
        if (i < 0)
          throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUint64(): Cannot convert negative value to unsigned long.");

        while (--i >= 0) {
            prev = x;
            x = (x << PyLong_SHIFT) | v->ob_digit[i];
            if ((x >> PyLong_SHIFT) != prev)
                throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUint64(): long int too large to convert.");
        }

        return x;
      }

      triton::uint128 PyLong_AsUint128(PyObject* vv) {
        PyLongObject* v;
        boost::multiprecision::checked_int128_t tmp;
        Py_ssize_t i;

        if (vv == NULL || !PyLong_Check(vv)) {
          if (vv != NULL && PyInt_Check(vv))
            return PyInt_AsLong(vv);
          throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUint256(): bad internal call.");
        }

        v = reinterpret_cast<PyLongObject*>(vv);
        i = Py_SIZE(v);

        const bool neg = (i <= 0);
        if (neg) {
          if (i == 0)
            return 0;
          i = -i;
        }

        try {
          boost::multiprecision::detail::import_bits(tmp, v->ob_digit, v->ob_digit + i, PyLong_SHIFT, false);
        }
        catch (std::overflow_error&) {
          throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUint256(): long integer too large to convert.");
        }

        return static_cast<triton::uint128>(neg ? -tmp : tmp);
      }

      triton::uint256 PyLong_AsUint256(PyObject* vv) {
        PyLongObject* v;
        boost::multiprecision::checked_int256_t tmp;
        Py_ssize_t i;

        if (vv == NULL || !PyLong_Check(vv)) {
          if (vv != NULL && PyInt_Check(vv))
              return PyInt_AsLong(vv);
          throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUint256(): bad internal call.");
        }

        v = reinterpret_cast<PyLongObject*>(vv);
        i = Py_SIZE(v);

        const bool neg = (i <= 0);
        if (neg) {
          if (i == 0)
            return 0;
          i = -i;
        }

        try {
          boost::multiprecision::detail::import_bits(tmp, v->ob_digit, v->ob_digit + i, PyLong_SHIFT, false);
        }
        catch (std::overflow_error&) {
          throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUint256(): long integer too large to convert.");
        }

        return static_cast<triton::uint256>(neg ? -tmp : tmp);
      }

      triton::uint512 PyLong_AsUint512(PyObject* vv) {
        PyLongObject* v;
        boost::multiprecision::checked_int512_t tmp;
        Py_ssize_t i;

        if (vv == NULL || !PyLong_Check(vv)) {
          if (vv != NULL && PyInt_Check(vv))
            return PyInt_AsLong(vv);
          throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUint256(): bad internal call.");
        }

        v = reinterpret_cast<PyLongObject*>(vv);
        i = Py_SIZE(v);

        const bool neg = (i <= 0);
        if (neg) {
          if (i == 0)
            return 0;
          i = -i;
        }

        try {
          boost::multiprecision::detail::import_bits(tmp, v->ob_digit, v->ob_digit + i, PyLong_SHIFT, false);
        }
        catch (std::overflow_error&) {
          throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUint256(): long integer too large to convert.");
        }

        return static_cast<triton::uint512>(neg ? -tmp : tmp);
      }

      /* Returns a PyObject from a {32,64}-bits integer */
      PyObject* PyLong_FromUint(triton::__uint value) {
        // it is mandatory to let Python impl deal with small numbers (static objects)
        if (value <= std::numeric_limits<unsigned long>::max())
          return PyLong_FromUnsignedLong(static_cast<unsigned long>(value));

        PyLongObject* v;
        triton::__uint t;
        int ndigits = 0;

        /* Count the number of Python digits. */
        t = value;
        while (t) {
          ++ndigits;
          t >>= PyLong_SHIFT;
        }

        v = _PyLong_New(ndigits);
        digit* p = v->ob_digit;
        Py_SIZE(v) = ndigits;
        while (value) {
          *p++ = static_cast<digit>(value & PyLong_MASK);
          value >>= PyLong_SHIFT;
        }

        return (PyObject*)v;
      }

      /* Returns a PyObject from a {32,64}-bits integer */
      PyObject* PyLong_FromUsize(triton::usize value) {
        // it is mandatory to let Python impl deal with small numbers (static objects)
        if (value <= std::numeric_limits<unsigned long>::max())
          return PyLong_FromUnsignedLong(static_cast<unsigned long>(value));

        PyLongObject* v;
        triton::usize t;
        int ndigits = 0;

        /* Count the number of Python digits. */
        t = value;
        while (t) {
          ++ndigits;
          t >>= PyLong_SHIFT;
        }

        v = _PyLong_New(ndigits);
        digit* p = v->ob_digit;
        Py_SIZE(v) = ndigits;
        while (value) {
          *p++ = static_cast<digit>(value & PyLong_MASK);
          value >>= PyLong_SHIFT;
        }

        return (PyObject*)v;
      }

      /* Returns a PyObject from a 32-bits integer */
      PyObject* PyLong_FromUint32(triton::uint32 value) {
        // it is mandatory to let Python impl deal with small numbers (static objects)
        if (value <= std::numeric_limits<unsigned long>::max())
          return PyLong_FromUnsignedLong(static_cast<unsigned long>(value));

        PyLongObject* v;
        triton::uint32 t;
        int ndigits = 0;

        /* Count the number of Python digits. */
        t = value;
        while (t) {
          ++ndigits;
          t >>= PyLong_SHIFT;
        }

        v = _PyLong_New(ndigits);
        digit* p = v->ob_digit;
        Py_SIZE(v) = ndigits;
        while (value) {
          *p++ = static_cast<digit>(value & PyLong_MASK);
          value >>= PyLong_SHIFT;
        }

        return (PyObject*)v;
      }

      /* Returns a PyObject from a 64-bits integer */
      PyObject* PyLong_FromUint64(triton::uint64 value) {
        // it is mandatory to let Python impl deal with small numbers (static objects)
        if (value <= std::numeric_limits<unsigned long>::max())
          return PyLong_FromUnsignedLong(static_cast<unsigned long>(value));

        PyLongObject* v;
        triton::uint64 t;
        int ndigits = 0;

        /* Count the number of Python digits. */
        t = value;
        while (t) {
          ++ndigits;
          t >>= PyLong_SHIFT;
        }

        v = _PyLong_New(ndigits);
        digit* p = v->ob_digit;
        Py_SIZE(v) = ndigits;
        while (value) {
          *p++ = static_cast<digit>(value & PyLong_MASK);
          value >>= PyLong_SHIFT;
        }

        return (PyObject*)v;
      }

      /* Returns a PyObject from a 128-bits integer */
      PyObject* PyLong_FromUint128(triton::uint128 value) {
        // it is mandatory to let Python impl deal with small numbers (static objects)
        if (value <= std::numeric_limits<unsigned long>::max())
          return PyLong_FromUnsignedLong(static_cast<unsigned long>(value));

        PyLongObject* v;
        std::vector<digit> digits;

        boost::multiprecision::detail::export_bits(value, std::back_inserter(digits), PyLong_SHIFT, false);
        v = _PyLong_New(digits.size());
        std::copy(digits.begin(), digits.end(), v->ob_digit);

        return (PyObject*)v;
      }

      /* Returns a PyObject from a 256-bits integer */
      PyObject* PyLong_FromUint256(triton::uint256 value) {
        // it is mandatory to let Python impl deal with small numbers (static objects)
        if (value <= std::numeric_limits<unsigned long>::max())
          return PyLong_FromUnsignedLong(static_cast<unsigned long>(value));

        PyLongObject* v;
        std::vector<digit> digits;

        boost::multiprecision::detail::export_bits(value, std::back_inserter(digits), PyLong_SHIFT, false);
        v = _PyLong_New(digits.size());
        std::copy(digits.begin(), digits.end(), v->ob_digit);

        return (PyObject*)v;
      }

      /* Returns a PyObject from a 512-bits integer */
      PyObject* PyLong_FromUint512(triton::uint512 value) {
        // it is mandatory to let Python impl deal with small numbers (static objects)
        if (value <= std::numeric_limits<unsigned long>::max())
          return PyLong_FromUnsignedLong(static_cast<unsigned long>(value));

        PyLongObject* v;
        std::vector<digit> digits;

        boost::multiprecision::detail::export_bits(value, std::back_inserter(digits), PyLong_SHIFT, false);
        v = _PyLong_New(digits.size());
        std::copy(digits.begin(), digits.end(), v->ob_digit);

        return (PyObject*)v;
      }

    }; /* python namespace */
  }; /* bindings namespace */
}; /* triton namespace */
<commit_msg>fix namespace<commit_after>//! \file
/*
**  Copyright (C) - Triton
**
**  This program is under the terms of the BSD License.
*/

#include <vector>
#include <boost/multiprecision/cpp_int.hpp>
#include <triton/pythonBindings.hpp>
#include <triton/pythonUtils.hpp>
#include <triton/exceptions.hpp>
#include <triton/tritonTypes.hpp>

namespace triton {
  namespace bindings {
    namespace python {

      bool PyLong_AsBool(PyObject* obj) {
        return (PyObject_IsTrue(obj) != 0);
      }

      triton::__uint PyLong_AsUint(PyObject* vv) {
        PyLongObject* v;
        triton::__uint x, prev;
        Py_ssize_t i;

        if (vv == NULL || !PyLong_Check(vv)) {
          if (vv != NULL && PyInt_Check(vv)) {
              triton::__uint val = PyInt_AsLong(vv);
              return val;
          }
          throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUint(): Bad internal call.");
        }

        v = reinterpret_cast<PyLongObject*>(vv);
        i = Py_SIZE(v);
        x = 0;
        if (i < 0)
          throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUint(): Cannot convert negative value to unsigned long.");

        while (--i >= 0) {
            prev = x;
            x = (x << PyLong_SHIFT) | v->ob_digit[i];
            if ((x >> PyLong_SHIFT) != prev)
                throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUint(): long int too large to convert.");
        }

        return x;
      }

      triton::usize PyLong_AsUsize(PyObject* vv) {
        PyLongObject* v;
        triton::usize x, prev;
        Py_ssize_t i;

        if (vv == NULL || !PyLong_Check(vv)) {
          if (vv != NULL && PyInt_Check(vv)) {
              triton::usize val = PyInt_AsLong(vv);
              return val;
          }
          throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUsize(): Bad internal call.");
        }

        v = reinterpret_cast<PyLongObject*>(vv);
        i = Py_SIZE(v);
        x = 0;
        if (i < 0)
          throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUsize(): Cannot convert negative value to unsigned long.");

        while (--i >= 0) {
            prev = x;
            x = (x << PyLong_SHIFT) | v->ob_digit[i];
            if ((x >> PyLong_SHIFT) != prev)
                throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUsize(): long int too large to convert.");
        }

        return x;
      }

      triton::uint32 PyLong_AsUint32(PyObject* vv) {
        PyLongObject* v;
        triton::uint32 x, prev;
        Py_ssize_t i;

        if (vv == NULL || !PyLong_Check(vv)) {
          if (vv != NULL && PyInt_Check(vv)) {
              triton::uint32 val = PyInt_AsLong(vv);
              return val;
          }
          throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUint32(): Bad internal call.");
        }

        v = reinterpret_cast<PyLongObject*>(vv);
        i = Py_SIZE(v);
        x = 0;
        if (i < 0)
          throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUint32(): Cannot convert negative value to unsigned long.");

        while (--i >= 0) {
            prev = x;
            x = (x << PyLong_SHIFT) | v->ob_digit[i];
            if ((x >> PyLong_SHIFT) != prev)
                throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUint32(): long int too large to convert.");
        }

        return x;
      }

      triton::uint64 PyLong_AsUint64(PyObject* vv) {
        PyLongObject* v;
        triton::uint64 x, prev;
        Py_ssize_t i;

        if (vv == NULL || !PyLong_Check(vv)) {
          if (vv != NULL && PyInt_Check(vv)) {
              triton::uint64 val = PyInt_AsLong(vv);
              return val;
          }
          throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUint64(): Bad internal call.");
        }

        v = reinterpret_cast<PyLongObject*>(vv);
        i = Py_SIZE(v);
        x = 0;
        if (i < 0)
          throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUint64(): Cannot convert negative value to unsigned long.");

        while (--i >= 0) {
            prev = x;
            x = (x << PyLong_SHIFT) | v->ob_digit[i];
            if ((x >> PyLong_SHIFT) != prev)
                throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUint64(): long int too large to convert.");
        }

        return x;
      }

      triton::uint128 PyLong_AsUint128(PyObject* vv) {
        PyLongObject* v;
        boost::multiprecision::checked_int128_t tmp;
        Py_ssize_t i;

        if (vv == NULL || !PyLong_Check(vv)) {
          if (vv != NULL && PyInt_Check(vv))
            return PyInt_AsLong(vv);
          throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUint256(): bad internal call.");
        }

        v = reinterpret_cast<PyLongObject*>(vv);
        i = Py_SIZE(v);

        const bool neg = (i <= 0);
        if (neg) {
          if (i == 0)
            return 0;
          i = -i;
        }

        try {
          boost::multiprecision::import_bits(tmp, v->ob_digit, v->ob_digit + i, PyLong_SHIFT, false);
        }
        catch (std::overflow_error&) {
          throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUint256(): long integer too large to convert.");
        }

        return static_cast<triton::uint128>(neg ? -tmp : tmp);
      }

      triton::uint256 PyLong_AsUint256(PyObject* vv) {
        PyLongObject* v;
        boost::multiprecision::checked_int256_t tmp;
        Py_ssize_t i;

        if (vv == NULL || !PyLong_Check(vv)) {
          if (vv != NULL && PyInt_Check(vv))
              return PyInt_AsLong(vv);
          throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUint256(): bad internal call.");
        }

        v = reinterpret_cast<PyLongObject*>(vv);
        i = Py_SIZE(v);

        const bool neg = (i <= 0);
        if (neg) {
          if (i == 0)
            return 0;
          i = -i;
        }

        try {
          boost::multiprecision::import_bits(tmp, v->ob_digit, v->ob_digit + i, PyLong_SHIFT, false);
        }
        catch (std::overflow_error&) {
          throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUint256(): long integer too large to convert.");
        }

        return static_cast<triton::uint256>(neg ? -tmp : tmp);
      }

      triton::uint512 PyLong_AsUint512(PyObject* vv) {
        PyLongObject* v;
        boost::multiprecision::checked_int512_t tmp;
        Py_ssize_t i;

        if (vv == NULL || !PyLong_Check(vv)) {
          if (vv != NULL && PyInt_Check(vv))
            return PyInt_AsLong(vv);
          throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUint256(): bad internal call.");
        }

        v = reinterpret_cast<PyLongObject*>(vv);
        i = Py_SIZE(v);

        const bool neg = (i <= 0);
        if (neg) {
          if (i == 0)
            return 0;
          i = -i;
        }

        try {
          boost::multiprecision::import_bits(tmp, v->ob_digit, v->ob_digit + i, PyLong_SHIFT, false);
        }
        catch (std::overflow_error&) {
          throw triton::exceptions::Bindings("triton::bindings::python::PyLong_AsUint256(): long integer too large to convert.");
        }

        return static_cast<triton::uint512>(neg ? -tmp : tmp);
      }

      /* Returns a PyObject from a {32,64}-bits integer */
      PyObject* PyLong_FromUint(triton::__uint value) {
        // it is mandatory to let Python impl deal with small numbers (static objects)
        if (value <= std::numeric_limits<unsigned long>::max())
          return PyLong_FromUnsignedLong(static_cast<unsigned long>(value));

        PyLongObject* v;
        triton::__uint t;
        int ndigits = 0;

        /* Count the number of Python digits. */
        t = value;
        while (t) {
          ++ndigits;
          t >>= PyLong_SHIFT;
        }

        v = _PyLong_New(ndigits);
        digit* p = v->ob_digit;
        Py_SIZE(v) = ndigits;
        while (value) {
          *p++ = static_cast<digit>(value & PyLong_MASK);
          value >>= PyLong_SHIFT;
        }

        return (PyObject*)v;
      }

      /* Returns a PyObject from a {32,64}-bits integer */
      PyObject* PyLong_FromUsize(triton::usize value) {
        // it is mandatory to let Python impl deal with small numbers (static objects)
        if (value <= std::numeric_limits<unsigned long>::max())
          return PyLong_FromUnsignedLong(static_cast<unsigned long>(value));

        PyLongObject* v;
        triton::usize t;
        int ndigits = 0;

        /* Count the number of Python digits. */
        t = value;
        while (t) {
          ++ndigits;
          t >>= PyLong_SHIFT;
        }

        v = _PyLong_New(ndigits);
        digit* p = v->ob_digit;
        Py_SIZE(v) = ndigits;
        while (value) {
          *p++ = static_cast<digit>(value & PyLong_MASK);
          value >>= PyLong_SHIFT;
        }

        return (PyObject*)v;
      }

      /* Returns a PyObject from a 32-bits integer */
      PyObject* PyLong_FromUint32(triton::uint32 value) {
        // it is mandatory to let Python impl deal with small numbers (static objects)
        if (value <= std::numeric_limits<unsigned long>::max())
          return PyLong_FromUnsignedLong(static_cast<unsigned long>(value));

        PyLongObject* v;
        triton::uint32 t;
        int ndigits = 0;

        /* Count the number of Python digits. */
        t = value;
        while (t) {
          ++ndigits;
          t >>= PyLong_SHIFT;
        }

        v = _PyLong_New(ndigits);
        digit* p = v->ob_digit;
        Py_SIZE(v) = ndigits;
        while (value) {
          *p++ = static_cast<digit>(value & PyLong_MASK);
          value >>= PyLong_SHIFT;
        }

        return (PyObject*)v;
      }

      /* Returns a PyObject from a 64-bits integer */
      PyObject* PyLong_FromUint64(triton::uint64 value) {
        // it is mandatory to let Python impl deal with small numbers (static objects)
        if (value <= std::numeric_limits<unsigned long>::max())
          return PyLong_FromUnsignedLong(static_cast<unsigned long>(value));

        PyLongObject* v;
        triton::uint64 t;
        int ndigits = 0;

        /* Count the number of Python digits. */
        t = value;
        while (t) {
          ++ndigits;
          t >>= PyLong_SHIFT;
        }

        v = _PyLong_New(ndigits);
        digit* p = v->ob_digit;
        Py_SIZE(v) = ndigits;
        while (value) {
          *p++ = static_cast<digit>(value & PyLong_MASK);
          value >>= PyLong_SHIFT;
        }

        return (PyObject*)v;
      }

      /* Returns a PyObject from a 128-bits integer */
      PyObject* PyLong_FromUint128(triton::uint128 value) {
        // it is mandatory to let Python impl deal with small numbers (static objects)
        if (value <= std::numeric_limits<unsigned long>::max())
          return PyLong_FromUnsignedLong(static_cast<unsigned long>(value));

        PyLongObject* v;
        std::vector<digit> digits;

        boost::multiprecision::export_bits(value, std::back_inserter(digits), PyLong_SHIFT, false);
        v = _PyLong_New(digits.size());
        std::copy(digits.begin(), digits.end(), v->ob_digit);

        return (PyObject*)v;
      }

      /* Returns a PyObject from a 256-bits integer */
      PyObject* PyLong_FromUint256(triton::uint256 value) {
        // it is mandatory to let Python impl deal with small numbers (static objects)
        if (value <= std::numeric_limits<unsigned long>::max())
          return PyLong_FromUnsignedLong(static_cast<unsigned long>(value));

        PyLongObject* v;
        std::vector<digit> digits;

        boost::multiprecision::export_bits(value, std::back_inserter(digits), PyLong_SHIFT, false);
        v = _PyLong_New(digits.size());
        std::copy(digits.begin(), digits.end(), v->ob_digit);

        return (PyObject*)v;
      }

      /* Returns a PyObject from a 512-bits integer */
      PyObject* PyLong_FromUint512(triton::uint512 value) {
        // it is mandatory to let Python impl deal with small numbers (static objects)
        if (value <= std::numeric_limits<unsigned long>::max())
          return PyLong_FromUnsignedLong(static_cast<unsigned long>(value));

        PyLongObject* v;
        std::vector<digit> digits;

        boost::multiprecision::export_bits(value, std::back_inserter(digits), PyLong_SHIFT, false);
        v = _PyLong_New(digits.size());
        std::copy(digits.begin(), digits.end(), v->ob_digit);

        return (PyObject*)v;
      }

    }; /* python namespace */
  }; /* bindings namespace */
}; /* triton namespace */
<|endoftext|>


<commit_before>/*******************************************************
      Lightwave Scene Loader for OSG

  Copyright (C) 2004 Marco Jez <marco.jez@poste.it>
  OpenSceneGraph is (C) 2004 Robert Osfield
********************************************************/

#include "SceneLoader.h"

#include <osg/Notify>
#include <osg/PositionAttitudeTransform>
#include <osg/AnimationPath>

#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>

#include <fstream>
#include <sstream>

using namespace lwosg;

namespace
{

    int str_to_int(const std::string &s)
    {
        std::istringstream iss(s);
        int n;
        iss >> n;
        return n;
    }

    int hex_to_int(const std::string &s)
    {
        std::istringstream iss(s);
        int n;
        iss >> std::hex >> n;
        return n;
    }

    osg::Quat rotate_ypr(const osg::Vec3 &ypr, const osg::Vec3 pivot_rot = osg::Vec3(0, 0, 0))
    {
        osg::Quat Q1(ypr.z(), osg::Vec3(0, -1, 0));
        osg::Quat Q2(ypr.y(), osg::Vec3(-1, 0, 0));
        osg::Quat Q3(ypr.x(), osg::Vec3(0, 0, -1));
        osg::Quat Q4(pivot_rot.z(), osg::Vec3(0, -1, 0));
        osg::Quat Q5(pivot_rot.y(), osg::Vec3(-1, 0, 0));
        osg::Quat Q6(pivot_rot.x(), osg::Vec3(0, 0, -1));
        return Q1 * Q2 * Q3 * Q4 * Q5 * Q6;
    }

    void trim(std::string& str)
    {
        // trim any trailing control characters.
        //std::cout<<"trim string "<<str<<std::endl;
        while (!str.empty() && str[str.size()-1]<32)
        {
            // removing control character
            //std::cout<<"    removing control character "<<(int)str[str.size()-1]<<std::endl;
            str.erase(str.size()-1);
        }

    }

}

SceneLoader::SceneLoader()
:    capture_obj_motion_(false),
    capture_cam_motion_(false)
{
}

SceneLoader::SceneLoader(const Options &options)
:    capture_obj_motion_(false),
    capture_cam_motion_(false),
    options_(options)
{
}

osg::Group *SceneLoader::load(const std::string &filename, bool search)
{
    std::string fname;

    if (search) {
        fname = osgDB::findDataFile(filename);
        if (fname.empty()) return 0;
    } else {
        fname = filename;
    }

    std::ifstream ifs(fname.c_str());
    if (!ifs.is_open()) return 0;

    clear();

    std::string identifier;
    while (ifs >> identifier) {
        if (identifier == "{") {
            ifs >> identifier;
            std::ws(ifs);
            std::vector<std::string> data;
            std::string data_line;
            while (std::getline(ifs, data_line)) {
                trim(data_line);
                if (data_line == "}") {
                    std::ws(ifs);
                    break;
                }
                data.push_back(data_line);
                std::ws(ifs);
            }
            if (!data.empty()) {
                if (!parse_block(identifier, data)) {
                    return 0;
                }
            }
        } else {
            std::string data;
            std::getline(ifs, data);
            trim(data);
            std::istringstream iss(data);
            std::ws(iss);
            std::getline(iss, data);
            trim(data);
            if (!parse_block(identifier, data)) {
                return 0;
            }
        }
    }

    // build camera animations
    for (Scene_camera_list::iterator ci=scene_cameras_.begin(); ci!=scene_cameras_.end(); ++ci) {
        if (!ci->motion.keys.empty()) {
            osg::ref_ptr<osg::AnimationPath> ap = new osg::AnimationPath;
            for (Motion_envelope::Key_map::const_iterator j=ci->motion.keys.begin(); j!=ci->motion.keys.end(); ++j) {
                osg::Vec3 pos(options_.csf->fix_point(j->second.position));
                //const osg::Vec3 &ypr = j->second.ypr;
                osg::AnimationPath::ControlPoint cp(pos, osg::Quat(osg::PI_2, osg::Vec3(1, 0, 0)) * rotate_ypr(j->second.ypr), j->second.scale);
                ap->insert(j->first, cp);
            }
            camera_animations_.push_back(ap.get());
        }
    }

    // build objects and object animations
    typedef std::map<int, osg::ref_ptr<osg::PositionAttitudeTransform> > PAT_map;
    PAT_map pats;
    int j = 0;
    for (Scene_object_list::iterator i=scene_objects_.begin(); i!=scene_objects_.end(); ++i, ++j) {
        osg::ref_ptr<osg::PositionAttitudeTransform> pat = pats[j];
        if (!pat.valid()) {
            pat = new osg::PositionAttitudeTransform;
            pats[j] = pat;
        }

        pat->addChild(i->layer_node.get());
        pat->setPivotPoint(options_.csf->fix_point(i->pivot));

        // still
        if (!i->motion.keys.empty()) {
            pat->setPosition(options_.csf->fix_point(i->motion.keys.begin()->second.position));
            pat->setAttitude(rotate_ypr(i->motion.keys.begin()->second.ypr, i->pivot_rot));
        }

        // animation
        if (i->motion.keys.size() > 1) {
            osg::ref_ptr<osg::AnimationPath> ap = new osg::AnimationPath;
            for (Motion_envelope::Key_map::const_iterator j=i->motion.keys.begin(); j!=i->motion.keys.end(); ++j) {
                osg::Vec3 pos(options_.csf->fix_point(j->second.position));
                osg::AnimationPath::ControlPoint cp(pos, rotate_ypr(j->second.ypr, i->pivot_rot), j->second.scale);
                ap->insert(j->first, cp);
            }
            osg::ref_ptr<osg::AnimationPathCallback> apc = new osg::AnimationPathCallback(ap.get());
            pat->setUpdateCallback(apc.get());
        }

        if (i->parent == -1) {
            root_->addChild(pat.get());
        } else {
            if (i->parent < static_cast<int>(scene_objects_.size())) {
                osg::ref_ptr<osg::PositionAttitudeTransform> parent = pats[i->parent];
                if (!parent.valid()) {
                    parent = new osg::PositionAttitudeTransform;
                    pats[i->parent] = parent;
                }
                parent->addChild(pat.get());
            } else {
                osg::notify(osg::WARN) << "Warning: lwosg::SceneLoader: invalid parent" << std::endl;
            }
        }
    }

    return root_.get();
}

bool SceneLoader::parse_block(const std::string &name, const std::string &data)
{
    std::istringstream iss(data);

    if (name == "AddCamera") {
        scene_cameras_.push_back(Scene_camera());
    }

    if (name == "AddNullObject") {
        osg::ref_ptr<osg::Group> nullobjnode = new osg::Group;
        nullobjnode->setName(data);
        objects_[data] = nullobjnode;
        Scene_object so;
        so.layer_node = nullobjnode.get();
        scene_objects_.push_back(so);
    }

    if (name == "LoadObjectLayer") {
        unsigned layer;
        iss >> layer;
        std::ws(iss);
        std::string filename;
        std::getline(iss, filename);

        // trim any trailing control characters.
        trim(filename);

        if (!filename.empty())
        {

            osg::ref_ptr<osg::Group> objnode;

            Object_map::const_iterator i = objects_.find(filename);

            if (i == objects_.end()) {

                osg::notify(osg::NOTICE) << "Loading object \"" << filename << "\"" << std::endl;

                objnode = dynamic_cast<osg::Group *>(osgDB::readNodeFile(filename));
                if (!objnode.valid()) return false;

                objects_[filename] = objnode;

            } else {
                objnode = i->second;
            }

            if (layer > objnode->getNumChildren()) {
                osg::notify(osg::WARN) << "Warning: lwosg::SceneLoader: layer " << layer << " does not exist in object " << filename << std::endl;
                return 0;
            }

            Scene_object so;
            so.layer_node = objnode->getChild(layer-1);
            if (so.layer_node.valid()) {
                scene_objects_.push_back(so);
            }
                }
    }

    if (name == "PivotPosition") {
        if (!scene_objects_.empty()) {
            osg::Vec3 pivot;
            iss >> pivot.x() >> pivot.y() >> pivot.z();
            scene_objects_.back().pivot = pivot;
        }
    }

    if (name == "PivotRotation") {
        if (!scene_objects_.empty()) {
            osg::Vec3 pivot;
            iss >> pivot.x() >> pivot.y() >> pivot.z();
            scene_objects_.back().pivot_rot = pivot * (osg::PI / 180.0f);
        }
    }

    if (name == "ParentItem") {
        if (!scene_objects_.empty()) {
            std::string id;
            iss >> id;
            if (id.length() == 8) {
                if (id[0] == '1') {
                    id.erase(0, 1);
                    scene_objects_.back().parent = hex_to_int(id);
                }
            } else {
                scene_objects_.back().parent = str_to_int(id);
            }
        }
    }

    if (name == "NumChannels") {
        iss >> channel_count_;
    }

    if (name == "Channel") {
        iss >> current_channel_;
    }

    if (name == "ObjectMotion") {
        capture_obj_motion_ = true;
    }

    if (name == "CameraMotion") {
        capture_cam_motion_ = true;
    }

    return true;
}

bool SceneLoader::parse_block(const std::string &name, const std::vector<std::string> &data)
{
    if (name == "Envelope") {
        if (((capture_obj_motion_ && !scene_objects_.empty()) ||
            (capture_cam_motion_ && !scene_cameras_.empty())) &&
            (data.size() >= 2)) {

            Motion_envelope::Key_map &keys = capture_obj_motion_ ? scene_objects_.back().motion.keys : scene_cameras_.back().motion.keys;

            if (current_channel_ >= (channel_count_ - 1)) {
                capture_obj_motion_ = false;
                capture_cam_motion_ = false;
            }

            for (unsigned i=1; i<data.size(); ++i) {
                std::istringstream iss(data[i]);
                std::string key_id;
                iss >> key_id;
                if (key_id == "Key") {
                    float value;
                    double time;
                    if (iss >> value >> time) {
                        switch (current_channel_) {
                            case 0: keys[time].position.x() = value; break;
                            case 1: keys[time].position.y() = value; break;
                            case 2: keys[time].position.z() = value; break;
                            case 3: keys[time].ypr.x() = value; break;
                            case 4: keys[time].ypr.y() = value; break;
                            case 5: keys[time].ypr.z() = value; break;
                            case 6: keys[time].scale.x() = value; break;
                            case 7: keys[time].scale.y() = value; break;
                            case 8: keys[time].scale.z() = value; break;
                            default: ;
                        }
                    }
                }
            }
        }
    }
    return true;
}

void SceneLoader::clear()
{
    root_ = new osg::Group;
    objects_.clear();
    scene_objects_.clear();
    scene_cameras_.clear();
    camera_animations_.clear();
    channel_count_ = 0;
    current_channel_ = 0;
}
<commit_msg>Added setting of pivot point in AnimationPathCallback<commit_after>/*******************************************************
      Lightwave Scene Loader for OSG

  Copyright (C) 2004 Marco Jez <marco.jez@poste.it>
  OpenSceneGraph is (C) 2004 Robert Osfield
********************************************************/

#include "SceneLoader.h"

#include <osg/Notify>
#include <osg/PositionAttitudeTransform>
#include <osg/AnimationPath>

#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>

#include <fstream>
#include <sstream>

using namespace lwosg;

namespace
{

    int str_to_int(const std::string &s)
    {
        std::istringstream iss(s);
        int n;
        iss >> n;
        return n;
    }

    int hex_to_int(const std::string &s)
    {
        std::istringstream iss(s);
        int n;
        iss >> std::hex >> n;
        return n;
    }

    osg::Quat rotate_ypr(const osg::Vec3 &ypr, const osg::Vec3 pivot_rot = osg::Vec3(0, 0, 0))
    {
        osg::Quat Q1(ypr.z(), osg::Vec3(0, -1, 0));
        osg::Quat Q2(ypr.y(), osg::Vec3(-1, 0, 0));
        osg::Quat Q3(ypr.x(), osg::Vec3(0, 0, -1));
        osg::Quat Q4(pivot_rot.z(), osg::Vec3(0, -1, 0));
        osg::Quat Q5(pivot_rot.y(), osg::Vec3(-1, 0, 0));
        osg::Quat Q6(pivot_rot.x(), osg::Vec3(0, 0, -1));
        return Q1 * Q2 * Q3 * Q4 * Q5 * Q6;
    }

    void trim(std::string& str)
    {
        // trim any trailing control characters.
        //std::cout<<"trim string "<<str<<std::endl;
        while (!str.empty() && str[str.size()-1]<32)
        {
            // removing control character
            //std::cout<<"    removing control character "<<(int)str[str.size()-1]<<std::endl;
            str.erase(str.size()-1);
        }

    }

}

SceneLoader::SceneLoader()
:    capture_obj_motion_(false),
    capture_cam_motion_(false)
{
}

SceneLoader::SceneLoader(const Options &options)
:    capture_obj_motion_(false),
    capture_cam_motion_(false),
    options_(options)
{
}

osg::Group *SceneLoader::load(const std::string &filename, bool search)
{
    std::string fname;

    if (search) {
        fname = osgDB::findDataFile(filename);
        if (fname.empty()) return 0;
    } else {
        fname = filename;
    }

    std::ifstream ifs(fname.c_str());
    if (!ifs.is_open()) return 0;

    clear();

    std::string identifier;
    while (ifs >> identifier) {
        if (identifier == "{") {
            ifs >> identifier;
            std::ws(ifs);
            std::vector<std::string> data;
            std::string data_line;
            while (std::getline(ifs, data_line)) {
                trim(data_line);
                if (data_line == "}") {
                    std::ws(ifs);
                    break;
                }
                data.push_back(data_line);
                std::ws(ifs);
            }
            if (!data.empty()) {
                if (!parse_block(identifier, data)) {
                    return 0;
                }
            }
        } else {
            std::string data;
            std::getline(ifs, data);
            trim(data);
            std::istringstream iss(data);
            std::ws(iss);
            std::getline(iss, data);
            trim(data);
            if (!parse_block(identifier, data)) {
                return 0;
            }
        }
    }

    // build camera animations
    for (Scene_camera_list::iterator ci=scene_cameras_.begin(); ci!=scene_cameras_.end(); ++ci) {
        if (!ci->motion.keys.empty()) {
            osg::ref_ptr<osg::AnimationPath> ap = new osg::AnimationPath;
            for (Motion_envelope::Key_map::const_iterator j=ci->motion.keys.begin(); j!=ci->motion.keys.end(); ++j) {
                osg::Vec3 pos(options_.csf->fix_point(j->second.position));
                //const osg::Vec3 &ypr = j->second.ypr;
                osg::AnimationPath::ControlPoint cp(pos, osg::Quat(osg::PI_2, osg::Vec3(1, 0, 0)) * rotate_ypr(j->second.ypr), j->second.scale);
                osg::notify(osg::NOTICE)<<"scale = "<<j->second.scale<<std::endl;
                ap->insert(j->first, cp);
            }
            camera_animations_.push_back(ap.get());
        }
    }

    // build objects and object animations
    typedef std::map<int, osg::ref_ptr<osg::PositionAttitudeTransform> > PAT_map;
    PAT_map pats;
    int j = 0;
    for (Scene_object_list::iterator i=scene_objects_.begin(); i!=scene_objects_.end(); ++i, ++j) {
        osg::ref_ptr<osg::PositionAttitudeTransform> pat = pats[j];
        if (!pat.valid()) {
            pat = new osg::PositionAttitudeTransform;
            pats[j] = pat;
        }

        pat->addChild(i->layer_node.get());
        pat->setPivotPoint(options_.csf->fix_point(i->pivot));

        // still
        if (!i->motion.keys.empty()) {
            pat->setPosition(options_.csf->fix_point(i->motion.keys.begin()->second.position));
            pat->setAttitude(rotate_ypr(i->motion.keys.begin()->second.ypr, i->pivot_rot));
        }

        // animation
        if (i->motion.keys.size() > 1) {
            osg::ref_ptr<osg::AnimationPath> ap = new osg::AnimationPath;
            for (Motion_envelope::Key_map::const_iterator j=i->motion.keys.begin(); j!=i->motion.keys.end(); ++j) {
                osg::Vec3 pos(options_.csf->fix_point(j->second.position));
                osg::AnimationPath::ControlPoint cp(pos, rotate_ypr(j->second.ypr, i->pivot_rot), j->second.scale);
                ap->insert(j->first, cp);
            }
            osg::ref_ptr<osg::AnimationPathCallback> apc = new osg::AnimationPathCallback(ap.get());
            apc->setPivotPoint(options_.csf->fix_point(i->pivot));
            pat->setUpdateCallback(apc.get());
        }

        if (i->parent == -1) {
            root_->addChild(pat.get());
        } else {
            if (i->parent < static_cast<int>(scene_objects_.size())) {
                osg::ref_ptr<osg::PositionAttitudeTransform> parent = pats[i->parent];
                if (!parent.valid()) {
                    parent = new osg::PositionAttitudeTransform;
                    pats[i->parent] = parent;
                }
                parent->addChild(pat.get());
            } else {
                osg::notify(osg::WARN) << "Warning: lwosg::SceneLoader: invalid parent" << std::endl;
            }
        }
    }

    return root_.get();
}

bool SceneLoader::parse_block(const std::string &name, const std::string &data)
{
    std::istringstream iss(data);

    if (name == "AddCamera") {
        scene_cameras_.push_back(Scene_camera());
    }

    if (name == "AddNullObject") {
        osg::ref_ptr<osg::Group> nullobjnode = new osg::Group;
        nullobjnode->setName(data);
        objects_[data] = nullobjnode;
        Scene_object so;
        so.layer_node = nullobjnode.get();
        scene_objects_.push_back(so);
    }

    if (name == "LoadObjectLayer") {
        unsigned layer;
        iss >> layer;
        std::ws(iss);
        std::string filename;
        std::getline(iss, filename);

        // trim any trailing control characters.
        trim(filename);

        if (!filename.empty())
        {

            osg::ref_ptr<osg::Group> objnode;

            Object_map::const_iterator i = objects_.find(filename);

            if (i == objects_.end()) {

                osg::notify(osg::NOTICE) << "Loading object \"" << filename << "\"" << std::endl;

                objnode = dynamic_cast<osg::Group *>(osgDB::readNodeFile(filename));
                if (!objnode.valid()) return false;

                objects_[filename] = objnode;

            } else {
                objnode = i->second;
            }

            if (layer > objnode->getNumChildren()) {
                osg::notify(osg::WARN) << "Warning: lwosg::SceneLoader: layer " << layer << " does not exist in object " << filename << std::endl;
                return 0;
            }

            Scene_object so;
            so.layer_node = objnode->getChild(layer-1);
            if (so.layer_node.valid()) {
                scene_objects_.push_back(so);
            }
                }
    }

    if (name == "PivotPosition") {
        if (!scene_objects_.empty()) {
            osg::Vec3 pivot;
            iss >> pivot.x() >> pivot.y() >> pivot.z();
            scene_objects_.back().pivot = pivot;
        }
    }

    if (name == "PivotRotation") {
        if (!scene_objects_.empty()) {
            osg::Vec3 pivot;
            iss >> pivot.x() >> pivot.y() >> pivot.z();
            scene_objects_.back().pivot_rot = pivot * (osg::PI / 180.0f);
        }
    }

    if (name == "ParentItem") {
        if (!scene_objects_.empty()) {
            std::string id;
            iss >> id;
            if (id.length() == 8) {
                if (id[0] == '1') {
                    id.erase(0, 1);
                    scene_objects_.back().parent = hex_to_int(id);
                }
            } else {
                scene_objects_.back().parent = str_to_int(id);
            }
        }
    }

    if (name == "NumChannels") {
        iss >> channel_count_;
    }

    if (name == "Channel") {
        iss >> current_channel_;
    }

    if (name == "ObjectMotion") {
        capture_obj_motion_ = true;
    }

    if (name == "CameraMotion") {
        capture_cam_motion_ = true;
    }

    return true;
}

bool SceneLoader::parse_block(const std::string &name, const std::vector<std::string> &data)
{
    if (name == "Envelope") {
        if (((capture_obj_motion_ && !scene_objects_.empty()) ||
            (capture_cam_motion_ && !scene_cameras_.empty())) &&
            (data.size() >= 2)) {

            Motion_envelope::Key_map &keys = capture_obj_motion_ ? scene_objects_.back().motion.keys : scene_cameras_.back().motion.keys;

            if (current_channel_ >= (channel_count_ - 1)) {
                capture_obj_motion_ = false;
                capture_cam_motion_ = false;
            }

            for (unsigned i=1; i<data.size(); ++i) {
                std::istringstream iss(data[i]);
                std::string key_id;
                iss >> key_id;
                if (key_id == "Key") {
                    float value;
                    double time;
                    if (iss >> value >> time) {
                        switch (current_channel_) {
                            case 0: keys[time].position.x() = value; break;
                            case 1: keys[time].position.y() = value; break;
                            case 2: keys[time].position.z() = value; break;
                            case 3: keys[time].ypr.x() = value; break;
                            case 4: keys[time].ypr.y() = value; break;
                            case 5: keys[time].ypr.z() = value; break;
                            case 6: keys[time].scale.x() = value; break;
                            case 7: keys[time].scale.y() = value; break;
                            case 8: keys[time].scale.z() = value; break;
                            default: ;
                        }
                    }
                }
            }
        }
    }
    return true;
}

void SceneLoader::clear()
{
    root_ = new osg::Group;
    objects_.clear();
    scene_objects_.clear();
    scene_cameras_.clear();
    camera_animations_.clear();
    channel_count_ = 0;
    current_channel_ = 0;
}
<|endoftext|>


<commit_before>#ifndef STAN_MATH_PRIM_MAT_FUNCTOR_MAP_RECT_HPP
#define STAN_MATH_PRIM_MAT_FUNCTOR_MAP_RECT_HPP

#include <stan/math/prim/arr/err/check_matching_sizes.hpp>
#include <stan/math/prim/mat/fun/dims.hpp>
#include <stan/math/prim/mat/fun/typedefs.hpp>

#define STAN_REGISTER_MAP_RECT(CALLID, FUNCTOR)

#ifdef STAN_MPI
#error "MPI not yet supported"
#else
#include <stan/math/prim/mat/functor/map_rect_serial.hpp>
#endif

#include <vector>

namespace stan {
namespace math {

/**
 * Map N function evaluations to parameters and data which are in
 * rectangular format. Each function evaluation may return a column
 * vector of different sizes and the output is the concatenated vector
 * from all evaluations.
 *
 * In addition to job specific parameters, real and int data, a shared
 * parameter vector is repeated in all evaluations. All input
 * parameters are stored as vectors whereas data is stored as arrays.
 *
 * For N jobs the output of this function is
 *
 * [
 * f(shared_params, job_params[1], x_r[1], x_i[1]),
 * f(shared_params, job_params[2], x_r[2], x_i[2]),
 * ... ]'.
 *
 * The function is implemented with serial execution and with
 * parallelism (TODO) using MPI. The MPI version is only available if
 * STAN_MPI is defined. For the MPI version to work this function
 * has these special non-standard conventions:
 *
 * - The call_id template parameter is considered as a label for the
 *   functor F and data combination. Since MPI communication is
 *   expensive, the real and int data is transmitted only a single
 *   time per functor F / call_id combination to the workers.
 * - The MPI implementation requires that the functor type fully
 *   specifies the functor and hence requires a default constructible
 *   function object. This choice reduces the need for communication
 *   across MPI as the type is sufficient and the state of the
 *   functor is not necessary to transmit. Thus, the functor is
 *   specified as template argument only.
 * - The size of the returned vector of each job must stay consistent
 *   when performing repeated calls to map_rect (which usually vary
 *   the values of the parameters).
 * - To achieve the exact same results between the serial and the MPI
 *   evaluation scheme both variants work in exactly the same way
 *   which is to use nested AD calls and pre-computing all gradients
 *   when the function gets called. The usual evaluation scheme would
 *   build an AD graph instead of doing on-the-spot gradient
 *   evaluation. For large problems this results in speedups for the
 *   serial version even on a single core due to smaller AD graph
 *   sizes.
 * - In MPI operation mode, no outputs from the workers are streamed
 *   back to the root.
 * - Finally, each map_rect call must be registered with the
 *   STAN_REGISTER_MAP_RECT macro. This is required to enable
 *   communication between processes for the MPI case. The macro
 *   definition is empty if MPI is not enabled.
 *
 * The functor F is expected to have the usual operator() function
 * with signature
 *
 * template <typename T1, typename T2>
 * Eigen::Matrix<typename stan::return_type<T1, T2>::type, Eigen::Dynamic, 1>
 * operator()(const Eigen::Matrix<T1, Eigen::Dynamic, 1>& eta,
 *            const Eigen::Matrix<T2, Eigen::Dynamic, 1>& theta,
 *            const std::vector<double>& x_r, const std::vector<int>& x_i,
 *            std::ostream* msgs = 0) const { ... }
 *
 * WARNING: For the MPI case, the data arguments are NOT checked if
 * they are unchanged between repeated evaluations for a given
 * call_id/functor F pair. This is silently assumed to be immutable
 * between evaluations.
 *
 * @tparam T_shared_param Type of shared parameters.
 * @tparam T_job_param Type of job specific parameters.
 * @param shared_params shared parameter vector passed as first
 * argument to functor for all jobs
 * @param job_params Array of job specific parameter vectors. All job
 * specific parameters must have matching sizes.
 * @param x_r Array of real arrays for each job. The first dimension
 * must match the number of jobs (which is determined by the first
 * dimension of job_params) and each entry must have the same size.
 * @param x_i Array of int data with the same conventions as x_r.
 * @param msgs Output stream for messages.
 * @tparam call_id Label for functor/data combination. See above for
 * details.
 * @tparam F Functor which is applied to all job specific parameters
 * with conventions described.
 * @return concatenated results from all jobs
 */

template <int call_id, typename F, typename T_shared_param,
          typename T_job_param>
Eigen::Matrix<typename stan::return_type<T_shared_param, T_job_param>::type,
              Eigen::Dynamic, 1>
map_rect(const Eigen::Matrix<T_shared_param, Eigen::Dynamic, 1>& shared_params,
         const std::vector<Eigen::Matrix<T_job_param, Eigen::Dynamic, 1>>&
             job_params,
         const std::vector<std::vector<double>>& x_r,
         const std::vector<std::vector<int>>& x_i, std::ostream* msgs = 0) {
  static const char* function = "map_rect";
  typedef Eigen::Matrix<
      typename stan::return_type<T_shared_param, T_job_param>::type,
      Eigen::Dynamic, 1>
      return_t;

  check_matching_sizes(function, "job parameters", job_params, "real data",
                       x_r);
  check_matching_sizes(function, "job parameters", job_params, "int data", x_i);

  // check size consistency of inputs per job
  const std::vector<int> job_params_dims = dims(job_params);
  const int size_job_params = job_params_dims[1];
  const int size_x_r = dims(x_r)[1];
  const int size_x_i = dims(x_i)[1];
  for (int i = 1; i < job_params_dims[0]; i++) {
    check_size_match(function,
                     "Size of one of the vectors of "
                     "the job specific parameters",
                     job_params[i].size(),
                     "size of another vector of the "
                     "job specifc parameters",
                     size_job_params);
    check_size_match(function,
                     "Size of one of the arrays of "
                     "the job specific real data",
                     x_r[i].size(),
                     "size of another array of the "
                     "job specifc real data",
                     size_x_r);
    check_size_match(function,
                     "Size of one of the arrays of "
                     "the job specific int data",
                     x_i[i].size(),
                     "size of another array of the "
                     "job specifc int data",
                     size_x_i);
  }

  if (job_params_dims[0] == 0)
    return return_t();

#ifdef STAN_MPI
  // TODO: add MPI support
#else
  return internal::map_rect_serial<call_id, F, T_shared_param, T_job_param>(
      shared_params, job_params, x_r, x_i, msgs);
#endif
}

}  // namespace math
}  // namespace stan

#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0 (tags/google/stable/2017-11-14)<commit_after>#ifndef STAN_MATH_PRIM_MAT_FUNCTOR_MAP_RECT_HPP
#define STAN_MATH_PRIM_MAT_FUNCTOR_MAP_RECT_HPP

#include <stan/math/prim/arr/err/check_matching_sizes.hpp>
#include <stan/math/prim/mat/fun/dims.hpp>
#include <stan/math/prim/mat/fun/typedefs.hpp>

#define STAN_REGISTER_MAP_RECT(CALLID, FUNCTOR)

#ifdef STAN_MPI
#error "MPI not yet supported"
#else
#include <stan/math/prim/mat/functor/map_rect_serial.hpp>
#endif

#include <vector>

namespace stan {
namespace math {

/**
 * Map N function evaluations to parameters and data which are in
 * rectangular format. Each function evaluation may return a column
 * vector of different sizes and the output is the concatenated vector
 * from all evaluations.
 *
 * In addition to job specific parameters, real and int data, a shared
 * parameter vector is repeated in all evaluations. All input
 * parameters are stored as vectors whereas data is stored as arrays.
 *
 * For N jobs the output of this function is
 *
 * [
 * f(shared_params, job_params[1], x_r[1], x_i[1]),
 * f(shared_params, job_params[2], x_r[2], x_i[2]),
 * ... ]'.
 *
 * The function is implemented with serial execution and with
 * parallelism (TODO) using MPI. The MPI version is only available if
 * STAN_MPI is defined. For the MPI version to work this function
 * has these special non-standard conventions:
 *
 * - The call_id template parameter is considered as a label for the
 *   functor F and data combination. Since MPI communication is
 *   expensive, the real and int data is transmitted only a single
 *   time per functor F / call_id combination to the workers.
 * - The MPI implementation requires that the functor type fully
 *   specifies the functor and hence requires a default constructible
 *   function object. This choice reduces the need for communication
 *   across MPI as the type is sufficient and the state of the
 *   functor is not necessary to transmit. Thus, the functor is
 *   specified as template argument only.
 * - The size of the returned vector of each job must stay consistent
 *   when performing repeated calls to map_rect (which usually vary
 *   the values of the parameters).
 * - To achieve the exact same results between the serial and the MPI
 *   evaluation scheme both variants work in exactly the same way
 *   which is to use nested AD calls and pre-computing all gradients
 *   when the function gets called. The usual evaluation scheme would
 *   build an AD graph instead of doing on-the-spot gradient
 *   evaluation. For large problems this results in speedups for the
 *   serial version even on a single core due to smaller AD graph
 *   sizes.
 * - In MPI operation mode, no outputs from the workers are streamed
 *   back to the root.
 * - Finally, each map_rect call must be registered with the
 *   STAN_REGISTER_MAP_RECT macro. This is required to enable
 *   communication between processes for the MPI case. The macro
 *   definition is empty if MPI is not enabled.
 *
 * The functor F is expected to have the usual operator() function
 * with signature
 *
 * template <typename T1, typename T2>
 * Eigen::Matrix<typename stan::return_type<T1, T2>::type, Eigen::Dynamic, 1>
 * operator()(const Eigen::Matrix<T1, Eigen::Dynamic, 1>& eta,
 *            const Eigen::Matrix<T2, Eigen::Dynamic, 1>& theta,
 *            const std::vector<double>& x_r, const std::vector<int>& x_i,
 *            std::ostream* msgs = 0) const { ... }
 *
 * WARNING: For the MPI case, the data arguments are NOT checked if
 * they are unchanged between repeated evaluations for a given
 * call_id/functor F pair. This is silently assumed to be immutable
 * between evaluations.
 *
 * @tparam T_shared_param Type of shared parameters.
 * @tparam T_job_param Type of job specific parameters.
 * @param shared_params shared parameter vector passed as first
 * argument to functor for all jobs
 * @param job_params Array of job specific parameter vectors. All job
 * specific parameters must have matching sizes.
 * @param x_r Array of real arrays for each job. The first dimension
 * must match the number of jobs (which is determined by the first
 * dimension of job_params) and each entry must have the same size.
 * @param x_i Array of int data with the same conventions as x_r.
 * @param msgs Output stream for messages.
 * @tparam call_id Label for functor/data combination. See above for
 * details.
 * @tparam F Functor which is applied to all job specific parameters
 * with conventions described.
 * @return concatenated results from all jobs
 */

template <int call_id, typename F, typename T_shared_param,
          typename T_job_param>
Eigen::Matrix<typename stan::return_type<T_shared_param, T_job_param>::type,
              Eigen::Dynamic, 1>
map_rect(const Eigen::Matrix<T_shared_param, Eigen::Dynamic, 1>& shared_params,
         const std::vector<Eigen::Matrix<T_job_param, Eigen::Dynamic, 1>>&
             job_params,
         const std::vector<std::vector<double>>& x_r,
         const std::vector<std::vector<int>>& x_i, std::ostream* msgs = 0) {
  static const char* function = "map_rect";
  typedef Eigen::Matrix<
      typename stan::return_type<T_shared_param, T_job_param>::type,
      Eigen::Dynamic, 1>
      return_t;

  check_matching_sizes(function, "job parameters", job_params, "real data",
                       x_r);
  check_matching_sizes(function, "job parameters", job_params, "int data", x_i);

  // check size consistency of inputs per job
  const std::vector<int> job_params_dims = dims(job_params);
  const int size_job_params = job_params_dims[1];
  const int size_x_r = dims(x_r)[1];
  const int size_x_i = dims(x_i)[1];
  for (int i = 1; i < job_params_dims[0]; i++) {
    check_size_match(function,
                     "Size of one of the vectors of "
                     "the job specific parameters",
                     job_params[i].size(),
                     "size of another vector of the "
                     "job specifc parameters",
                     size_job_params);
    check_size_match(function,
                     "Size of one of the arrays of "
                     "the job specific real data",
                     x_r[i].size(),
                     "size of another array of the "
                     "job specifc real data",
                     size_x_r);
    check_size_match(function,
                     "Size of one of the arrays of "
                     "the job specific int data",
                     x_i[i].size(),
                     "size of another array of the "
                     "job specifc int data",
                     size_x_i);
  }

  if (job_params_dims[0] == 0)
    return return_t();

#ifdef STAN_MPI
    // TODO: add MPI support
#else
  return internal::map_rect_serial<call_id, F, T_shared_param, T_job_param>(
      shared_params, job_params, x_r, x_i, msgs);
#endif
}

}  // namespace math
}  // namespace stan

#endif
<|endoftext|>


<commit_before><commit_msg>wae: unused variable 'sOut'<commit_after><|endoftext|>


<commit_before><commit_msg>fdo#68684 export more numbering types correctly into HTML<commit_after><|endoftext|>


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

#ifndef _BASEDLGS_HXX
#include <sfx2/basedlgs.hxx>
#endif
#ifndef _STDCTRL_HXX
#include <svtools/stdctrl.hxx>
#endif
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef _SVTABBX_HXX
#include <svtools/svtabbx.hxx>
#endif
#ifndef _HEADBAR_HXX
#include <svtools/headbar.hxx>
#endif
#ifndef _SWDBDATA_HXX
#include <swdbdata.hxx>
#endif
#ifndef SW_UI_SHARED_CONNECTION_HXX
#include "sharedconnection.hxx"
#endif

namespace com{namespace sun{namespace star{
    namespace container{
        class XNameAccess;
    }
    namespace sdbc{
        class XDataSource;
        class XConnection;
    }
    namespace sdbcx{
        class XColumnsSupplier;
    }
}}}
class SwMailMergeAddressBlockPage;
/*-- 08.04.2004 14:04:29---------------------------------------------------

  -----------------------------------------------------------------------*/
class SwAddressListDialog : public SfxModalDialog
{
    FixedInfo       m_aDescriptionFI;

    FixedInfo       m_aListFT;
    HeaderBar       m_aListHB;
    SvTabListBox    m_aListLB;

    PushButton      m_aLoadListPB;
    PushButton      m_aCreateListPB;
    PushButton      m_aFilterPB;
    PushButton      m_aEditPB;
    PushButton      m_aTablePB;

    FixedLine       m_aSeparatorFL;

    OKButton        m_aOK;
    CancelButton    m_aCancel;
    HelpButton      m_aHelp;

    String          m_sName;
    String          m_sTable;
    String          m_sConnecting;

    String          m_sCreatedURL;
    SvLBoxEntry*    m_pCreatedDataSource;

    bool            m_bInSelectHdl;

    SwMailMergeAddressBlockPage* m_pAddressPage;

    ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess>     m_xDBContext;
//    ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDataSource>          m_xSource;
//    ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>          m_xConnection;
//    ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XColumnsSupplier>    m_xColumnsSupplier;
    SwDBData                                                                        m_aDBData;

    void DetectTablesAndQueries(SvLBoxEntry* pSelect, bool bWidthDialog);

    DECL_LINK(FilterHdl_Impl, PushButton*);
    DECL_LINK(LoadHdl_Impl,   PushButton*);
    DECL_LINK(CreateHdl_Impl, PushButton*);
    DECL_LINK(ListBoxSelectHdl_Impl, SvTabListBox*);
    DECL_LINK(EditHdl_Impl, PushButton*);
    DECL_LINK(TableSelectHdl_Impl, PushButton*);
    DECL_LINK(OKHdl_Impl, PushButton*);

    DECL_STATIC_LINK(SwAddressListDialog, StaticListBoxSelectHdl_Impl, SvLBoxEntry*);

public:
    SwAddressListDialog(SwMailMergeAddressBlockPage* pParent);
    ~SwAddressListDialog();

    ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDataSource>
                        GetSource();

    SharedConnection    GetConnection();

    ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XColumnsSupplier>
                        GetColumnsSupplier();

    const SwDBData&     GetDBData() const       {return m_aDBData;}
    ::rtl::OUString     GetFilter();
};
#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.6.1072); FILE MERGED 2008/04/01 15:58:31 thb 1.6.1072.3: #i85898# Stripping all external header guards 2008/04/01 12:55:06 thb 1.6.1072.2: #i85898# Stripping all external header guards 2008/03/31 16:57:00 rt 1.6.1072.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: addresslistdialog.hxx,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.
 *
 ************************************************************************/
#ifndef _ADDRESSLISTDIALOG_HXX
#define _ADDRESSLISTDIALOG_HXX

#include <sfx2/basedlgs.hxx>
#include <svtools/stdctrl.hxx>
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#include <svtools/svtabbx.hxx>
#include <svtools/headbar.hxx>
#include <swdbdata.hxx>
#include "sharedconnection.hxx"

namespace com{namespace sun{namespace star{
    namespace container{
        class XNameAccess;
    }
    namespace sdbc{
        class XDataSource;
        class XConnection;
    }
    namespace sdbcx{
        class XColumnsSupplier;
    }
}}}
class SwMailMergeAddressBlockPage;
/*-- 08.04.2004 14:04:29---------------------------------------------------

  -----------------------------------------------------------------------*/
class SwAddressListDialog : public SfxModalDialog
{
    FixedInfo       m_aDescriptionFI;

    FixedInfo       m_aListFT;
    HeaderBar       m_aListHB;
    SvTabListBox    m_aListLB;

    PushButton      m_aLoadListPB;
    PushButton      m_aCreateListPB;
    PushButton      m_aFilterPB;
    PushButton      m_aEditPB;
    PushButton      m_aTablePB;

    FixedLine       m_aSeparatorFL;

    OKButton        m_aOK;
    CancelButton    m_aCancel;
    HelpButton      m_aHelp;

    String          m_sName;
    String          m_sTable;
    String          m_sConnecting;

    String          m_sCreatedURL;
    SvLBoxEntry*    m_pCreatedDataSource;

    bool            m_bInSelectHdl;

    SwMailMergeAddressBlockPage* m_pAddressPage;

    ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess>     m_xDBContext;
//    ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDataSource>          m_xSource;
//    ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>          m_xConnection;
//    ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XColumnsSupplier>    m_xColumnsSupplier;
    SwDBData                                                                        m_aDBData;

    void DetectTablesAndQueries(SvLBoxEntry* pSelect, bool bWidthDialog);

    DECL_LINK(FilterHdl_Impl, PushButton*);
    DECL_LINK(LoadHdl_Impl,   PushButton*);
    DECL_LINK(CreateHdl_Impl, PushButton*);
    DECL_LINK(ListBoxSelectHdl_Impl, SvTabListBox*);
    DECL_LINK(EditHdl_Impl, PushButton*);
    DECL_LINK(TableSelectHdl_Impl, PushButton*);
    DECL_LINK(OKHdl_Impl, PushButton*);

    DECL_STATIC_LINK(SwAddressListDialog, StaticListBoxSelectHdl_Impl, SvLBoxEntry*);

public:
    SwAddressListDialog(SwMailMergeAddressBlockPage* pParent);
    ~SwAddressListDialog();

    ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDataSource>
                        GetSource();

    SharedConnection    GetConnection();

    ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XColumnsSupplier>
                        GetColumnsSupplier();

    const SwDBData&     GetDBData() const       {return m_aDBData;}
    ::rtl::OUString     GetFilter();
};
#endif

<|endoftext|>


<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "dialogopen.h"
#include "dialognew.h"
#include "dialognewdirectory.h"

#include <QDirModel>
#include <QFileDialog>
#include <QInputDialog>
#include <QProgressDialog>
#include <QDir>
#include <QDesktopServices>
#include <QFileSystemWatcher>
#include <QUuid>
#include <QMessageBox>

#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    // Setup the UI
    ui->setupUi(this);

    // Setup history stuff
    folderHistory = new QStack<QString>();
    folderForwardHistory = new QStack<QString>();

    // Create the partition safe instance
    psInstance = new PartitionSafe();
    // Setup models
    model = new PSFileSystemModel(this, psInstance);
    modelDirs = new PSFileSystemModel(this, psInstance);

    // Setup a file watcher, it detect changes of files that are currently been edited
    watcher = new QFileSystemWatcher(this);
    connect(watcher, SIGNAL(fileChanged(const QString &)), this, SLOT(fileChanged(const QString &)));

#ifdef QT_DEBUG
#ifndef __WIN32
    const char *vaultPath = "/tmp/marc.vault";
    const char *keyStorePath = "/tmp/marc.keystore";
#else
    wchar_t _vaultPath[1024];
    wchar_t _keyStorePath[1024];
    ExpandEnvironmentStrings(L"%Temp%\\marc.vault", _vaultPath, 1024);
    ExpandEnvironmentStrings(L"%Temp%\\marc.keystore", _keyStorePath, 1024);
    char vaultPath[1024];
    char keyStorePath[1024];
    wcstombs(vaultPath, _vaultPath, 1024);
    wcstombs(keyStorePath, _keyStorePath, 1024);
#endif

    // Debug mode only, load a default vault
    initializeVault((const char *)vaultPath, (const char *)keyStorePath, "test", "test");

    // Show path in status bar
    this->setPath();
#endif
}

MainWindow::~MainWindow()
{
    delete ui;
    delete folderHistory;
    delete folderForwardHistory;
    delete model;
    delete modelDirs;
    delete psInstance;
}

void MainWindow::fileChanged(const QString & file){

    std::cout << "The file '" << file.toLatin1().data() << "' has been modified" << std::endl;
    Entry* item = modifiedFileList.value(file);

    if(item != NULL){
        QFileInfo fileInfo(file);
        psInstance->getVault()->getPartition()->importFile(file.toLatin1().data(), item->getFullPath().c_str());
    }

}

void MainWindow::on_treeViewExplorer_doubleClicked(const QModelIndex &index)
{
    // We should get the selected item
    Entry* item = model->getFile(index);

    // The item is a directory
    if(item->isDirectory()){

        // Get the path
        QString path = QString(item->getFullPath().c_str());

        // Enter given directory and add to history
        model->enterDirectory(path, *folderHistory, *folderForwardHistory);

        // Show path in status bar
        this->setPath();

    }

    // The double clicked item seems to be a file
    else{

        QUuid uuid = QUuid::createUuid();

        // Export the file to a temporary location
        QString tmpFile = QDir::tempPath().append("/").append(uuid.toString()).append("_").append(item->name.data());

        psInstance->getVault()->getPartition()->exportFile(item->getFullPath().data(), tmpFile.toLatin1().data());

        // Watch this temp file for changes
        watcher->addPath(tmpFile);
        modifiedFileList.insert(tmpFile, item);

        // Try to open it with the default application
        QDesktopServices::openUrl(QUrl(tmpFile.prepend("file:///"), QUrl::TolerantMode));
    }

}

void MainWindow::on_buttonBack_clicked()
{
    model->navigation_buttons(*folderHistory, *folderForwardHistory);

    // Show path in status bar
    this->setPath();
}

void MainWindow::on_buttonForward_clicked()
{
    model->navigation_buttons(*folderForwardHistory, *folderHistory);

    // Show path in status bar
    this->setPath();
}

void MainWindow::on_actionOpen_triggered()
{
    // Open the dialog
    DialogOpen *open = new DialogOpen(this);
    int dialogResult = open->exec();

    // Accepted dialog?
    if(dialogResult == QDialog::Accepted) {
        // Open the vault
        initializeVault(open->locationVault, open->locationKeyStore, open->username, open->password);
    }
}

void MainWindow::on_actionNew_triggered()
{
    DialogNew *newDialog = new DialogNew(this);

    newDialog->exec();
}

void MainWindow::on_buttonExport_clicked()
{
    exportFiles();
}

void MainWindow::on_buttonImport_clicked()
{
    importFiles();
}

void MainWindow::on_buttonDelete_clicked()
{
    deleteFileDirectory();
}

void MainWindow::on_actionFolder_triggered()
{
    importFolder();
}

void MainWindow::on_actionFile_triggered()
{
    importFiles();
}

void MainWindow::on_actionExport_triggered()
{
    exportFiles();
}

void MainWindow::importFiles()
{
    QFileDialog qFile;
    // Allow selecting of multiple files
    qFile.setFileMode(QFileDialog::ExistingFiles);
    // Open File dialog
    qFile.exec();

    int filesSelected =qFile.selectedFiles().count();
    int current = 0;

    QProgressDialog dialog(this);
    dialog.setLabelText(tr("Importing file..."));
    dialog.setRange(0, filesSelected);
    dialog.setVisible(true);
    dialog.setModal(true);

    // Import files one by one
    foreach (QString filePath, qFile.selectedFiles()) {
        qDebug() << filePath;
        QFileInfo fileInfo(filePath);

        dialog.setLabelText(tr("Importing file: %1").arg(fileInfo.fileName()));
        qApp->processEvents(QEventLoop::ExcludeUserInputEvents);

        QString destinationPath  = model->getCurrentDirectory().append("/").append(fileInfo.fileName());
        qDebug() << destinationPath;
        model->importFile(filePath.toLatin1().data(),destinationPath.toLatin1().data());
        //psInstance->importFile(filePath.toLatin1().data(),destinationPath.toLatin1().data());
        dialog.setValue(++current);
        qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
    }

    qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
}

void MainWindow::importFolder()
{
    qDebug() << "importFolder() called";

    QFileDialog qFile;
    // Allow selecting of multiple files
    qFile.setFileMode(QFileDialog::Directory);
    // Open File dialog
    qFile.exec();

    foreach (QString folderPath, qFile.selectedFiles()) {
        qDebug() << folderPath;

        // TODO: import folder from filePath
    }
}

void MainWindow::exportFiles()
{
    QFileDialog qFile;
    // Allow selecting of multiple files
    qFile.setFileMode(QFileDialog::DirectoryOnly);

    // Get the destination directory from the user
    QString destinationDir = qFile.getExistingDirectory();

    QModelIndexList selectedRowsList = ui->treeViewExplorer->selectionModel()->selectedRows();
    foreach (QModelIndex index, selectedRowsList)
    {
        QFileInfo fileInfo(model->getFile(index)->getFullPath().data());

        // Get the source and destination paths
        QString sourcePath = model->getFile(index)->getFullPath().data();
        QString destinationPath = destinationDir + "/" + fileInfo.fileName();

        qDebug() << sourcePath;
        qDebug() << destinationDir;
        qDebug() << destinationPath;

        // export the current file
        psInstance->getVault()->getPartition()->exportFile(sourcePath.toLatin1().data(), destinationPath.toLatin1().data());
    }
}

void MainWindow::deleteFileDirectory()
{
    model->deleteFileDirectory(selectedRowsList);
    on_treeViewExplorer_selectionChanged();
}

void MainWindow::initializeVault(const std::string vaultPath, const std::string keyStorePath, const std::string username, const std::string password)
{
    try {
        // Setup vault
        psInstance->init(vaultPath.c_str(), keyStorePath.c_str(), username.c_str(), password.c_str());
        psInstance->open();

        // Create file system models and other instances
        folderHistory->clear();
        folderForwardHistory->clear();

        // Initialize models
        model->init();
        modelDirs->init();

        // Set models in views
        ui->treeViewExplorer->setModel(model);
        ui->treeViewFiles->setModel(modelDirs);

        // TreeViewExplorer: Add signal slot for detecting selection.
        connect(ui->treeViewExplorer->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), this, SLOT(on_treeViewExplorer_selectionChanged()));

        // Enable import/export/Delete
        ui->buttonImport->setEnabled(true);
        ui->actionImports->setEnabled(true);
        ui->actionFile->setEnabled(true);

        // Set paths
        this->setPath();
    } catch(const char *exception) {
        std::cout << "Exception: " << exception << std::endl;
    }
}

void MainWindow::setPath()
{
    // Show message
    if(model != nullptr) ui->statusBar->showMessage(model->getCurrentDirectory());

    // At last item? Disable back button.
    ui->buttonBack->setEnabled(folderHistory->size() > 0);

    // At last forward item? Disable forward button.
    ui->buttonForward->setEnabled(folderForwardHistory->size() > 0);
}

void MainWindow::on_treeViewExplorer_selectionChanged()
{
    //checks if someting is selected
    selectedRowsList = ui->treeViewExplorer->selectionModel()->selectedRows();
    bool hasSelection = selectedRowsList.size()>=1;

    // Enable export/delete
    ui->buttonDelete->setEnabled(hasSelection);
    ui->buttonExport->setEnabled(hasSelection);
    ui->actionExport->setEnabled(hasSelection);
}

void MainWindow::on_buttonNewDirectory_clicked()
{
    DialogNewDirectory *newDialogDirectory = new DialogNewDirectory(this);

    int dialogResult = newDialogDirectory->exec();

    if(dialogResult == QDialog::Accepted)
    {
        // Get new directory name
        QString dirName = newDialogDirectory->dirName;
        QString fullPath = model->getCurrentDirectory()+"/"+dirName;
        // if not existing, create new directory
        if(!model->directoryExists(fullPath)) model->createDirectory(fullPath);
        else QMessageBox::warning(0,"Can't Create Directory", "Directory already exists");
    }
}
<commit_msg>#43 Remove spaces at end of Directory name.<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "dialogopen.h"
#include "dialognew.h"
#include "dialognewdirectory.h"

#include <QDirModel>
#include <QFileDialog>
#include <QInputDialog>
#include <QProgressDialog>
#include <QDir>
#include <QDesktopServices>
#include <QFileSystemWatcher>
#include <QUuid>
#include <QMessageBox>

#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    // Setup the UI
    ui->setupUi(this);

    // Setup history stuff
    folderHistory = new QStack<QString>();
    folderForwardHistory = new QStack<QString>();

    // Create the partition safe instance
    psInstance = new PartitionSafe();
    // Setup models
    model = new PSFileSystemModel(this, psInstance);
    modelDirs = new PSFileSystemModel(this, psInstance);

    // Setup a file watcher, it detect changes of files that are currently been edited
    watcher = new QFileSystemWatcher(this);
    connect(watcher, SIGNAL(fileChanged(const QString &)), this, SLOT(fileChanged(const QString &)));

#ifdef QT_DEBUG
#ifndef __WIN32
    const char *vaultPath = "/tmp/marc.vault";
    const char *keyStorePath = "/tmp/marc.keystore";
#else
    wchar_t _vaultPath[1024];
    wchar_t _keyStorePath[1024];
    ExpandEnvironmentStrings(L"%Temp%\\marc.vault", _vaultPath, 1024);
    ExpandEnvironmentStrings(L"%Temp%\\marc.keystore", _keyStorePath, 1024);
    char vaultPath[1024];
    char keyStorePath[1024];
    wcstombs(vaultPath, _vaultPath, 1024);
    wcstombs(keyStorePath, _keyStorePath, 1024);
#endif

    // Debug mode only, load a default vault
    initializeVault((const char *)vaultPath, (const char *)keyStorePath, "test", "test");

    // Show path in status bar
    this->setPath();
#endif
}

MainWindow::~MainWindow()
{
    delete ui;
    delete folderHistory;
    delete folderForwardHistory;
    delete model;
    delete modelDirs;
    delete psInstance;
}

void MainWindow::fileChanged(const QString & file){

    std::cout << "The file '" << file.toLatin1().data() << "' has been modified" << std::endl;
    Entry* item = modifiedFileList.value(file);

    if(item != NULL){
        QFileInfo fileInfo(file);
        psInstance->getVault()->getPartition()->importFile(file.toLatin1().data(), item->getFullPath().c_str());
    }

}

void MainWindow::on_treeViewExplorer_doubleClicked(const QModelIndex &index)
{
    // We should get the selected item
    Entry* item = model->getFile(index);

    // The item is a directory
    if(item->isDirectory()){

        // Get the path
        QString path = QString(item->getFullPath().c_str());

        // Enter given directory and add to history
        model->enterDirectory(path, *folderHistory, *folderForwardHistory);

        // Show path in status bar
        this->setPath();

    }

    // The double clicked item seems to be a file
    else{

        QUuid uuid = QUuid::createUuid();

        // Export the file to a temporary location
        QString tmpFile = QDir::tempPath().append("/").append(uuid.toString()).append("_").append(item->name.data());

        psInstance->getVault()->getPartition()->exportFile(item->getFullPath().data(), tmpFile.toLatin1().data());

        // Watch this temp file for changes
        watcher->addPath(tmpFile);
        modifiedFileList.insert(tmpFile, item);

        // Try to open it with the default application
        QDesktopServices::openUrl(QUrl(tmpFile.prepend("file:///"), QUrl::TolerantMode));
    }

}

void MainWindow::on_buttonBack_clicked()
{
    model->navigation_buttons(*folderHistory, *folderForwardHistory);

    // Show path in status bar
    this->setPath();
}

void MainWindow::on_buttonForward_clicked()
{
    model->navigation_buttons(*folderForwardHistory, *folderHistory);

    // Show path in status bar
    this->setPath();
}

void MainWindow::on_actionOpen_triggered()
{
    // Open the dialog
    DialogOpen *open = new DialogOpen(this);
    int dialogResult = open->exec();

    // Accepted dialog?
    if(dialogResult == QDialog::Accepted) {
        // Open the vault
        initializeVault(open->locationVault, open->locationKeyStore, open->username, open->password);
    }
}

void MainWindow::on_actionNew_triggered()
{
    DialogNew *newDialog = new DialogNew(this);

    newDialog->exec();
}

void MainWindow::on_buttonExport_clicked()
{
    exportFiles();
}

void MainWindow::on_buttonImport_clicked()
{
    importFiles();
}

void MainWindow::on_buttonDelete_clicked()
{
    deleteFileDirectory();
}

void MainWindow::on_actionFolder_triggered()
{
    importFolder();
}

void MainWindow::on_actionFile_triggered()
{
    importFiles();
}

void MainWindow::on_actionExport_triggered()
{
    exportFiles();
}

void MainWindow::importFiles()
{
    QFileDialog qFile;
    // Allow selecting of multiple files
    qFile.setFileMode(QFileDialog::ExistingFiles);
    // Open File dialog
    qFile.exec();

    int filesSelected =qFile.selectedFiles().count();
    int current = 0;

    QProgressDialog dialog(this);
    dialog.setLabelText(tr("Importing file..."));
    dialog.setRange(0, filesSelected);
    dialog.setVisible(true);
    dialog.setModal(true);

    // Import files one by one
    foreach (QString filePath, qFile.selectedFiles()) {
        qDebug() << filePath;
        QFileInfo fileInfo(filePath);

        dialog.setLabelText(tr("Importing file: %1").arg(fileInfo.fileName()));
        qApp->processEvents(QEventLoop::ExcludeUserInputEvents);

        QString destinationPath  = model->getCurrentDirectory().append("/").append(fileInfo.fileName());
        qDebug() << destinationPath;
        model->importFile(filePath.toLatin1().data(),destinationPath.toLatin1().data());
        //psInstance->importFile(filePath.toLatin1().data(),destinationPath.toLatin1().data());
        dialog.setValue(++current);
        qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
    }

    qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
}

void MainWindow::importFolder()
{
    qDebug() << "importFolder() called";

    QFileDialog qFile;
    // Allow selecting of multiple files
    qFile.setFileMode(QFileDialog::Directory);
    // Open File dialog
    qFile.exec();

    foreach (QString folderPath, qFile.selectedFiles()) {
        qDebug() << folderPath;

        // TODO: import folder from filePath
    }
}

void MainWindow::exportFiles()
{
    QFileDialog qFile;
    // Allow selecting of multiple files
    qFile.setFileMode(QFileDialog::DirectoryOnly);

    // Get the destination directory from the user
    QString destinationDir = qFile.getExistingDirectory();

    QModelIndexList selectedRowsList = ui->treeViewExplorer->selectionModel()->selectedRows();
    foreach (QModelIndex index, selectedRowsList)
    {
        QFileInfo fileInfo(model->getFile(index)->getFullPath().data());

        // Get the source and destination paths
        QString sourcePath = model->getFile(index)->getFullPath().data();
        QString destinationPath = destinationDir + "/" + fileInfo.fileName();

        qDebug() << sourcePath;
        qDebug() << destinationDir;
        qDebug() << destinationPath;

        // export the current file
        psInstance->getVault()->getPartition()->exportFile(sourcePath.toLatin1().data(), destinationPath.toLatin1().data());
    }
}

void MainWindow::deleteFileDirectory()
{
    model->deleteFileDirectory(selectedRowsList);
    on_treeViewExplorer_selectionChanged();
}

void MainWindow::initializeVault(const std::string vaultPath, const std::string keyStorePath, const std::string username, const std::string password)
{
    try {
        // Setup vault
        psInstance->init(vaultPath.c_str(), keyStorePath.c_str(), username.c_str(), password.c_str());
        psInstance->open();

        // Create file system models and other instances
        folderHistory->clear();
        folderForwardHistory->clear();

        // Initialize models
        model->init();
        modelDirs->init();

        // Set models in views
        ui->treeViewExplorer->setModel(model);
        ui->treeViewFiles->setModel(modelDirs);

        // TreeViewExplorer: Add signal slot for detecting selection.
        connect(ui->treeViewExplorer->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), this, SLOT(on_treeViewExplorer_selectionChanged()));

        // Enable import/export/Delete
        ui->buttonImport->setEnabled(true);
        ui->actionImports->setEnabled(true);
        ui->actionFile->setEnabled(true);

        // Set paths
        this->setPath();
    } catch(const char *exception) {
        std::cout << "Exception: " << exception << std::endl;
    }
}

void MainWindow::setPath()
{
    // Show message
    if(model != nullptr) ui->statusBar->showMessage(model->getCurrentDirectory());

    // At last item? Disable back button.
    ui->buttonBack->setEnabled(folderHistory->size() > 0);

    // At last forward item? Disable forward button.
    ui->buttonForward->setEnabled(folderForwardHistory->size() > 0);
}

void MainWindow::on_treeViewExplorer_selectionChanged()
{
    //checks if someting is selected
    selectedRowsList = ui->treeViewExplorer->selectionModel()->selectedRows();
    bool hasSelection = selectedRowsList.size()>=1;

    // Enable export/delete
    ui->buttonDelete->setEnabled(hasSelection);
    ui->buttonExport->setEnabled(hasSelection);
    ui->actionExport->setEnabled(hasSelection);
}

void MainWindow::on_buttonNewDirectory_clicked()
{
    DialogNewDirectory *newDialogDirectory = new DialogNewDirectory(this);

    int dialogResult = newDialogDirectory->exec();

    if(dialogResult == QDialog::Accepted)
    {
        // Get new directory name
        QString dirName = newDialogDirectory->dirName;
        dirName = dirName.trimmed();
        QString fullPath = model->getCurrentDirectory()+"/"+dirName;
        // if not existing, create new directory
        if(!model->directoryExists(fullPath)) model->createDirectory(fullPath);
        else QMessageBox::warning(0,"Can't Create Directory", "Directory already exists");
    }
}
<|endoftext|>