<commit_before>/*! @file */

#ifndef VECTOR_HPP__
#define VECTOR_HPP__

#include <memory>
#include <numeric>
#include <algorithm>
#include <cmath>
#include <vector>
#include <iostream>
#include <random>
#include <assert.h>

namespace linalgcpp
{

/*! @brief Vector represents a mathmatical vector
           with a size and data type
*/
template <typename T = double>
class Vector
{
    public:
        /*! @brief Default Constructor of zero size */
        Vector() = default;

        /*! @brief Constructor of setting the size
            @param size the length of the vector
        */
        Vector(size_t size);

        /*! @brief Constructor of setting the size and intial values
            @param size the length of the vector
            @param val the initial value to set all entries to
        */
        Vector(size_t size, T val);

        /*! @brief Constructor from an std::vector*/
        Vector(std::vector<T> vect);

        /*! @brief Copy Constructor */
        Vector(const Vector& vect) = default;

        /*! @brief Move constructor
        */
        Vector(Vector&& vect);

        /*! @brief Destructor
        */
        ~Vector() noexcept = default;

        /*! @brief Sets this vector equal to another
            @param other the vector to copy
        */
        Vector& operator=(Vector vect);

        /*! @brief Sets all entries to a scalar value
            @param val the value to set all entries to
        */
        Vector& operator=(T val);

        /*! @brief Swap two vectors
            @param lhs left hand side vector
            @param rhs right hand side vector
        */
        template <typename T2>
        friend void Swap(Vector<T2>& lhs, Vector<T2>& rhs);

        /*! @brief STL like begin. Points to start of data
            @retval pointer to the start of data
        */
        T* begin();

        /*! @brief STL like end. Points to the end of data
            @retval pointer to the end of data
        */
        T* end();

        /*! @brief STL like const begin. Points to start of data
            @retval const pointer to the start of data
        */
        const T* begin() const;

        /*! @brief STL like const end. Points to the end of data
            @retval const pointer to the end of data
        */
        const T* end() const;

        /*! @brief Index operator
            @param i index into vector
            @retval reference to value at index i
        */
        T& operator[](int i);

        /*! @brief Const index operator
            @param i index into vector
            @retval const reference to value at index i
        */
        const T& operator[](int i) const;

        /*! @brief Get the length of the vector
            @retval the length of the vector
        */
        size_t size() const;

        /*! @brief Print the vector entries
            @param label the label to print before the list of entries
            @param out stream to print to
        */
        void Print(const std::string& label = "", std::ostream& out = std::cout) const;

    private:
        std::vector<T> data_;

};

template <typename T>
Vector<T>::Vector(size_t size)
{
    data_.resize(size);
}

template <typename T>
Vector<T>::Vector(size_t size, T val)
{
    data_.resize(size, val);
}

template <typename T>
Vector<T>::Vector(std::vector<T> vect)
{
    std::swap(vect, data_);
}

template <typename T>
Vector<T>::Vector(Vector<T>&& vect)
{
    std::swap(*this, vect);
}

template <typename T>
Vector<T>& Vector<T>::operator=(Vector<T> vect)
{
    std::swap(*this, vect);

    return *this;
}

template <typename T2>
void Swap(Vector<T2>& lhs, Vector<T2>& rhs)
{
    std::swap(lhs.data_, rhs.data_);
}

template <typename T>
Vector<T>& Vector<T>::operator=(T val)
{
    std::fill(std::begin(data_), std::end(data_), val);

    return *this;
}

template <typename T>
T* Vector<T>::begin()
{
    return data_.data();
}

template <typename T>
T* Vector<T>::end()
{
    return data_.data() + data_.size();
}

template <typename T>
const T* Vector<T>::begin() const
{
    return data_.data();
}

template <typename T>
const T* Vector<T>::end() const
{
    return data_.data() + data_.size();
}

template <typename T>
T& Vector<T>::operator[](int i)
{
    assert(i >= 0);
    assert(static_cast<unsigned int>(i) < data_.size());

    return data_[i];
}

template <typename T>
const T& Vector<T>::operator[](int i) const
{
    assert(i >= 0);
    assert(static_cast<unsigned int>(i) < data_.size());

    return data_[i];
}

template <typename T>
size_t Vector<T>::size() const
{
    return data_.size();
}

template <typename T>
void Vector<T>::Print(const std::string& label, std::ostream& out) const
{
    out << label;

    out << (*this);

    out << "\n";
}

// Templated Free Functions

/*! @brief Compute the L2 norm of the vector
    @param vect the vector to compute the L2 norm of
    @retval the L2 norm
*/
template <typename T>
double L2Norm(const Vector<T>& vect)
{
    return std::sqrt(InnerProduct(vect, vect));
}

/*! @brief Print the vector to a stream
    @param out stream to print to
    @param vect the vector to print
*/
template <typename T>
std::ostream& operator<<(std::ostream& out, const Vector<T>& vect)
{
    out << "\n";

    for (const auto& i : vect)
    {
        out << i << "\n";
    }

    out << "\n";

    return out;
}

/*! @brief Compute the inner product two vectors x^T y
    @param lhs left hand side vector x
    @param rhs right hand side vector y
    @retval the inner product
*/
template <typename T, typename T2>
double InnerProduct(const Vector<T>& lhs, const Vector<T2>& rhs)
{
    assert(lhs.size() == rhs.size());

    double start = 0.0;
    return std::inner_product(std::begin(lhs), std::end(lhs), std::begin(rhs), start);
}

/*! @brief Compute the inner product two vectors x^T y
    @param lhs left hand side vector x
    @param rhs right hand side vector y
    @retval the inner product
*/
template <typename T, typename T2>
double operator*(const Vector<T>& lhs, const Vector<T2>& rhs)
{
    return InnerProduct(lhs, rhs);
}

/*! @brief Entrywise multiplication x_i = x_i * y_i
    @param lhs left hand side vector x
    @param rhs right hand side vector y
*/
template <typename T>
Vector<T>& operator*=(Vector<T>& lhs, const Vector<T>& rhs)
{
    assert(lhs.size() == rhs.size());

    const int size = lhs.size();

    for (int i = 0; i < size; ++i)
    {
        lhs[i] *= rhs[i];
    }

    return lhs;
}

/*! @brief Entrywise subtraction x_i = x_i - y_i
    @param lhs left hand side vector x
    @param rhs right hand side vector y
*/
template <typename T>
Vector<T>& operator-=(Vector<T>& lhs, const Vector<T>& rhs)
{
    assert(lhs.size() == rhs.size());

    const int size = lhs.size();

    for (int i = 0; i < size; ++i)
    {
        lhs[i] -= rhs[i];
    }

    return lhs;
}

/*! @brief Multiply a vector by a scalar
    @param vect vector to multiply
    @param val value to scale by
*/
template <typename T, typename T2>
Vector<T>& operator*=(Vector<T>& vect, T2 val)
{
    for (T& i : vect)
    {
        i *= val;
    }

    return vect;
}

/*! @brief Divide a vector by a scalar
    @param vect vector to multiply
    @param val value to scale by
*/
template <typename T, typename T2>
Vector<T>& operator/=(Vector<T>& vect, T2 val)
{
    assert(val != 0);

    for (T& i : vect)
    {
        i /= val;
    }

    return vect;
}

/*! @brief Multiply a vector by a scalar into a new vector
    @param vect vector to multiply
    @param val value to scale by
    @retval the vector multiplied by the scalar
*/
template <typename T, typename T2>
Vector<T> operator*(Vector<T> vect, T2 val)
{
    for (T& i : vect)
    {
        i *= val;
    }

    return vect;
}

/*! @brief Multiply a vector by a scalar into a new vector
    @param vect vector to multiply
    @param val value to scale by
    @retval the vector multiplied by the scalar
*/
template <typename T, typename T2>
Vector<T> operator*(T2 val, Vector<T> vect)
{
    for (T& i : vect)
    {
        i *= val;
    }

    return vect;
}

/*! @brief Add two vectors into a new vector z = x + y
    @param lhs left hand side vector x
    @param rhs right hand side vector y
    @retval the sum of the two vectors
*/
template <typename T>
Vector<T> operator+(Vector<T> lhs, const Vector<T>& rhs)
{
    return lhs += rhs;
}

/*! @brief Subtract two vectors into a new vector z = x - y
    @param lhs left hand side vector x
    @param rhs right hand side vector y
    @retval the difference of the two vectors
*/
template <typename T>
Vector<T> operator-(Vector<T> lhs, const Vector<T>& rhs)
{
    return lhs -= rhs;
}

/*! @brief Add a scalar to each entry
    @param lhs vector to add to
    @param val the value to add
*/
template <typename T, typename T2>
Vector<T>& operator+=(Vector<T>& lhs, T2 val)
{
    const int size = lhs.size();

    for (T& i : lhs)
    {
        i += val;
    }

    return lhs;
}

/*! @brief Subtract a scalar from each entry
    @param lhs vector to add to
    @param val the value to subtract
*/
template <typename T, typename T2>
Vector<T>& operator-=(Vector<T>& lhs, T2 val)
{
    const int size = lhs.size();

    for (T& i : lhs)
    {
        i -= val;
    }

    return lhs;
}

/*! @brief Compute the maximum entry value in a vector
    @param vect vector to find the max
    @retval the maximum entry value
*/
template <typename T>
T Max(const Vector<T>& vect)
{
    return *std::max_element(std::begin(vect), std::end(vect));
}

/*! @brief Compute the minimum entry value in a vector
    @param vect vector to find the minimum
    @retval the minimum entry value
*/
template <typename T>
T Min(const Vector<T>& vect)
{
    return *std::min_element(std::begin(vect), std::end(vect));
}

/*! @brief Compute the sum of all vector entries
    @param vect vector to find the sum
    @retval the sum of all entries
*/
template <typename T>
T Sum(const Vector<T>& vect)
{
    T total = 0.0;
    std::accumulate(std::begin(vect), std::end(vect), total);

    return total;
}

/*! @brief Compute the mean of all vector entries
    @param vect vector to find the mean
    @retval the mean of all entries
*/
template <typename T>
double Mean(const Vector<T>& vect)
{
    return Sum(vect) / vect.size();
}

/*! @brief Print an std vector to a stream
    @param out stream to print to
    @param vect the vector to print
*/
template <typename T>
std::ostream& operator<<(std::ostream& out, const std::vector<T>& vect)
{
    out << "\n";

    for (const auto& i : vect)
    {
        out << i << "\n";
    }

    out << "\n";

    return out;
}

/*! @brief Randomize the entries in a double vector
    @param vect vector to randomize
    @param lo lower range limit
    @param hi upper range limit
*/
void Randomize(Vector<double>& vect, double lo = 0.0, double hi = 1.0);

/*! @brief Randomize the entries in a integer vector
    @param vect vector to randomize
    @param lo lower range limit
    @param hi upper range limit
*/
void Randomize(Vector<int>& vect, int lo = 0.0, int hi = 1.0);

/*! @brief Normalize a vector such that its L2 norm is 1.0
    @param vect vector to normalize
*/
void Normalize(Vector<double>& vect);

/*! @brief Subtract a constant vector set to the average
    from this vector: x_i = x_i - mean(x)
    @param vect vector to subtract average from
*/
void SubAvg(Vector<double>& vect);

} // namespace linalgcpp

#endif // VECTOR_HPP__
<commit_msg>Fix vector documentation<commit_after>/*! @file */

#ifndef VECTOR_HPP__
#define VECTOR_HPP__

#include <memory>
#include <numeric>
#include <algorithm>
#include <cmath>
#include <vector>
#include <iostream>
#include <random>
#include <assert.h>

namespace linalgcpp
{

/*! @brief Vector represents a mathmatical vector
           with a size and data type
*/
template <typename T = double>
class Vector
{
    public:
        /*! @brief Default Constructor of zero size */
        Vector() = default;

        /*! @brief Constructor of setting the size
            @param size the length of the vector
        */
        Vector(size_t size);

        /*! @brief Constructor of setting the size and intial values
            @param size the length of the vector
            @param val the initial value to set all entries to
        */
        Vector(size_t size, T val);

        /*! @brief Constructor from an std::vector*/
        Vector(std::vector<T> vect);

        /*! @brief Copy Constructor */
        Vector(const Vector& vect) = default;

        /*! @brief Move constructor
            @param vect the vector to move
        */
        Vector(Vector&& vect);

        /*! @brief Destructor
        */
        ~Vector() noexcept = default;

        /*! @brief Sets this vector equal to another
            @param vect the vector to copy
        */
        Vector& operator=(Vector vect);

        /*! @brief Sets all entries to a scalar value
            @param val the value to set all entries to
        */
        Vector& operator=(T val);

        /*! @brief Swap two vectors
            @param lhs left hand side vector
            @param rhs right hand side vector
        */
        template <typename T2>
        friend void Swap(Vector<T2>& lhs, Vector<T2>& rhs);

        /*! @brief STL like begin. Points to start of data
            @retval pointer to the start of data
        */
        T* begin();

        /*! @brief STL like end. Points to the end of data
            @retval pointer to the end of data
        */
        T* end();

        /*! @brief STL like const begin. Points to start of data
            @retval const pointer to the start of data
        */
        const T* begin() const;

        /*! @brief STL like const end. Points to the end of data
            @retval const pointer to the end of data
        */
        const T* end() const;

        /*! @brief Index operator
            @param i index into vector
            @retval reference to value at index i
        */
        T& operator[](int i);

        /*! @brief Const index operator
            @param i index into vector
            @retval const reference to value at index i
        */
        const T& operator[](int i) const;

        /*! @brief Get the length of the vector
            @retval the length of the vector
        */
        size_t size() const;

        /*! @brief Print the vector entries
            @param label the label to print before the list of entries
            @param out stream to print to
        */
        void Print(const std::string& label = "", std::ostream& out = std::cout) const;

    private:
        std::vector<T> data_;

};

template <typename T>
Vector<T>::Vector(size_t size)
{
    data_.resize(size);
}

template <typename T>
Vector<T>::Vector(size_t size, T val)
{
    data_.resize(size, val);
}

template <typename T>
Vector<T>::Vector(std::vector<T> vect)
{
    std::swap(vect, data_);
}

template <typename T>
Vector<T>::Vector(Vector<T>&& vect)
{
    std::swap(*this, vect);
}

template <typename T>
Vector<T>& Vector<T>::operator=(Vector<T> vect)
{
    std::swap(*this, vect);

    return *this;
}

template <typename T2>
void Swap(Vector<T2>& lhs, Vector<T2>& rhs)
{
    std::swap(lhs.data_, rhs.data_);
}

template <typename T>
Vector<T>& Vector<T>::operator=(T val)
{
    std::fill(std::begin(data_), std::end(data_), val);

    return *this;
}

template <typename T>
T* Vector<T>::begin()
{
    return data_.data();
}

template <typename T>
T* Vector<T>::end()
{
    return data_.data() + data_.size();
}

template <typename T>
const T* Vector<T>::begin() const
{
    return data_.data();
}

template <typename T>
const T* Vector<T>::end() const
{
    return data_.data() + data_.size();
}

template <typename T>
T& Vector<T>::operator[](int i)
{
    assert(i >= 0);
    assert(static_cast<unsigned int>(i) < data_.size());

    return data_[i];
}

template <typename T>
const T& Vector<T>::operator[](int i) const
{
    assert(i >= 0);
    assert(static_cast<unsigned int>(i) < data_.size());

    return data_[i];
}

template <typename T>
size_t Vector<T>::size() const
{
    return data_.size();
}

template <typename T>
void Vector<T>::Print(const std::string& label, std::ostream& out) const
{
    out << label;

    out << (*this);

    out << "\n";
}

// Templated Free Functions

/*! @brief Compute the L2 norm of the vector
    @param vect the vector to compute the L2 norm of
    @retval the L2 norm
*/
template <typename T>
double L2Norm(const Vector<T>& vect)
{
    return std::sqrt(InnerProduct(vect, vect));
}

/*! @brief Print the vector to a stream
    @param out stream to print to
    @param vect the vector to print
*/
template <typename T>
std::ostream& operator<<(std::ostream& out, const Vector<T>& vect)
{
    out << "\n";

    for (const auto& i : vect)
    {
        out << i << "\n";
    }

    out << "\n";

    return out;
}

/*! @brief Compute the inner product two vectors x^T y
    @param lhs left hand side vector x
    @param rhs right hand side vector y
    @retval the inner product
*/
template <typename T, typename T2>
double InnerProduct(const Vector<T>& lhs, const Vector<T2>& rhs)
{
    assert(lhs.size() == rhs.size());

    double start = 0.0;
    return std::inner_product(std::begin(lhs), std::end(lhs), std::begin(rhs), start);
}

/*! @brief Compute the inner product two vectors x^T y
    @param lhs left hand side vector x
    @param rhs right hand side vector y
    @retval the inner product
*/
template <typename T, typename T2>
double operator*(const Vector<T>& lhs, const Vector<T2>& rhs)
{
    return InnerProduct(lhs, rhs);
}

/*! @brief Entrywise multiplication x_i = x_i * y_i
    @param lhs left hand side vector x
    @param rhs right hand side vector y
*/
template <typename T>
Vector<T>& operator*=(Vector<T>& lhs, const Vector<T>& rhs)
{
    assert(lhs.size() == rhs.size());

    const int size = lhs.size();

    for (int i = 0; i < size; ++i)
    {
        lhs[i] *= rhs[i];
    }

    return lhs;
}

/*! @brief Entrywise subtraction x_i = x_i - y_i
    @param lhs left hand side vector x
    @param rhs right hand side vector y
*/
template <typename T>
Vector<T>& operator-=(Vector<T>& lhs, const Vector<T>& rhs)
{
    assert(lhs.size() == rhs.size());

    const int size = lhs.size();

    for (int i = 0; i < size; ++i)
    {
        lhs[i] -= rhs[i];
    }

    return lhs;
}

/*! @brief Multiply a vector by a scalar
    @param vect vector to multiply
    @param val value to scale by
*/
template <typename T, typename T2>
Vector<T>& operator*=(Vector<T>& vect, T2 val)
{
    for (T& i : vect)
    {
        i *= val;
    }

    return vect;
}

/*! @brief Divide a vector by a scalar
    @param vect vector to multiply
    @param val value to scale by
*/
template <typename T, typename T2>
Vector<T>& operator/=(Vector<T>& vect, T2 val)
{
    assert(val != 0);

    for (T& i : vect)
    {
        i /= val;
    }

    return vect;
}

/*! @brief Multiply a vector by a scalar into a new vector
    @param vect vector to multiply
    @param val value to scale by
    @retval the vector multiplied by the scalar
*/
template <typename T, typename T2>
Vector<T> operator*(Vector<T> vect, T2 val)
{
    for (T& i : vect)
    {
        i *= val;
    }

    return vect;
}

/*! @brief Multiply a vector by a scalar into a new vector
    @param vect vector to multiply
    @param val value to scale by
    @retval the vector multiplied by the scalar
*/
template <typename T, typename T2>
Vector<T> operator*(T2 val, Vector<T> vect)
{
    for (T& i : vect)
    {
        i *= val;
    }

    return vect;
}

/*! @brief Add two vectors into a new vector z = x + y
    @param lhs left hand side vector x
    @param rhs right hand side vector y
    @retval the sum of the two vectors
*/
template <typename T>
Vector<T> operator+(Vector<T> lhs, const Vector<T>& rhs)
{
    return lhs += rhs;
}

/*! @brief Subtract two vectors into a new vector z = x - y
    @param lhs left hand side vector x
    @param rhs right hand side vector y
    @retval the difference of the two vectors
*/
template <typename T>
Vector<T> operator-(Vector<T> lhs, const Vector<T>& rhs)
{
    return lhs -= rhs;
}

/*! @brief Add a scalar to each entry
    @param lhs vector to add to
    @param val the value to add
*/
template <typename T, typename T2>
Vector<T>& operator+=(Vector<T>& lhs, T2 val)
{
    const int size = lhs.size();

    for (T& i : lhs)
    {
        i += val;
    }

    return lhs;
}

/*! @brief Subtract a scalar from each entry
    @param lhs vector to add to
    @param val the value to subtract
*/
template <typename T, typename T2>
Vector<T>& operator-=(Vector<T>& lhs, T2 val)
{
    const int size = lhs.size();

    for (T& i : lhs)
    {
        i -= val;
    }

    return lhs;
}

/*! @brief Compute the maximum entry value in a vector
    @param vect vector to find the max
    @retval the maximum entry value
*/
template <typename T>
T Max(const Vector<T>& vect)
{
    return *std::max_element(std::begin(vect), std::end(vect));
}

/*! @brief Compute the minimum entry value in a vector
    @param vect vector to find the minimum
    @retval the minimum entry value
*/
template <typename T>
T Min(const Vector<T>& vect)
{
    return *std::min_element(std::begin(vect), std::end(vect));
}

/*! @brief Compute the sum of all vector entries
    @param vect vector to find the sum
    @retval the sum of all entries
*/
template <typename T>
T Sum(const Vector<T>& vect)
{
    T total = 0.0;
    std::accumulate(std::begin(vect), std::end(vect), total);

    return total;
}

/*! @brief Compute the mean of all vector entries
    @param vect vector to find the mean
    @retval the mean of all entries
*/
template <typename T>
double Mean(const Vector<T>& vect)
{
    return Sum(vect) / vect.size();
}

/*! @brief Print an std vector to a stream
    @param out stream to print to
    @param vect the vector to print
*/
template <typename T>
std::ostream& operator<<(std::ostream& out, const std::vector<T>& vect)
{
    out << "\n";

    for (const auto& i : vect)
    {
        out << i << "\n";
    }

    out << "\n";

    return out;
}

/*! @brief Randomize the entries in a double vector
    @param vect vector to randomize
    @param lo lower range limit
    @param hi upper range limit
*/
void Randomize(Vector<double>& vect, double lo = 0.0, double hi = 1.0);

/*! @brief Randomize the entries in a integer vector
    @param vect vector to randomize
    @param lo lower range limit
    @param hi upper range limit
*/
void Randomize(Vector<int>& vect, int lo = 0.0, int hi = 1.0);

/*! @brief Normalize a vector such that its L2 norm is 1.0
    @param vect vector to normalize
*/
void Normalize(Vector<double>& vect);

/*! @brief Subtract a constant vector set to the average
    from this vector: x_i = x_i - mean(x)
    @param vect vector to subtract average from
*/
void SubAvg(Vector<double>& vect);

} // namespace linalgcpp

#endif // VECTOR_HPP__
<|endoftext|>


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

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

#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _SVX_SVXENUM_HXX
#include <svx/svxenum.hxx>
#endif
#ifndef _SVX_SVXIDS_HRC
#include <svx/svxids.hrc>
#endif

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

class SvXMLUnitConverter;
namespace rtl
{
    class OUString;
}

// class SvxEscapementItem -----------------------------------------------

#define DFLT_ESC_SUPER   33     // 1/3
#define DFLT_ESC_SUB    -33     // auch 1/3 fr"uher 8/100
#define DFLT_ESC_PROP    58
#define DFLT_ESC_AUTO_SUPER 101
#define DFLT_ESC_AUTO_SUB  -101

/*  [Beschreibung]

    Dieses Item beschreibt die Schrift-Position.
*/

class SVX_DLLPUBLIC SvxEscapementItem : public SfxEnumItemInterface
{
    short nEsc;
    BYTE  nProp;
public:
    TYPEINFO();

    SvxEscapementItem( const USHORT nId  );
    SvxEscapementItem( const SvxEscapement eEscape,
                   const USHORT nId  );
    SvxEscapementItem( const short nEsc, const BYTE nProp,
                   const USHORT nId  );

    // "pure virtual Methoden" vom SfxPoolItem
    virtual int              operator==( const SfxPoolItem& ) const;
    virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
                                    SfxMapUnit eCoreMetric,
                                    SfxMapUnit ePresMetric,
                                    String &rText, const IntlWrapper * = 0 ) const;

    virtual sal_Bool             QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
    virtual sal_Bool             PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );

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

    inline void SetEscapement( const SvxEscapement eNew )
    {
        if( SVX_ESCAPEMENT_OFF == eNew )
            nEsc = 0, nProp = 100;
        else
            if( SVX_ESCAPEMENT_SUPERSCRIPT == eNew )
                nEsc = DFLT_ESC_SUPER, nProp = DFLT_ESC_PROP;
            else
                nEsc = DFLT_ESC_SUB, nProp = DFLT_ESC_PROP;
    }
    inline SvxEscapement GetEscapement() const { return static_cast< SvxEscapement >( GetEnumValue() ); }

    inline short &GetEsc() { return nEsc; }
    inline short GetEsc() const { return nEsc; }

    inline BYTE &GetProp() { return nProp; }
    inline BYTE GetProp() const { return nProp; }

    inline SvxEscapementItem& operator=(const SvxEscapementItem& rEsc)
        {
            nEsc  = rEsc.GetEsc();
            nProp = rEsc.GetProp();
            return *this;
        }

    virtual USHORT          GetValueCount() const;
    virtual String          GetValueTextByPos( USHORT nPos ) const;
    virtual USHORT          GetEnumValue() const;
    virtual void            SetEnumValue( USHORT nNewVal );
};

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.3.446); FILE MERGED 2008/04/01 15:49:32 thb 1.3.446.3: #i85898# Stripping all external header guards 2008/04/01 12:46:38 thb 1.3.446.2: #i85898# Stripping all external header guards 2008/03/31 14:18:11 rt 1.3.446.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: escpitem.hxx,v $
 * $Revision: 1.4 $
 *
 * 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 _SVX_ESCPITEM_HXX
#define _SVX_ESCPITEM_HXX

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

#include <svtools/eitem.hxx>
#include <svx/svxenum.hxx>
#ifndef _SVX_SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
#include "svx/svxdllapi.h"

class SvXMLUnitConverter;
namespace rtl
{
    class OUString;
}

// class SvxEscapementItem -----------------------------------------------

#define DFLT_ESC_SUPER   33     // 1/3
#define DFLT_ESC_SUB    -33     // auch 1/3 fr"uher 8/100
#define DFLT_ESC_PROP    58
#define DFLT_ESC_AUTO_SUPER 101
#define DFLT_ESC_AUTO_SUB  -101

/*  [Beschreibung]

    Dieses Item beschreibt die Schrift-Position.
*/

class SVX_DLLPUBLIC SvxEscapementItem : public SfxEnumItemInterface
{
    short nEsc;
    BYTE  nProp;
public:
    TYPEINFO();

    SvxEscapementItem( const USHORT nId  );
    SvxEscapementItem( const SvxEscapement eEscape,
                   const USHORT nId  );
    SvxEscapementItem( const short nEsc, const BYTE nProp,
                   const USHORT nId  );

    // "pure virtual Methoden" vom SfxPoolItem
    virtual int              operator==( const SfxPoolItem& ) const;
    virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
                                    SfxMapUnit eCoreMetric,
                                    SfxMapUnit ePresMetric,
                                    String &rText, const IntlWrapper * = 0 ) const;

    virtual sal_Bool             QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
    virtual sal_Bool             PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );

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

    inline void SetEscapement( const SvxEscapement eNew )
    {
        if( SVX_ESCAPEMENT_OFF == eNew )
            nEsc = 0, nProp = 100;
        else
            if( SVX_ESCAPEMENT_SUPERSCRIPT == eNew )
                nEsc = DFLT_ESC_SUPER, nProp = DFLT_ESC_PROP;
            else
                nEsc = DFLT_ESC_SUB, nProp = DFLT_ESC_PROP;
    }
    inline SvxEscapement GetEscapement() const { return static_cast< SvxEscapement >( GetEnumValue() ); }

    inline short &GetEsc() { return nEsc; }
    inline short GetEsc() const { return nEsc; }

    inline BYTE &GetProp() { return nProp; }
    inline BYTE GetProp() const { return nProp; }

    inline SvxEscapementItem& operator=(const SvxEscapementItem& rEsc)
        {
            nEsc  = rEsc.GetEsc();
            nProp = rEsc.GetProp();
            return *this;
        }

    virtual USHORT          GetValueCount() const;
    virtual String          GetValueTextByPos( USHORT nPos ) const;
    virtual USHORT          GetEnumValue() const;
    virtual void            SetEnumValue( USHORT nNewVal );
};

#endif

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2017 Akil Darjean (adarjean@uh.edu)
 * Distributed under the MIT License.
 * See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT
 */

#include "window.h"
#include <iostream>

void Window::create()
{
    this->filename = "";

    init();
    draw();
}

void Window::create(std::string filename)
{
    this->filename = filename;

    load();
    init();
    draw();
}

void Window::load()
{
    if (!texture.loadFromFile(filename)) {
        std::cout << "Error: file does not exist" << std::endl;
    }
    texture.setSmooth(true);
    sprite.setTexture(texture);
}

void Window::init()
{
    window.create(sf::VideoMode(640, 480), "SFML Image Viewer");

    // Initialize view
    view.reset(sf::FloatRect(
        0,
        0,
        static_cast<float>(texture.getSize().x),
        static_cast<float>(texture.getSize().y)));
}

void Window::checkEvents()
{
    sf::Event event;
    while (window.pollEvent(event)) {
        if (event.type == sf::Event::Closed) {
            window.close();
        }
        if (event.type == sf::Event::Resized) {
            getLetterboxView();
        }
    }
}

void Window::draw()
{
    while (window.isOpen()) {
        checkEvents();

        window.clear();
        window.setView(view);
        window.draw(sprite);
        window.display();
    }
}

void Window::getLetterboxView()
{
    float windowRatio = window.getSize().x / static_cast<float>(window.getSize().y);
    float viewRatio = view.getSize().x / static_cast<float>(view.getSize().y);

    sf::Vector2f size;
    sf::Vector2f pos;

    if (windowRatio > viewRatio) {
        size.x = viewRatio / windowRatio;
        pos.x = (1 - size.x) / 2.f;
        size.y = 1;
        pos.y = 0;
    } else {
        size.y = windowRatio / viewRatio;
        pos.y = (1 - size.y) / 2.f;
        size.x = 1;
        pos.x = 0;
    }

    view.setViewport(sf::FloatRect(pos.x, pos.y, size.x, size.y));
}
<commit_msg>Add keyboard handling<commit_after>/*
 * Copyright (c) 2017 Akil Darjean (adarjean@uh.edu)
 * Distributed under the MIT License.
 * See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT
 */

#include "window.h"
#include <iostream>

void Window::create()
{
    this->filename = "";

    init();
    draw();
}

void Window::create(std::string filename)
{
    this->filename = filename;

    load();
    init();
    draw();
}

void Window::load()
{
    if (!texture.loadFromFile(filename)) {
        std::cout << "Error: file does not exist" << std::endl;
    }
    texture.setSmooth(true);
    sprite.setTexture(texture);
}

void Window::init()
{
    window.create(sf::VideoMode(640, 480), "SFML Image Viewer");

    // Initialize view
    view.reset(sf::FloatRect(
        0,
        0,
        static_cast<float>(texture.getSize().x),
        static_cast<float>(texture.getSize().y)));
}

void Window::checkEvents()
{
    sf::Event event;
    while (window.pollEvent(event)) {
        switch (event.type) {
        case sf::Event::EventType::Closed:
            window.close();
            break;

        case sf::Event::EventType::Resized:
            getLetterboxView();
            break;

        case sf::Event::KeyPressed:
            if (event.key.code == sf::Keyboard::Q) {
                window.close();
            }

        default:
            break;
        }
    }
}

void Window::draw()
{
    while (window.isOpen()) {
        checkEvents();

        window.clear();
        window.setView(view);
        window.draw(sprite);
        window.display();
    }
}

void Window::getLetterboxView()
{
    float windowRatio = window.getSize().x / static_cast<float>(window.getSize().y);
    float viewRatio = view.getSize().x / static_cast<float>(view.getSize().y);

    sf::Vector2f size;
    sf::Vector2f pos;

    if (windowRatio > viewRatio) {
        size.x = viewRatio / windowRatio;
        pos.x = (1 - size.x) / 2.f;
        size.y = 1;
        pos.y = 0;
    } else {
        size.y = windowRatio / viewRatio;
        pos.y = (1 - size.y) / 2.f;
        size.x = 1;
        pos.x = 0;
    }

    view.setViewport(sf::FloatRect(pos.x, pos.y, size.x, size.y));
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2017 Akil Darjean (adarjean@uh.edu)
 * Distributed under the MIT License.
 * See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT
 */

#include "window.h"
#include <SFML/Graphics.hpp>
#include <boost/filesystem.hpp>
#include <exception>
#include <future>

struct path_leaf_string {
    std::string operator()(const boost::filesystem::directory_entry& entry) const
    {
        return entry.path().leaf().string();
    }
};

Window::Window(const std::string&& filename)
{
    this->filename = filename;
    this->isFullscreen = false;

    load();
    init();
    draw();
}

void Window::load()
{
    // Run a seperate thread to get a list of all files in the directory
    auto f = std::async(&Window::getFilesInDirectory, this);

    if (!texture.loadFromFile(filename)) {
        throw std::runtime_error("Error: Image not found");
    }
    texture.setSmooth(true);
    sprite.setTexture(texture);

    files = f.get();
}

void Window::init()
{
    desktop = sf::VideoMode::getDesktopMode();

    window.create(sf::VideoMode(640, 480), "SFML Image Viewer");
    window.setKeyRepeatEnabled(false);
    window.setFramerateLimit(framerate);

    // Initialize view
    view.reset(sf::FloatRect(
        0.0f,
        0.0f,
        static_cast<float>(texture.getSize().x),
        static_cast<float>(texture.getSize().y)));
}

void Window::draw()
{
    while (window.isOpen()) {
        checkEvents();

        window.clear();
        window.setView(view);
        window.draw(sprite);
        window.display();
    }
}

void Window::checkEvents()
{
    sf::Event event;
    while (window.pollEvent(event)) {
        switch (event.type) {
        case sf::Event::EventType::Closed:
            window.close();
            break;

        case sf::Event::EventType::Resized:
            getLetterboxView();
            break;

        case sf::Event::KeyPressed:
            if (event.key.code == sf::Keyboard::Q) {
                window.close();
            }
            if (event.key.code == sf::Keyboard::F) {
                if (!isFullscreen) {
                    window.create(desktop, "SFML Image Viewer", sf::Style::Fullscreen);
                } else {
                    window.create(sf::VideoMode(640, 480), "SFML Image Viewer");
                }
                isFullscreen = !isFullscreen;
                break;
            }

        default:
            break;
        }
    }
}

void Window::getLetterboxView()
{
    float windowRatio = window.getSize().x / static_cast<float>(window.getSize().y);
    float viewRatio = view.getSize().x / static_cast<float>(view.getSize().y);

    sf::Vector2f size;
    sf::Vector2f pos;

    if (windowRatio > viewRatio) {
        size.x = viewRatio / windowRatio;
        pos.x = (1.0f - size.x) / 2.0f;
        size.y = 1.0f;
        pos.y = 0.0f;
    } else {
        size.y = windowRatio / viewRatio;
        pos.y = (1.0f - size.y) / 2.0f;
        size.x = 1.0f;
        pos.x = 0.0f;
    }

    view.setViewport(sf::FloatRect(pos.x, pos.y, size.x, size.y));
}

std::vector<std::string> Window::getFilesInDirectory()
{
    std::vector<std::string> v;
    auto dir = boost::filesystem::current_path();

    boost::filesystem::path p(dir);
    boost::filesystem::directory_iterator start(p);
    boost::filesystem::directory_iterator end;
    std::transform(start, end, std::back_inserter(v), path_leaf_string());

    return v;
}
<commit_msg>Make sure getFilesInDirectory() is run asynchronously<commit_after>/*
 * Copyright (c) 2017 Akil Darjean (adarjean@uh.edu)
 * Distributed under the MIT License.
 * See accompanying file LICENSE.md or copy at http://opensource.org/licenses/MIT
 */

#include "window.h"
#include <SFML/Graphics.hpp>
#include <boost/filesystem.hpp>
#include <exception>
#include <future>

struct path_leaf_string {
    std::string operator()(const boost::filesystem::directory_entry& entry) const
    {
        return entry.path().leaf().string();
    }
};

Window::Window(const std::string&& filename)
{
    this->filename = filename;
    this->isFullscreen = false;

    load();
    init();
    draw();
}

void Window::load()
{
    // Run a seperate thread to get a list of all files in the directory
    auto f = std::async(std::launch::async, &Window::getFilesInDirectory, this);

    if (!texture.loadFromFile(filename)) {
        throw std::runtime_error("Error: Image not found");
    }
    texture.setSmooth(true);
    sprite.setTexture(texture);

    files = f.get();
}

void Window::init()
{
    desktop = sf::VideoMode::getDesktopMode();

    window.create(sf::VideoMode(640, 480), "SFML Image Viewer");
    window.setKeyRepeatEnabled(false);
    window.setFramerateLimit(framerate);

    // Initialize view
    view.reset(sf::FloatRect(
        0.0f,
        0.0f,
        static_cast<float>(texture.getSize().x),
        static_cast<float>(texture.getSize().y)));
}

void Window::draw()
{
    while (window.isOpen()) {
        checkEvents();

        window.clear();
        window.setView(view);
        window.draw(sprite);
        window.display();
    }
}

void Window::checkEvents()
{
    sf::Event event;
    while (window.pollEvent(event)) {
        switch (event.type) {
        case sf::Event::EventType::Closed:
            window.close();
            break;

        case sf::Event::EventType::Resized:
            getLetterboxView();
            break;

        case sf::Event::KeyPressed:
            if (event.key.code == sf::Keyboard::Q) {
                window.close();
            }
            if (event.key.code == sf::Keyboard::F) {
                if (!isFullscreen) {
                    window.create(desktop, "SFML Image Viewer", sf::Style::Fullscreen);
                } else {
                    window.create(sf::VideoMode(640, 480), "SFML Image Viewer");
                }
                isFullscreen = !isFullscreen;
                break;
            }

        default:
            break;
        }
    }
}

void Window::getLetterboxView()
{
    float windowRatio = window.getSize().x / static_cast<float>(window.getSize().y);
    float viewRatio = view.getSize().x / static_cast<float>(view.getSize().y);

    sf::Vector2f size;
    sf::Vector2f pos;

    if (windowRatio > viewRatio) {
        size.x = viewRatio / windowRatio;
        pos.x = (1.0f - size.x) / 2.0f;
        size.y = 1.0f;
        pos.y = 0.0f;
    } else {
        size.y = windowRatio / viewRatio;
        pos.y = (1.0f - size.y) / 2.0f;
        size.x = 1.0f;
        pos.x = 0.0f;
    }

    view.setViewport(sf::FloatRect(pos.x, pos.y, size.x, size.y));
}

std::vector<std::string> Window::getFilesInDirectory()
{
    std::vector<std::string> v;
    auto dir = boost::filesystem::current_path();

    boost::filesystem::path p(dir);
    boost::filesystem::directory_iterator start(p);
    boost::filesystem::directory_iterator end;
    std::transform(start, end, std::back_inserter(v), path_leaf_string());

    return v;
}
<|endoftext|>


<commit_before>/**
*  Copyright (C) 2018 3D Repo Ltd
*
*  This program is free software: you can redistribute it and/or modify
*  it under the terms of the GNU Affero General Public License as
*  published by the Free Software Foundation, either version 3 of the
*  License, or (at your option) any later version.
*
*  This program 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 Affero General Public License for more details.
*
*  You should have received a copy of the GNU Affero General Public License
*  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <OdaCommon.h>
#include <OdString.h>

#include <toString.h>
#include <DgLevelTableRecord.h>

#include "geometry_dumper.h"
#include "../../../../core/model/bson/repo_bson_factory.h"
using namespace repo::manipulator::modelconvertor::odaHelper;

void GeometryDumper::triangleOut(const OdInt32* p3Vertices, const OdGeVector3d* pNormal)
{
	const OdGePoint3d*  pVertexDataList = vertexDataList();
	const OdGeVector3d* pNormals = NULL;

	if ((pVertexDataList + p3Vertices[0]) != (pVertexDataList + p3Vertices[1]) &&
		(pVertexDataList + p3Vertices[0]) != (pVertexDataList + p3Vertices[2]) &&
		(pVertexDataList + p3Vertices[1]) != (pVertexDataList + p3Vertices[2]))
	{
		std::vector<repo::lib::RepoVector3D64> vertices;
		for (int i = 0; i < 3; ++i)
		{
			vertices.push_back({ pVertexDataList[p3Vertices[i]].x , pVertexDataList[p3Vertices[i]].y, pVertexDataList[p3Vertices[i]].z });
		}
		collector->addFace(vertices);
	}
}

double GeometryDumper::deviation(
	const OdGiDeviationType deviationType,
	const OdGePoint3d& pointOnCurve) const {
	return 0;
}

VectoriseDevice* GeometryDumper::device()
{
	return static_cast<VectoriseDevice*>(OdGsBaseVectorizeView::device());
}

std::string convertToStdString(const OdString &value) {
	return (LPCTSTR)value;
}

bool GeometryDumper::doDraw(OdUInt32 i, const OdGiDrawable* pDrawable)
{
	OdDgElementPtr pElm = OdDgElement::cast(pDrawable);
	auto currentItem = pElm;
	auto previousItem = pElm;
	while (currentItem->ownerId()) {
		previousItem = currentItem;
		auto ownerId = currentItem->ownerId();
		auto ownerItem = OdDgElement::cast(ownerId.openObject(OdDg::kForRead));
		currentItem = ownerItem;
	}

	//We want to group meshes together up to 1 below the top.
	OdString groupID = toString(previousItem->elementId().getHandle());
	collector->setMeshGroup(convertToStdString(groupID));

	OdString sHandle = pElm->isDBRO() ? toString(pElm->elementId().getHandle()) : toString(OD_T("non-DbResident"));
	collector->setNextMeshName(convertToStdString(sHandle));

	OdGiSubEntityTraitsData traits = effectiveTraits();
	OdDgElementId idLevel = traits.layer();
	if (!idLevel.isNull())
	{
		OdDgLevelTableRecordPtr pLevel = idLevel.openObject(OdDg::kForRead);
		collector->setLayer(convertToStdString(pLevel->getName()));
	}
	return OdGsBaseMaterialView::doDraw(i, pDrawable);
}

OdCmEntityColor GeometryDumper::fixByACI(const ODCOLORREF *ids, const OdCmEntityColor &color)
{
	if (color.isByACI() || color.isByDgnIndex())
	{
		return OdCmEntityColor(ODGETRED(ids[color.colorIndex()]), ODGETGREEN(ids[color.colorIndex()]), ODGETBLUE(ids[color.colorIndex()]));
	}
	else if (!color.isByColor())
	{
		return OdCmEntityColor(0, 0, 0);
	}
	return color;
}

OdGiMaterialItemPtr GeometryDumper::fillMaterialCache(
	OdGiMaterialItemPtr prevCache,
	OdDbStub* materialId,
	const OdGiMaterialTraitsData & materialData
) {

	auto id = (OdUInt64)(OdIntPtr)materialId;

	OdGiMaterialColor diffuseColor; OdGiMaterialMap diffuseMap;
	OdGiMaterialColor ambientColor;
	OdGiMaterialColor specularColor; OdGiMaterialMap specularMap; double glossFactor;
	double opacityPercentage; OdGiMaterialMap opacityMap;
	double refrIndex; OdGiMaterialMap refrMap;

	materialData.diffuse(diffuseColor, diffuseMap);
	materialData.ambient(ambientColor);
	materialData.specular(specularColor, specularMap, glossFactor);
	materialData.opacity(opacityPercentage, opacityMap);
	materialData.refraction(refrIndex, refrMap);

	OdGiMaterialMap bumpMap;
	materialData.bump(bumpMap);

	ODCOLORREF colorDiffuse(0), colorAmbient(0), colorSpecular(0);
	if (diffuseColor.color().colorMethod() == OdCmEntityColor::kByColor)
	{
		colorDiffuse = ODTOCOLORREF(diffuseColor.color());
	}
	else if (diffuseColor.color().colorMethod() == OdCmEntityColor::kByACI)
	{
		colorDiffuse = OdCmEntityColor::lookUpRGB((OdUInt8)diffuseColor.color().colorIndex());
	}
	if (ambientColor.color().colorMethod() == OdCmEntityColor::kByColor)
	{
		colorAmbient = ODTOCOLORREF(ambientColor.color());
	}
	else if (ambientColor.color().colorMethod() == OdCmEntityColor::kByACI)
	{
		colorAmbient = OdCmEntityColor::lookUpRGB((OdUInt8)ambientColor.color().colorIndex());
	}
	if (specularColor.color().colorMethod() == OdCmEntityColor::kByColor)
	{
		colorSpecular = ODTOCOLORREF(specularColor.color());
	}
	else if (specularColor.color().colorMethod() == OdCmEntityColor::kByACI)
	{
		colorSpecular = OdCmEntityColor::lookUpRGB((OdUInt8)specularColor.color().colorIndex());
	}

	OdCmEntityColor color = fixByACI(this->device()->getPalette(), effectiveTraits().trueColor());
	repo_material_t material;
	// diffuse
	if (diffuseColor.method() == OdGiMaterialColor::kOverride)
		material.diffuse = { ODGETRED(colorDiffuse) / 255.0f, ODGETGREEN(colorDiffuse) / 255.0f, ODGETBLUE(colorDiffuse) / 255.0f, 1.0f };
	else
		material.diffuse = { color.red() / 255.0f, color.green() / 255.0f, color.blue() / 255.0f, 1.0f };
	/*
	TODO: texture support
	mData.bDiffuseChannelEnabled = (GETBIT(materialData.channelFlags(), OdGiMaterialTraits::kUseDiffuse)) ? true : false;
	if (mData.bDiffuseChannelEnabled && diffuseMap.source() == OdGiMaterialMap::kFile && !diffuseMap.sourceFileName().isEmpty())
	{
	mData.bDiffuseHasTexture = true;
	mData.sDiffuseFileSource = diffuseMap.sourceFileName();
	}*/

	// specular
	if (specularColor.method() == OdGiMaterialColor::kOverride)
		material.specular = { ODGETRED(colorSpecular) / 255.0f, ODGETGREEN(colorSpecular) / 255.0f, ODGETBLUE(colorSpecular) / 255.0f, 1.0f };
	else
		material.specular = { color.red() / 255.0f, color.green() / 255.0f, color.blue() / 255.0f, 1.0f };

	material.shininessStrength = 1 - glossFactor;
	material.shininess = materialData.reflectivity();

	// opacity
	material.opacity = opacityPercentage;

	// refraction
	/*mData.bRefractionChannelEnabled = (GETBIT(materialData.channelFlags(), OdGiMaterialTraits::kUseRefraction)) ? 1 : 0;
	mData.dRefractionIndex = materialData.reflectivity();*/

	// transclucence
	//mData.dTranslucence = materialData.translucence();

	collector->setCurrentMaterial(material);
	collector->stopMeshEntry();
	collector->startMeshEntry();

	return OdGiMaterialItemPtr();
}

void GeometryDumper::init(GeometryCollector *const geoCollector) {
	collector = geoCollector;
}

void GeometryDumper::beginViewVectorization()
{
	OdGsBaseMaterialView::beginViewVectorization();
	setEyeToOutputTransform(getEyeToWorldTransform());

	OdGiGeometrySimplifier::setDrawContext(OdGsBaseMaterialView::drawContext());
	output().setDestGeometry((OdGiGeometrySimplifier&)*this);
}

void GeometryDumper::endViewVectorization()
{
	collector->stopMeshEntry();
	OdGsBaseMaterialView::endViewVectorization();
}

void GeometryDumper::setMode(OdGsView::RenderMode mode)
{
	OdGsBaseVectorizeView::m_renderMode = kGouraudShaded;
	m_regenerationType = kOdGiRenderCommand;
	OdGiGeometrySimplifier::m_renderMode = OdGsBaseVectorizeView::m_renderMode;
}<commit_msg>ISSUE #271 fix travis hopefully.<commit_after>/**
*  Copyright (C) 2018 3D Repo Ltd
*
*  This program is free software: you can redistribute it and/or modify
*  it under the terms of the GNU Affero General Public License as
*  published by the Free Software Foundation, either version 3 of the
*  License, or (at your option) any later version.
*
*  This program 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 Affero General Public License for more details.
*
*  You should have received a copy of the GNU Affero General Public License
*  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <OdaCommon.h>
#include <OdString.h>

#include <toString.h>
#include <DgLevelTableRecord.h>

#include "geometry_dumper.h"
#include "../../../../core/model/bson/repo_bson_factory.h"
using namespace repo::manipulator::modelconvertor::odaHelper;

void GeometryDumper::triangleOut(const OdInt32* p3Vertices, const OdGeVector3d* pNormal)
{
	const OdGePoint3d*  pVertexDataList = vertexDataList();
	const OdGeVector3d* pNormals = NULL;

	if ((pVertexDataList + p3Vertices[0]) != (pVertexDataList + p3Vertices[1]) &&
		(pVertexDataList + p3Vertices[0]) != (pVertexDataList + p3Vertices[2]) &&
		(pVertexDataList + p3Vertices[1]) != (pVertexDataList + p3Vertices[2]))
	{
		std::vector<repo::lib::RepoVector3D64> vertices;
		for (int i = 0; i < 3; ++i)
		{
			vertices.push_back({ pVertexDataList[p3Vertices[i]].x , pVertexDataList[p3Vertices[i]].y, pVertexDataList[p3Vertices[i]].z });
		}
		collector->addFace(vertices);
	}
}

double GeometryDumper::deviation(
	const OdGiDeviationType deviationType,
	const OdGePoint3d& pointOnCurve) const {
	return 0;
}

VectoriseDevice* GeometryDumper::device()
{
	return static_cast<VectoriseDevice*>(OdGsBaseVectorizeView::device());
}

std::string convertToStdString(const OdString &value) {
	const char *ansi = static_cast<const char *>(value);
	return std::string(ansi);
}

bool GeometryDumper::doDraw(OdUInt32 i, const OdGiDrawable* pDrawable)
{
	OdDgElementPtr pElm = OdDgElement::cast(pDrawable);
	auto currentItem = pElm;
	auto previousItem = pElm;
	while (currentItem->ownerId()) {
		previousItem = currentItem;
		auto ownerId = currentItem->ownerId();
		auto ownerItem = OdDgElement::cast(ownerId.openObject(OdDg::kForRead));
		currentItem = ownerItem;
	}

	//We want to group meshes together up to 1 below the top.
	OdString groupID = toString(previousItem->elementId().getHandle());
	collector->setMeshGroup(convertToStdString(groupID));

	OdString sHandle = pElm->isDBRO() ? toString(pElm->elementId().getHandle()) : toString(OD_T("non-DbResident"));
	collector->setNextMeshName(convertToStdString(sHandle));

	OdGiSubEntityTraitsData traits = effectiveTraits();
	OdDgElementId idLevel = traits.layer();
	if (!idLevel.isNull())
	{
		OdDgLevelTableRecordPtr pLevel = idLevel.openObject(OdDg::kForRead);
		collector->setLayer(convertToStdString(pLevel->getName()));
	}
	return OdGsBaseMaterialView::doDraw(i, pDrawable);
}

OdCmEntityColor GeometryDumper::fixByACI(const ODCOLORREF *ids, const OdCmEntityColor &color)
{
	if (color.isByACI() || color.isByDgnIndex())
	{
		return OdCmEntityColor(ODGETRED(ids[color.colorIndex()]), ODGETGREEN(ids[color.colorIndex()]), ODGETBLUE(ids[color.colorIndex()]));
	}
	else if (!color.isByColor())
	{
		return OdCmEntityColor(0, 0, 0);
	}
	return color;
}

OdGiMaterialItemPtr GeometryDumper::fillMaterialCache(
	OdGiMaterialItemPtr prevCache,
	OdDbStub* materialId,
	const OdGiMaterialTraitsData & materialData
) {

	auto id = (OdUInt64)(OdIntPtr)materialId;

	OdGiMaterialColor diffuseColor; OdGiMaterialMap diffuseMap;
	OdGiMaterialColor ambientColor;
	OdGiMaterialColor specularColor; OdGiMaterialMap specularMap; double glossFactor;
	double opacityPercentage; OdGiMaterialMap opacityMap;
	double refrIndex; OdGiMaterialMap refrMap;

	materialData.diffuse(diffuseColor, diffuseMap);
	materialData.ambient(ambientColor);
	materialData.specular(specularColor, specularMap, glossFactor);
	materialData.opacity(opacityPercentage, opacityMap);
	materialData.refraction(refrIndex, refrMap);

	OdGiMaterialMap bumpMap;
	materialData.bump(bumpMap);

	ODCOLORREF colorDiffuse(0), colorAmbient(0), colorSpecular(0);
	if (diffuseColor.color().colorMethod() == OdCmEntityColor::kByColor)
	{
		colorDiffuse = ODTOCOLORREF(diffuseColor.color());
	}
	else if (diffuseColor.color().colorMethod() == OdCmEntityColor::kByACI)
	{
		colorDiffuse = OdCmEntityColor::lookUpRGB((OdUInt8)diffuseColor.color().colorIndex());
	}
	if (ambientColor.color().colorMethod() == OdCmEntityColor::kByColor)
	{
		colorAmbient = ODTOCOLORREF(ambientColor.color());
	}
	else if (ambientColor.color().colorMethod() == OdCmEntityColor::kByACI)
	{
		colorAmbient = OdCmEntityColor::lookUpRGB((OdUInt8)ambientColor.color().colorIndex());
	}
	if (specularColor.color().colorMethod() == OdCmEntityColor::kByColor)
	{
		colorSpecular = ODTOCOLORREF(specularColor.color());
	}
	else if (specularColor.color().colorMethod() == OdCmEntityColor::kByACI)
	{
		colorSpecular = OdCmEntityColor::lookUpRGB((OdUInt8)specularColor.color().colorIndex());
	}

	OdCmEntityColor color = fixByACI(this->device()->getPalette(), effectiveTraits().trueColor());
	repo_material_t material;
	// diffuse
	if (diffuseColor.method() == OdGiMaterialColor::kOverride)
		material.diffuse = { ODGETRED(colorDiffuse) / 255.0f, ODGETGREEN(colorDiffuse) / 255.0f, ODGETBLUE(colorDiffuse) / 255.0f, 1.0f };
	else
		material.diffuse = { color.red() / 255.0f, color.green() / 255.0f, color.blue() / 255.0f, 1.0f };
	/*
	TODO: texture support
	mData.bDiffuseChannelEnabled = (GETBIT(materialData.channelFlags(), OdGiMaterialTraits::kUseDiffuse)) ? true : false;
	if (mData.bDiffuseChannelEnabled && diffuseMap.source() == OdGiMaterialMap::kFile && !diffuseMap.sourceFileName().isEmpty())
	{
	mData.bDiffuseHasTexture = true;
	mData.sDiffuseFileSource = diffuseMap.sourceFileName();
	}*/

	// specular
	if (specularColor.method() == OdGiMaterialColor::kOverride)
		material.specular = { ODGETRED(colorSpecular) / 255.0f, ODGETGREEN(colorSpecular) / 255.0f, ODGETBLUE(colorSpecular) / 255.0f, 1.0f };
	else
		material.specular = { color.red() / 255.0f, color.green() / 255.0f, color.blue() / 255.0f, 1.0f };

	material.shininessStrength = 1 - glossFactor;
	material.shininess = materialData.reflectivity();

	// opacity
	material.opacity = opacityPercentage;

	// refraction
	/*mData.bRefractionChannelEnabled = (GETBIT(materialData.channelFlags(), OdGiMaterialTraits::kUseRefraction)) ? 1 : 0;
	mData.dRefractionIndex = materialData.reflectivity();*/

	// transclucence
	//mData.dTranslucence = materialData.translucence();

	collector->setCurrentMaterial(material);
	collector->stopMeshEntry();
	collector->startMeshEntry();

	return OdGiMaterialItemPtr();
}

void GeometryDumper::init(GeometryCollector *const geoCollector) {
	collector = geoCollector;
}

void GeometryDumper::beginViewVectorization()
{
	OdGsBaseMaterialView::beginViewVectorization();
	setEyeToOutputTransform(getEyeToWorldTransform());

	OdGiGeometrySimplifier::setDrawContext(OdGsBaseMaterialView::drawContext());
	output().setDestGeometry((OdGiGeometrySimplifier&)*this);
}

void GeometryDumper::endViewVectorization()
{
	collector->stopMeshEntry();
	OdGsBaseMaterialView::endViewVectorization();
}

void GeometryDumper::setMode(OdGsView::RenderMode mode)
{
	OdGsBaseVectorizeView::m_renderMode = kGouraudShaded;
	m_regenerationType = kOdGiRenderCommand;
	OdGiGeometrySimplifier::m_renderMode = OdGsBaseVectorizeView::m_renderMode;
}<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Jolla Ltd.
** Contact: Vesa-Matti Hartikainen <vesa-matti.hartikainen@jollamobile.com>
**
****************************************************************************/

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "bookmarkmanager.h"
#include <QDebug>
#include <QFile>
#include <QTextStream>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>
#include <QRegularExpression>
#include <MGConfItem>

#include "bookmark.h"
#include "browserpaths.h"

BookmarkManager::BookmarkManager()
  : QObject(nullptr)
{
    m_clearBookmarksConfItem = new MGConfItem("/apps/sailfish-browser/actions/clear_bookmarks", this);

    clearBookmarks();

    connect(m_clearBookmarksConfItem.data(), &MGConfItem::valueChanged,
            this, &BookmarkManager::clearBookmarks);
}

BookmarkManager* BookmarkManager::instance()
{
    static BookmarkManager* singleton;
    if (!singleton) {
        singleton = new BookmarkManager();
    }

    return singleton;
}

void BookmarkManager::save(const QList<Bookmark*> & bookmarks)
{
    QString dataLocation = BrowserPaths::dataLocation();
    if (dataLocation.isNull()) {
        return;
    }
    QString path = dataLocation + "/bookmarks.json";
    QFile file(path);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qWarning() << "Can't create file " << path;
        return;
    }
    QTextStream out(&file);
    QJsonArray items;

    foreach (Bookmark* bookmark, bookmarks) {
        QJsonObject title;
        title.insert("url", QJsonValue(bookmark->url()));
        title.insert("title", QJsonValue(bookmark->title()));
        title.insert("favicon", QJsonValue(bookmark->favicon()));
        title.insert("hasTouchIcon", QJsonValue(bookmark->hasTouchIcon()));
        items.append(QJsonValue(title));
    }
    QJsonDocument doc(items);
    out.setCodec("UTF-8");
    out << doc.toJson();
    file.close();
}

void BookmarkManager::clear()
{
    save(QList<Bookmark*>());
    emit cleared();
}

QList<Bookmark*> BookmarkManager::load() {
    QList<Bookmark*> bookmarks;
    QString bookmarkFile = BrowserPaths::dataLocation() + "/bookmarks.json";
    QScopedPointer<QFile> file(new QFile(bookmarkFile));

    if (!file->open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "Unable to open bookmarks " << bookmarkFile;

        file.reset(new QFile(QLatin1Literal("/usr/share/sailfish-browser/default-content/bookmarks.json")));
        if (!file->open(QIODevice::ReadOnly | QIODevice::Text)) {
            qWarning() << "Unable to open bookmarks defaults";
            return bookmarks;
        }
    }

    QJsonDocument doc = QJsonDocument::fromJson(file->readAll());
    if (doc.isArray()) {
        QJsonArray array = doc.array();
        QJsonArray::iterator i;
        for (i=array.begin(); i != array.end(); ++i) {
            if ((*i).isObject()) {
                QJsonObject obj = (*i).toObject();
                QString url = obj.value("url").toString();
                QString favicon = obj.value("favicon").toString();
                Bookmark* m = new Bookmark(obj.value("title").toString(),
                                           url,
                                           favicon,
                                           obj.value("hasTouchIcon").toBool());
                bookmarks.append(m);
            }
        }
    } else {
        qWarning() << "Bookmarks.json should be an array of items";
    }
    file->close();
    return bookmarks;
}

void BookmarkManager::clearBookmarks()
{
    if (m_clearBookmarksConfItem->value(false).toBool()) {
        clear();
        m_clearBookmarksConfItem->set(false);
    }
}
<commit_msg>[browser] Use for-range to iterate over bookmarks. JB#53083<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Jolla Ltd.
** Contact: Vesa-Matti Hartikainen <vesa-matti.hartikainen@jollamobile.com>
**
****************************************************************************/

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "bookmarkmanager.h"
#include <QDebug>
#include <QFile>
#include <QTextStream>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>
#include <QRegularExpression>
#include <MGConfItem>

#include "bookmark.h"
#include "browserpaths.h"

BookmarkManager::BookmarkManager()
  : QObject(nullptr)
{
    m_clearBookmarksConfItem = new MGConfItem("/apps/sailfish-browser/actions/clear_bookmarks", this);

    clearBookmarks();

    connect(m_clearBookmarksConfItem.data(), &MGConfItem::valueChanged,
            this, &BookmarkManager::clearBookmarks);
}

BookmarkManager* BookmarkManager::instance()
{
    static BookmarkManager* singleton;
    if (!singleton) {
        singleton = new BookmarkManager();
    }

    return singleton;
}

void BookmarkManager::save(const QList<Bookmark*> & bookmarks)
{
    QString dataLocation = BrowserPaths::dataLocation();
    if (dataLocation.isNull()) {
        return;
    }
    QString path = dataLocation + "/bookmarks.json";
    QFile file(path);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qWarning() << "Can't create file " << path;
        return;
    }
    QTextStream out(&file);
    QJsonArray items;

    foreach (Bookmark* bookmark, bookmarks) {
        QJsonObject title;
        title.insert("url", QJsonValue(bookmark->url()));
        title.insert("title", QJsonValue(bookmark->title()));
        title.insert("favicon", QJsonValue(bookmark->favicon()));
        title.insert("hasTouchIcon", QJsonValue(bookmark->hasTouchIcon()));
        items.append(QJsonValue(title));
    }
    QJsonDocument doc(items);
    out.setCodec("UTF-8");
    out << doc.toJson();
    file.close();
}

void BookmarkManager::clear()
{
    save(QList<Bookmark*>());
    emit cleared();
}

QList<Bookmark*> BookmarkManager::load() {
    QList<Bookmark*> bookmarks;
    QString bookmarkFile = BrowserPaths::dataLocation() + "/bookmarks.json";
    QScopedPointer<QFile> file(new QFile(bookmarkFile));

    if (!file->open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "Unable to open bookmarks " << bookmarkFile;

        file.reset(new QFile(QLatin1Literal("/usr/share/sailfish-browser/default-content/bookmarks.json")));
        if (!file->open(QIODevice::ReadOnly | QIODevice::Text)) {
            qWarning() << "Unable to open bookmarks defaults";
            return bookmarks;
        }
    }

    QJsonDocument doc = QJsonDocument::fromJson(file->readAll());
    if (doc.isArray()) {
        QJsonArray array = doc.array();
        for (const QJsonValue &value : array) {
            if (value.isObject()) {
                QJsonObject obj = value.toObject();
                QString url = obj.value("url").toString();
                QString favicon = obj.value("favicon").toString();
                Bookmark* m = new Bookmark(obj.value("title").toString(),
                                           url,
                                           favicon,
                                           obj.value("hasTouchIcon").toBool());
                bookmarks.append(m);
            }
        }
    } else {
        qWarning() << "Bookmarks.json should be an array of items";
    }
    file->close();
    return bookmarks;
}

void BookmarkManager::clearBookmarks()
{
    if (m_clearBookmarksConfItem->value(false).toBool()) {
        clear();
        m_clearBookmarksConfItem->set(false);
    }
}
<|endoftext|>


<commit_before>/*
* Copyright 2015 BrewPi/Elco Jacobs.
*
* This file is part of BrewPi.
*
* BrewPi 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.
*
* BrewPi 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 BrewPi.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <boost/test/unit_test.hpp>

#include "runner.h"
#include <string>

#include "ActuatorInterfaces.h"
#include "ActuatorMocks.h"
#include "ActuatorTimeLimited.h"
#include "ActuatorMutexDriver.h"
#include "ActuatorPwm.h"
#include "ActuatorSetPoint.h"
#include "TempSensorMock.h"
#include "TempSensor.h"
#include "Pid.h"
#include "SetPoint.h"
#include "Control.h"
#include "json_writer.h"

BOOST_AUTO_TEST_SUITE(EsjTest)

BOOST_AUTO_TEST_CASE(serialize_nested_actuators) {
    //ActuatorBool * actBool = new ActuatorBool();
    //ActuatorTimeLimited * actTl = new ActuatorTimeLimited(actBool, 10, 20);
    ActuatorBool * boolAct1 = new ActuatorBool();
    ActuatorMutexDriver * mutexAct1 = new ActuatorMutexDriver(boolAct1);
    ActuatorPwm * act1 = new ActuatorPwm (mutexAct1, 20);

    std::string json;

    json = JSON::producer<ActuatorPwm>::convert(act1);

    /* With some extra whitespace, the valid output looks like this:
{
    "class": "ActuatorPwm",
    "variables": {
        "value": 0.0000,
        "period": 20000,
        "minVal": 0.0000,
        "maxVal": 100.0000,
        "target": {
            "class": "ActuatorMutexDriver",
            "variables": {
                "mutexGroup": null,
                "target": {
                    "class": "ActuatorBool",
                    "variables": {
                        "state": false
                    }
                }
            }
        }
    }
}
*/

    std::string valid = R"({"class":"ActuatorPwm","variables":{"value":0.0000,)"
                        R"("period":20000,"minVal":0.0000,"maxVal":100.0000,)"
                        R"("target":{"class":"ActuatorMutexDriver",)"
                        R"("variables":{"mutexGroup":null,)"
                        R"("target":{"class":"ActuatorBool",)"
                        R"("variables":{"state":false}}}}}})";
    BOOST_CHECK_EQUAL(valid, json);
}

BOOST_AUTO_TEST_CASE(serialize_nested_actuators2) {
    ActuatorDigital* coolerPin = new ActuatorBool();
    ActuatorDigital* coolerTimeLimited = new ActuatorTimeLimited(coolerPin, 120, 180); // 2 min minOn time, 3 min minOff
    ActuatorMutexGroup * mutex = new ActuatorMutexGroup();
    ActuatorDigital* coolerMutex = new ActuatorMutexDriver(coolerTimeLimited, mutex);
    ActuatorRange* cooler = new ActuatorPwm(coolerMutex, 600); // period 10 min

    std::string json;

    json = JSON::producer<ActuatorRange>::convert(cooler);

/* With some extra whitespace, the valid output looks like this:
{
    "class": "ActuatorPwm",
    "variables": {
        "value": 0.0000,
        "period": 600000,
        "minVal": 0.0000,
        "maxVal": 100.0000,
        "target": {
            "class": "ActuatorMutexDriver",
            "variables": {
                "mutexGroup": {
                    "class": "ActuatorMutexGroup",
                    "variables": {
                        "deadTime": 0,
                        "lastActiveTime": 0
                    }
                },
                "target": {
                    "class": "ActuatorTimeLimited",
                    "variables": {
                        "minOnTime": 120,
                        "minOffTime": 180,
                        "maxOnTime": 65535,
                        "active": false,
                        "target": {
                            "class": "ActuatorBool",
                            "variables": {
                                "state": false
                            }
                        }
                    }
                }
            }
        }
    }
}
*/

    std::string valid = R"({"class":"ActuatorPwm","variables":{"value":0.0000,)"
                        R"("period":600000,"minVal":0.0000,"maxVal":100.0000,)"
                        R"("target":{"class":"ActuatorMutexDriver",)"
                        R"("variables":{"mutexGroup":{"class":"ActuatorMutexGroup",)"
                        R"("variables":{"deadTime":0,"lastActiveTime":0}},)"
                        R"("target":{"class":"ActuatorTimeLimited",)"
                        R"("variables":{"minOnTime":120,"minOffTime":180,"maxOnTime":65535,)"
                        R"("active":false,"target":{"class":"ActuatorBool",)"
                        R"("variables":{"state":false}}}}}}}})";

    BOOST_CHECK_EQUAL(valid, json);
}

BOOST_AUTO_TEST_CASE(serialize_setpoint) {
    SetPoint * sp1 = new SetPointSimple();
    SetPoint * sp2 = new SetPointConstant(20.0);

    std::string json = JSON::producer<SetPoint>::convert(sp1);
    std::string valid = R"({"class":"SetPointSimple","variables":{"value":null}})";

    BOOST_CHECK_EQUAL(valid, json);

    json = JSON::producer<SetPoint>::convert(sp2);
    valid = R"({"class":"SetPointConstant","variables":{"value":20.0000}})";

    BOOST_CHECK_EQUAL(valid, json);
}

BOOST_AUTO_TEST_CASE(serialize_ActuatorSetPoint) {
    SetPoint * sp1 = new SetPointSimple();
    SetPoint * sp2 = new SetPointConstant(20.0);
    ActuatorRange * act = new ActuatorSetPoint(sp1, sp2, -10.0, 10.0);
    act->setValue(5.0); // should set sp1 to sp2 + 5.0 = 25.0;

    std::string json = JSON::producer<ActuatorRange>::convert(act);

/* With some extra whitespace, the valid output looks like this:
    {
        "class": "ActuatorSetPoint",
        "variables": {
            "target": {
                "class": "SetPointSimple",
                "variables": {
                    "value": 25.0000
                }
            },
            "reference": {
                "class": "SetPointConstant",
                "variables": {
                    "value": 20.0000
                }
            },
            "minimum": -10.0000,
            "maximum": 10.0000
        }
    }
*/

    std::string valid = R"({"class":"ActuatorSetPoint","variables":{)"
        R"("target":{"class":"SetPointSimple","variables":{"value":25.0000}},)"
        R"("reference":{"class":"SetPointConstant","variables":{)"
        R"("value":20.0000}},"minimum":-10.0000,"maximum":10.0000}})";

    BOOST_CHECK_EQUAL(valid, json);
}

BOOST_AUTO_TEST_CASE(serialize_Pid) {
    TempSensorBasic * sensor = new TempSensorMock(20.0);
    ActuatorDigital * boolAct = new ActuatorBool();
    ActuatorRange * pwmAct = new ActuatorPwm(boolAct,4);
    SetPoint * sp = new SetPointSimple(20.0);
    Pid * pid = new Pid(sensor, pwmAct, sp);

    std::string json = JSON::producer<Pid>::convert(pid);

/* With some extra whitespace, the valid output looks like this:
{
    "class": "Pid",
    "variables": {
        "name":"",
        "setPoint": {
            "class": "SetPointSimple",
            "variables": {
                "value": 20.0000
            }
        },
        "inputSensor": {
            "class": "TempSensorMock",
            "variables": {
                "value": 20.0000,
                "connected": true
            }
        },
        "inputError": 0,
        "Kp": 0.0000,
        "Ti": 0,
        "Td": 0,
        "p": 0.0000,
        "i": 0.0000,
        "d": 0.0000,
        "actuatorIsNegative": false,
        "outputActuator": {
            "class": "ActuatorPwm",
            "variables": {
                "value": 0.0000,
                "period": 4000,
                "minVal": 0.0000,
                "maxVal": 100.0000,
                "target": {
                    "class": "ActuatorBool",
                    "variables": {
                        "state": false
                    }
                }
            }
        }
    }
}
*/

    std::string valid = R"({"class":"Pid","variables":{"name":"",)"
        R"("setPoint":{"class":"SetPointSimple","variables":{"value":20.0000}},)"
        R"("inputSensor":{"class":"TempSensorMock","variables":{"value":20.0000,"connected":true}},)"
        R"("inputError":0.0000,"Kp":0.0000,"Ti":0,"Td":0,"p":0.0000,"i":0.0000,"d":0.0000,)"
        R"("actuatorIsNegative":false,"outputActuator":{"class":"ActuatorPwm",)"
        R"("variables":{"value":0.0000,"period":4000,"minVal":0.0000,"maxVal":100.0000,)"
        R"("target":{"class":"ActuatorBool","variables":{"state":false}}}}}})";

    BOOST_CHECK_EQUAL(valid, json);
}

BOOST_AUTO_TEST_CASE(serialize_TempSensor) {
    TempSensorBasic * s = new TempSensorMock(20.0);
    TempSensor * sensor = new TempSensor(s, "test");

    std::string json = JSON::producer<TempSensor>::convert(sensor);
    std::string valid = R"({"class":"TempSensor","variables":{"name":"test","sensor":{)"
        R"("class":"TempSensorMock","variables":{"value":20.0000,"connected":true}}}})";

    BOOST_CHECK_EQUAL(valid, json);
}

BOOST_AUTO_TEST_CASE(serialize_control) {

    Control * control = new Control();

    std::string json;

    json = JSON::producer<Control>::convert(control);

    BOOST_TEST_MESSAGE("Control JSON = " << json); // use --log_level=all to see in stdout
}

BOOST_AUTO_TEST_SUITE_END()

<commit_msg>fixup! Added enable/disable to PID class and updated SetMode<commit_after>/*
* Copyright 2015 BrewPi/Elco Jacobs.
*
* This file is part of BrewPi.
*
* BrewPi 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.
*
* BrewPi 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 BrewPi.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <boost/test/unit_test.hpp>

#include "runner.h"
#include <string>

#include "ActuatorInterfaces.h"
#include "ActuatorMocks.h"
#include "ActuatorTimeLimited.h"
#include "ActuatorMutexDriver.h"
#include "ActuatorPwm.h"
#include "ActuatorSetPoint.h"
#include "TempSensorMock.h"
#include "TempSensor.h"
#include "Pid.h"
#include "SetPoint.h"
#include "Control.h"
#include "json_writer.h"

BOOST_AUTO_TEST_SUITE(EsjTest)

BOOST_AUTO_TEST_CASE(serialize_nested_actuators) {
    //ActuatorBool * actBool = new ActuatorBool();
    //ActuatorTimeLimited * actTl = new ActuatorTimeLimited(actBool, 10, 20);
    ActuatorBool * boolAct1 = new ActuatorBool();
    ActuatorMutexDriver * mutexAct1 = new ActuatorMutexDriver(boolAct1);
    ActuatorPwm * act1 = new ActuatorPwm (mutexAct1, 20);

    std::string json;

    json = JSON::producer<ActuatorPwm>::convert(act1);

    /* With some extra whitespace, the valid output looks like this:
{
    "class": "ActuatorPwm",
    "variables": {
        "value": 0.0000,
        "period": 20000,
        "minVal": 0.0000,
        "maxVal": 100.0000,
        "target": {
            "class": "ActuatorMutexDriver",
            "variables": {
                "mutexGroup": null,
                "target": {
                    "class": "ActuatorBool",
                    "variables": {
                        "state": false
                    }
                }
            }
        }
    }
}
*/

    std::string valid = R"({"class":"ActuatorPwm","variables":{"value":0.0000,)"
                        R"("period":20000,"minVal":0.0000,"maxVal":100.0000,)"
                        R"("target":{"class":"ActuatorMutexDriver",)"
                        R"("variables":{"mutexGroup":null,)"
                        R"("target":{"class":"ActuatorBool",)"
                        R"("variables":{"state":false}}}}}})";
    BOOST_CHECK_EQUAL(valid, json);
}

BOOST_AUTO_TEST_CASE(serialize_nested_actuators2) {
    ActuatorDigital* coolerPin = new ActuatorBool();
    ActuatorDigital* coolerTimeLimited = new ActuatorTimeLimited(coolerPin, 120, 180); // 2 min minOn time, 3 min minOff
    ActuatorMutexGroup * mutex = new ActuatorMutexGroup();
    ActuatorDigital* coolerMutex = new ActuatorMutexDriver(coolerTimeLimited, mutex);
    ActuatorRange* cooler = new ActuatorPwm(coolerMutex, 600); // period 10 min

    std::string json;

    json = JSON::producer<ActuatorRange>::convert(cooler);

/* With some extra whitespace, the valid output looks like this:
{
    "class": "ActuatorPwm",
    "variables": {
        "value": 0.0000,
        "period": 600000,
        "minVal": 0.0000,
        "maxVal": 100.0000,
        "target": {
            "class": "ActuatorMutexDriver",
            "variables": {
                "mutexGroup": {
                    "class": "ActuatorMutexGroup",
                    "variables": {
                        "deadTime": 0,
                        "lastActiveTime": 0
                    }
                },
                "target": {
                    "class": "ActuatorTimeLimited",
                    "variables": {
                        "minOnTime": 120,
                        "minOffTime": 180,
                        "maxOnTime": 65535,
                        "active": false,
                        "target": {
                            "class": "ActuatorBool",
                            "variables": {
                                "state": false
                            }
                        }
                    }
                }
            }
        }
    }
}
*/

    std::string valid = R"({"class":"ActuatorPwm","variables":{"value":0.0000,)"
                        R"("period":600000,"minVal":0.0000,"maxVal":100.0000,)"
                        R"("target":{"class":"ActuatorMutexDriver",)"
                        R"("variables":{"mutexGroup":{"class":"ActuatorMutexGroup",)"
                        R"("variables":{"deadTime":0,"lastActiveTime":0}},)"
                        R"("target":{"class":"ActuatorTimeLimited",)"
                        R"("variables":{"minOnTime":120,"minOffTime":180,"maxOnTime":65535,)"
                        R"("active":false,"target":{"class":"ActuatorBool",)"
                        R"("variables":{"state":false}}}}}}}})";

    BOOST_CHECK_EQUAL(valid, json);
}

BOOST_AUTO_TEST_CASE(serialize_setpoint) {
    SetPoint * sp1 = new SetPointSimple();
    SetPoint * sp2 = new SetPointConstant(20.0);

    std::string json = JSON::producer<SetPoint>::convert(sp1);
    std::string valid = R"({"class":"SetPointSimple","variables":{"value":null}})";

    BOOST_CHECK_EQUAL(valid, json);

    json = JSON::producer<SetPoint>::convert(sp2);
    valid = R"({"class":"SetPointConstant","variables":{"value":20.0000}})";

    BOOST_CHECK_EQUAL(valid, json);
}

BOOST_AUTO_TEST_CASE(serialize_ActuatorSetPoint) {
    SetPoint * sp1 = new SetPointSimple();
    SetPoint * sp2 = new SetPointConstant(20.0);
    ActuatorRange * act = new ActuatorSetPoint(sp1, sp2, -10.0, 10.0);
    act->setValue(5.0); // should set sp1 to sp2 + 5.0 = 25.0;

    std::string json = JSON::producer<ActuatorRange>::convert(act);

/* With some extra whitespace, the valid output looks like this:
    {
        "class": "ActuatorSetPoint",
        "variables": {
            "target": {
                "class": "SetPointSimple",
                "variables": {
                    "value": 25.0000
                }
            },
            "reference": {
                "class": "SetPointConstant",
                "variables": {
                    "value": 20.0000
                }
            },
            "minimum": -10.0000,
            "maximum": 10.0000
        }
    }
*/

    std::string valid = R"({"class":"ActuatorSetPoint","variables":{)"
        R"("target":{"class":"SetPointSimple","variables":{"value":25.0000}},)"
        R"("reference":{"class":"SetPointConstant","variables":{)"
        R"("value":20.0000}},"minimum":-10.0000,"maximum":10.0000}})";

    BOOST_CHECK_EQUAL(valid, json);
}

BOOST_AUTO_TEST_CASE(serialize_Pid) {
    TempSensorBasic * sensor = new TempSensorMock(20.0);
    ActuatorDigital * boolAct = new ActuatorBool();
    ActuatorRange * pwmAct = new ActuatorPwm(boolAct,4);
    SetPoint * sp = new SetPointSimple(20.0);
    Pid * pid = new Pid(sensor, pwmAct, sp);

    std::string json = JSON::producer<Pid>::convert(pid);

/* With some extra whitespace, the valid output looks like this:
{
    "class": "Pid",
    "variables": {
        "name":"",
        "enabled":true,
        "setPoint": {
            "class": "SetPointSimple",
            "variables": {
                "value": 20.0000
            }
        },
        "inputSensor": {
            "class": "TempSensorMock",
            "variables": {
                "value": 20.0000,
                "connected": true
            }
        },
        "inputError": 0,
        "Kp": 0.0000,
        "Ti": 0,
        "Td": 0,
        "p": 0.0000,
        "i": 0.0000,
        "d": 0.0000,
        "actuatorIsNegative": false,
        "outputActuator": {
            "class": "ActuatorPwm",
            "variables": {
                "value": 0.0000,
                "period": 4000,
                "minVal": 0.0000,
                "maxVal": 100.0000,
                "target": {
                    "class": "ActuatorBool",
                    "variables": {
                        "state": false
                    }
                }
            }
        }
    }
}
*/

    std::string valid = R"({"class":"Pid","variables":{"name":"","enabled":true,)"
        R"("setPoint":{"class":"SetPointSimple","variables":{"value":20.0000}},)"
        R"("inputSensor":{"class":"TempSensorMock","variables":{"value":20.0000,"connected":true}},)"
        R"("inputError":0.0000,"Kp":0.0000,"Ti":0,"Td":0,"p":0.0000,"i":0.0000,"d":0.0000,)"
        R"("actuatorIsNegative":false,"outputActuator":{"class":"ActuatorPwm",)"
        R"("variables":{"value":0.0000,"period":4000,"minVal":0.0000,"maxVal":100.0000,)"
        R"("target":{"class":"ActuatorBool","variables":{"state":false}}}}}})";

    BOOST_CHECK_EQUAL(valid, json);
}

BOOST_AUTO_TEST_CASE(serialize_TempSensor) {
    TempSensorBasic * s = new TempSensorMock(20.0);
    TempSensor * sensor = new TempSensor(s, "test");

    std::string json = JSON::producer<TempSensor>::convert(sensor);
    std::string valid = R"({"class":"TempSensor","variables":{"name":"test","sensor":{)"
        R"("class":"TempSensorMock","variables":{"value":20.0000,"connected":true}}}})";

    BOOST_CHECK_EQUAL(valid, json);
}

BOOST_AUTO_TEST_CASE(serialize_control) {

    Control * control = new Control();

    std::string json;

    json = JSON::producer<Control>::convert(control);

    BOOST_TEST_MESSAGE("Control JSON = " << json); // use --log_level=all to see in stdout
}

BOOST_AUTO_TEST_SUITE_END()

<|endoftext|>