<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Philipp Kerling <pkerling@casix.org>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#pragma once

#include <bitset>
#include <type_traits>

namespace Util {

    /**
     * Provide information about a custom enum class type
     *
     * Needed only by \ref EnumClassBitset.
     *
     * Has to have exactly one static const element named \c max of type T that
     * equals the last possible value of the enumeration type.
     *
     * \tparam T enum class type to describe
     */
    template<typename T>
    struct EnumTraits;

    /**
     * std::bitset for enum class types
     *
     * Provides a type-safe interface to std::bitset when used with enum class types.
     * \ref EnumTraits must be specialized for the enum type.
     * This also provides an iterator interface for easy enumeration of all members
     * in the set with range-based for loops.
     *
     * Most operations from std::bitset are provided except the shift operators
     * which should not be particularly useful on enum class sets.
     * The boolean "value" of an enumeration member in the context of this class means
     * whether it is part of the set.
     *
     * Inspired by http://stackoverflow.com/questions/17350214/using-enum-class-with-stdbitset
     *
     * Example:
     * \code{.cpp}
     * enum class ConntrackState {
     *     NEW,
     *     ESTABLISHED,
     *     RELATED
     * };
     *
     * namespace Util {
     *     template<>
     *     struct EnumTraits<ConntrackState> {
     *         static constexpr ConntrackState max = ConntrackState::RELATED;
     *     };
     * }
     *
     * typedef EnumClassBitset<ConntrackState> ConntrackStateSet;
     *
     * void example() {
     *     ConntrackStateSet states;
     *     states.set(ConntrackState::NEW);
     *     states.set(ConntrackState::ESTABLISHED);
     *     bool result = states.test(ConntrackState::NEW);
     *     std::cout << result << std::endl;    // 1
     *     for (auto state : states) {
     *         switch (state) {
     *             case ConntrackState::NEW:
     *                 std::cout << "NEW is in the set" << std::endl;         // will be output
     *                 break;
     *             case ConntrackState::ESTABLISHED:
     *                 std::cout << "ESTABLISHED is in the set" << std::endl; // will be output
     *                 break;
     *             case ConntrackState::RELATED:
     *                 std::cout << "RELATED is in the set" << std::endl;     // will not be output
     *                 break;
     *         }
     *     }
     * }
     * \endcode
     *
     * \tparam T enum class type
     */
    template<typename T>
    class EnumClassBitset
    {
    public:
        /// Type of the bitset implementation
        typedef std::bitset<static_cast<std::size_t>(EnumTraits<T>::max)> ImplType;

    private:
        /// Implementation of the bitset
        ImplType mBitset;

        /**
         * Cast the enum class type away to use it as an offset into the bitset
         * \param member enumeration member to convert
         * \return member casted to std::size_t
         */
        inline std::size_t enumIndex(T member) const
        {
            return static_cast<std::size_t>(member);
        }

    public:
        /**
         * Readonly iterator for elements in the set
         */
        struct iterator : std::iterator<std::forward_iterator_tag, T>
        {
        private:
            /// Enum set the iterator belongs to
            EnumClassBitset const & bitset;
            /// Index into the set of the current value
            std::size_t index;
            /// Index cast to T
            T value;

            /**
             * Private constructor for begin() and end()
             *
             * This constructor can be used to generate an invalid iterator when
             * \c argIndex is set to an element that is not inside the set.
             * To find the first correct element, use \ref findNext.
             *
             * \param argBitset enum set the iterator belongs to
             * \param argIndex index into the set of the current value
             */
            iterator(EnumClassBitset const & argBitset, std::size_t argIndex)
            : bitset(argBitset), index(argIndex)
            {
                value = static_cast<T> (index);
            }

            /**
             * Starting with the current index, find the first index
             * that corresponds to an element actually in the set
             *
             * If none is found, \c index is bitset.size(), which should be equivalent
             * to bitset.end() as iterator.
             */
            void findNext()
            {
                while (index < bitset.size()) {
                    value = static_cast<T> (index);
                    if (bitset.test(value)) {
                        break;
                    }
                    index++;
                };
            }

            friend class EnumClassBitset;

        public:
            /**
             * Get the enumeration member this iterator represents
             */
            T& operator*()
            {
                return value;
            }
            /**
             * Advance the iterator
             * \return iterator for the next enumeration member in the set, or
             *         a past-the-end iterator
             */
            iterator& operator++()
            {
                index++;
                findNext();
                return *this;
            }
            /**
             * Compare with another iterator for equality
             * \param other other iterator
             * \return \c true if the iterators point to the same element in the same set, \c false otherwise
             */
            bool operator==(iterator const & other) const
            {
                return (std::addressof(bitset) == std::addressof(other.bitset)) && (index == other.index);
            }
            /**
             * Compare with another iterator for inequality
             * \param other other iterator
             * \return \c false if the iterators point to the same element in the same set, \c true otherwise
             */
            bool operator!=(iterator const & other) const
            {
                return !((*this) == other);
            }
        };

        typedef typename ImplType::reference reference;

        /**
         * Default constructor
         *
         * All enumeration members are considered to be not in the set.
         */
        EnumClassBitset()
        {
        }

        /**
         * Compare with another enumeration set for equality
         * \param other set to compare
         * \return \c true if the members of both sets are equivalent, \c false otherwise
         */
        bool operator==(const EnumClassBitset& other) const
        {
            return mBitset == other.mBitset;
        }
        /**
         * Compare with another enumeration set for inequality
         * \param other set to compare
         * \return \c false if the members of both sets are equivalent, \c true otherwise
         */
        bool operator!=(const EnumClassBitset& other) const
        {
            return mBitset != other.mBitset;
        }

        /**
         * Access the enumeration member \c member
         *
         * Unlike \ref test, does not throw exceptions: the behaviour is undefined
         * if \c member is out of bounds.
         *
         * \param member member to access the value of
         * \return \c true if the \c member is in the set, \c false otherwise
         */
        constexpr bool operator[](T member) const
        {
            return mBitset[enumIndex(member)];
        }

        /**
         * Access the enumeration member \c member
         *
         * Unlike \ref test, does not throw exceptions: the behaviour is undefined
         * if \c member is out of bounds.
         *
         * \param member member to access the value of
         * \return an object of type reference, which allows including/excluding
         *         the member from the set by writing to it
         */
        reference operator[](T member)
        {
            return mBitset[enumIndex(member)];
        }

        /**
         * Return the value of the enumeration member \c member
         *
         * \throws std::out_of_range if \c member is not a valid enumeration member
         *
         * \param member member to return the value of
         * \return \c true if the requested enumeration member is in the set, \c false otherwise
         */
        bool test(T member) const
        {
            return mBitset.test(enumIndex(member));
        }

        /**
         * Check if all possible enumeration members are part of the set
         */
        bool all() const
        {
            return mBitset.all();
        }

        /**
         * Check if any of the possible enumeration members are part of the set
         */
        bool any() const
        {
            return mBitset.any();
        }

        /**
         * Check if none of the possible enumeration members are part of the set
         */
        bool none() const
        {
            return mBitset.none();
        }

        /**
         * Get the number of enumeration members that are part of the set
         */
        std::size_t count() const
        {
            return mBitset.count();
        }

        /**
         * Returns the number of enumeration members that the set can hold
         *
         * \return number of members the set can hold, i.e. EnumTraits<T>::max
         */
        constexpr std::size_t size() const
        {
            return mBitset.size();
        }

        /**
         * Set the value of the enumeration member \c member to \c false
         * \param member member to set the value of to \c false
         * \return \c *this
         */
        EnumClassBitset& reset(T member)
        {
            mBitset.reset(enumIndex(member));
            return *this;
        }

        /**
         * Flip the values of all enumeration members, i.e. get the inverse set
         * \return \c *this
         */
        EnumClassBitset& flip()
        {
            mBitset.flip();
            return *this;
        }

        /**
         * Flip the value of the enumeration member \c member
         * \param member member to flip the value of
         * \return \c *this
         */
        EnumClassBitset& flip(T member)
        {
            mBitset.flip(enumIndex(member));
            return *this;
        }

        /**
         * Set the value of the enumeration member \c member to value
         * \param member member to set the value of
         * \param value value to set the enumeration member to
         * \return \c *this
         */
        EnumClassBitset& set(T member, bool value = true)
        {
            mBitset.set(enumIndex(member), value);
            return *this;
        }

        /**
         * Intersect this set with another set
         * \param other another set
         * \return \c *this
         */
        EnumClassBitset& operator&=(EnumClassBitset const & other)
        {
            mBitset &= other.mBitset;
            return *this;
        }

        /**
         * Combine this set with another set
         * \param other another set
         * \return \c *this
         */
        EnumClassBitset& operator|=(EnumClassBitset const & other)
        {
            mBitset |= other.mBitset;
            return *this;
        }

        /**
         * Combine this set with another set using an exclusive-OR relation
         * \param other another set
         * \return \c *this
         */
        EnumClassBitset& operator^=(EnumClassBitset const & other)
        {
            mBitset ^= other.mBitset;
            return *this;
        }

        /**
         * Build the intersection with another set
         * \param other another set
         * \return set with all elements that are set in both this set and \c other
         */
        EnumClassBitset operator&(EnumClassBitset const & other) const
        {
            EnumClassBitset newBitset(*this);
            newBitset.mBitset &= other.mBitset;
            return newBitset;
        }

        /**
         * Build the union set with another set
         * \param other another set
         * \return set with all elements that are set in this set or \c other
         */
        EnumClassBitset operator|(EnumClassBitset const & other) const
        {
            EnumClassBitset newBitset(*this);
            newBitset.mBitset |= other.mBitset;
            return newBitset;
        }

        /**
         * Build the union set with another set
         * \param other another set
         * \return set with all elements that are set in either this set or \c other
         */
        EnumClassBitset operator^(EnumClassBitset const & other) const
        {
            EnumClassBitset newBitset(*this);
            newBitset.mBitset ^= other.mBitset;
            return newBitset;
        }

        /**
         * Get a set with the values of all enumeration members, i.e. the inverse set
         * \sa flip
         * \return set which contains all enumeration members that are not contained
         *         in this set
         */
        EnumClassBitset operator~() const
        {
            EnumClassBitset newBitset(*this);
            newBitset.flip();
            return newBitset;
        }

        /**
         * Constant iterator to the first enumeration member in the set
         */
        iterator begin() const
        {
            auto iter = iterator(*this, 0);
            // Advance to first element in set
            iter.findNext();
            return iter;
        }

        /**
         * Constant iterator past the last enumeration member in the set
         */
        iterator end() const
        {
            return iterator(*this, static_cast<std::size_t>(EnumTraits<T>::max));
        }

        /**
         * Convert the enumeration member set to a raw \c std::bitset
         *
         * \return \c std::bitset instance with bit positions corresponding to
         *         enumeration members in this set set to \c true
         */
        ImplType to_raw_bitset() const
        {
            return mBitset;
        }

    };

}
<commit_msg>Fix off-by-one bitset size bug<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Philipp Kerling <pkerling@casix.org>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#pragma once

#include <bitset>
#include <type_traits>

namespace Util {

    /**
     * Provide information about a custom enum class type
     *
     * Needed only by \ref EnumClassBitset.
     *
     * Has to have exactly one static const element named \c max of type T that
     * equals the last possible value of the enumeration type.
     *
     * \tparam T enum class type to describe
     */
    template<typename T>
    struct EnumTraits;

    /**
     * std::bitset for enum class types
     *
     * Provides a type-safe interface to std::bitset when used with enum class types.
     * \ref EnumTraits must be specialized for the enum type. The enumeration members
     * should start at value 0 and all values should be continuous. Otherwise some space
     * will be wasted in the bitset.
     * This also provides an iterator interface for easy enumeration of all members
     * in the set with range-based for loops.
     *
     * Most operations from std::bitset are provided except the shift operators
     * which should not be particularly useful on enum class sets.
     * The boolean "value" of an enumeration member in the context of this class means
     * whether it is part of the set.
     *
     * Inspired by http://stackoverflow.com/questions/17350214/using-enum-class-with-stdbitset
     *
     * Example:
     * \code{.cpp}
     * enum class ConntrackState {
     *     NEW,
     *     ESTABLISHED,
     *     RELATED
     * };
     *
     * namespace Util {
     *     template<>
     *     struct EnumTraits<ConntrackState> {
     *         static constexpr ConntrackState max = ConntrackState::RELATED;
     *     };
     * }
     *
     * typedef EnumClassBitset<ConntrackState> ConntrackStateSet;
     *
     * void example() {
     *     ConntrackStateSet states;
     *     states.set(ConntrackState::NEW);
     *     states.set(ConntrackState::ESTABLISHED);
     *     bool result = states.test(ConntrackState::NEW);
     *     std::cout << result << std::endl;    // 1
     *     for (auto state : states) {
     *         switch (state) {
     *             case ConntrackState::NEW:
     *                 std::cout << "NEW is in the set" << std::endl;         // will be output
     *                 break;
     *             case ConntrackState::ESTABLISHED:
     *                 std::cout << "ESTABLISHED is in the set" << std::endl; // will be output
     *                 break;
     *             case ConntrackState::RELATED:
     *                 std::cout << "RELATED is in the set" << std::endl;     // will not be output
     *                 break;
     *         }
     *     }
     * }
     * \endcode
     *
     * \tparam T enum class type
     */
    template<typename T>
    class EnumClassBitset
    {
    public:
        /// Type of the bitset implementation
        typedef std::bitset<static_cast<std::size_t>(EnumTraits<T>::max) + 1> ImplType;

    private:
        /// Implementation of the bitset
        ImplType mBitset;

        /**
         * Cast the enum class type away to use it as an offset into the bitset
         * \param member enumeration member to convert
         * \return member casted to std::size_t
         */
        inline std::size_t enumIndex(T member) const
        {
            return static_cast<std::size_t>(member);
        }

    public:
        /**
         * Readonly iterator for elements in the set
         */
        struct iterator : std::iterator<std::forward_iterator_tag, T>
        {
        private:
            /// Enum set the iterator belongs to
            EnumClassBitset const & bitset;
            /// Index into the set of the current value
            std::size_t index;
            /// Index cast to T
            T value;

            /**
             * Private constructor for begin() and end()
             *
             * This constructor can be used to generate an invalid iterator when
             * \c argIndex is set to an element that is not inside the set.
             * To find the first correct element, use \ref findNext.
             *
             * \param argBitset enum set the iterator belongs to
             * \param argIndex index into the set of the current value
             */
            iterator(EnumClassBitset const & argBitset, std::size_t argIndex)
            : bitset(argBitset), index(argIndex)
            {
                value = static_cast<T> (index);
            }

            /**
             * Starting with the current index, find the first index
             * that corresponds to an element actually in the set
             *
             * If none is found, \c index is bitset.size(), which should be equivalent
             * to bitset.end() as iterator.
             */
            void findNext()
            {
                while (index < bitset.size()) {
                    value = static_cast<T> (index);
                    if (bitset.test(value)) {
                        break;
                    }
                    index++;
                };
            }

            friend class EnumClassBitset;

        public:
            /**
             * Get the enumeration member this iterator represents
             */
            T& operator*()
            {
                return value;
            }
            /**
             * Advance the iterator
             * \return iterator for the next enumeration member in the set, or
             *         a past-the-end iterator
             */
            iterator& operator++()
            {
                index++;
                findNext();
                return *this;
            }
            /**
             * Compare with another iterator for equality
             * \param other other iterator
             * \return \c true if the iterators point to the same element in the same set, \c false otherwise
             */
            bool operator==(iterator const & other) const
            {
                return (std::addressof(bitset) == std::addressof(other.bitset)) && (index == other.index);
            }
            /**
             * Compare with another iterator for inequality
             * \param other other iterator
             * \return \c false if the iterators point to the same element in the same set, \c true otherwise
             */
            bool operator!=(iterator const & other) const
            {
                return !((*this) == other);
            }
        };

        typedef typename ImplType::reference reference;

        /**
         * Default constructor
         *
         * All enumeration members are considered to be not in the set.
         */
        EnumClassBitset()
        {
        }

        /**
         * Compare with another enumeration set for equality
         * \param other set to compare
         * \return \c true if the members of both sets are equivalent, \c false otherwise
         */
        bool operator==(const EnumClassBitset& other) const
        {
            return mBitset == other.mBitset;
        }
        /**
         * Compare with another enumeration set for inequality
         * \param other set to compare
         * \return \c false if the members of both sets are equivalent, \c true otherwise
         */
        bool operator!=(const EnumClassBitset& other) const
        {
            return mBitset != other.mBitset;
        }

        /**
         * Access the enumeration member \c member
         *
         * Unlike \ref test, does not throw exceptions: the behaviour is undefined
         * if \c member is out of bounds.
         *
         * \param member member to access the value of
         * \return \c true if the \c member is in the set, \c false otherwise
         */
        constexpr bool operator[](T member) const
        {
            return mBitset[enumIndex(member)];
        }

        /**
         * Access the enumeration member \c member
         *
         * Unlike \ref test, does not throw exceptions: the behaviour is undefined
         * if \c member is out of bounds.
         *
         * \param member member to access the value of
         * \return an object of type reference, which allows including/excluding
         *         the member from the set by writing to it
         */
        reference operator[](T member)
        {
            return mBitset[enumIndex(member)];
        }

        /**
         * Return the value of the enumeration member \c member
         *
         * \throws std::out_of_range if \c member is not a valid enumeration member
         *
         * \param member member to return the value of
         * \return \c true if the requested enumeration member is in the set, \c false otherwise
         */
        bool test(T member) const
        {
            return mBitset.test(enumIndex(member));
        }

        /**
         * Check if all possible enumeration members are part of the set
         */
        bool all() const
        {
            return mBitset.all();
        }

        /**
         * Check if any of the possible enumeration members are part of the set
         */
        bool any() const
        {
            return mBitset.any();
        }

        /**
         * Check if none of the possible enumeration members are part of the set
         */
        bool none() const
        {
            return mBitset.none();
        }

        /**
         * Get the number of enumeration members that are part of the set
         */
        std::size_t count() const
        {
            return mBitset.count();
        }

        /**
         * Returns the number of enumeration members that the set can hold
         *
         * \return number of members the set can hold, i.e. EnumTraits<T>::max
         */
        constexpr std::size_t size() const
        {
            return mBitset.size();
        }

        /**
         * Set the value of the enumeration member \c member to \c false
         * \param member member to set the value of to \c false
         * \return \c *this
         */
        EnumClassBitset& reset(T member)
        {
            mBitset.reset(enumIndex(member));
            return *this;
        }

        /**
         * Flip the values of all enumeration members, i.e. get the inverse set
         * \return \c *this
         */
        EnumClassBitset& flip()
        {
            mBitset.flip();
            return *this;
        }

        /**
         * Flip the value of the enumeration member \c member
         * \param member member to flip the value of
         * \return \c *this
         */
        EnumClassBitset& flip(T member)
        {
            mBitset.flip(enumIndex(member));
            return *this;
        }

        /**
         * Set the value of the enumeration member \c member to value
         * \param member member to set the value of
         * \param value value to set the enumeration member to
         * \return \c *this
         */
        EnumClassBitset& set(T member, bool value = true)
        {
            mBitset.set(enumIndex(member), value);
            return *this;
        }

        /**
         * Intersect this set with another set
         * \param other another set
         * \return \c *this
         */
        EnumClassBitset& operator&=(EnumClassBitset const & other)
        {
            mBitset &= other.mBitset;
            return *this;
        }

        /**
         * Combine this set with another set
         * \param other another set
         * \return \c *this
         */
        EnumClassBitset& operator|=(EnumClassBitset const & other)
        {
            mBitset |= other.mBitset;
            return *this;
        }

        /**
         * Combine this set with another set using an exclusive-OR relation
         * \param other another set
         * \return \c *this
         */
        EnumClassBitset& operator^=(EnumClassBitset const & other)
        {
            mBitset ^= other.mBitset;
            return *this;
        }

        /**
         * Build the intersection with another set
         * \param other another set
         * \return set with all elements that are set in both this set and \c other
         */
        EnumClassBitset operator&(EnumClassBitset const & other) const
        {
            EnumClassBitset newBitset(*this);
            newBitset.mBitset &= other.mBitset;
            return newBitset;
        }

        /**
         * Build the union set with another set
         * \param other another set
         * \return set with all elements that are set in this set or \c other
         */
        EnumClassBitset operator|(EnumClassBitset const & other) const
        {
            EnumClassBitset newBitset(*this);
            newBitset.mBitset |= other.mBitset;
            return newBitset;
        }

        /**
         * Build the union set with another set
         * \param other another set
         * \return set with all elements that are set in either this set or \c other
         */
        EnumClassBitset operator^(EnumClassBitset const & other) const
        {
            EnumClassBitset newBitset(*this);
            newBitset.mBitset ^= other.mBitset;
            return newBitset;
        }

        /**
         * Get a set with the values of all enumeration members, i.e. the inverse set
         * \sa flip
         * \return set which contains all enumeration members that are not contained
         *         in this set
         */
        EnumClassBitset operator~() const
        {
            EnumClassBitset newBitset(*this);
            newBitset.flip();
            return newBitset;
        }

        /**
         * Constant iterator to the first enumeration member in the set
         */
        iterator begin() const
        {
            auto iter = iterator(*this, 0);
            // Advance to first element in set
            iter.findNext();
            return iter;
        }

        /**
         * Constant iterator past the last enumeration member in the set
         */
        iterator end() const
        {
            return iterator(*this, static_cast<std::size_t>(EnumTraits<T>::max) + 1);
        }

        /**
         * Convert the enumeration member set to a raw \c std::bitset
         *
         * \return \c std::bitset instance with bit positions corresponding to
         *         enumeration members in this set set to \c true
         */
        ImplType to_raw_bitset() const
        {
            return mBitset;
        }

    };

}
<|endoftext|>


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

#include "printing/printing_context_cairo.h"

#include "base/logging.h"
#include "base/values.h"
#include "printing/units.h"
#include "printing/print_settings_initializer_gtk.h"

#if defined(OS_CHROMEOS)
#include <unicode/ulocdata.h>
#else
#include <gtk/gtk.h>
#include <gtk/gtkprintunixdialog.h>
#endif  // defined(OS_CHROMEOS)

#if !defined(OS_CHROMEOS)
namespace {
  // Function pointer for creating print dialogs.
  static void* (*create_dialog_func_)(
      printing::PrintingContext::PrintSettingsCallback* callback,
      printing::PrintingContextCairo* context) = NULL;
  // Function pointer for printing documents.
  static void (*print_document_func_)(
      void* print_dialog,
      const printing::NativeMetafile* metafile,
      const string16& document_name) = NULL;
}  // namespace
#endif  // !defined(OS_CHROMEOS)

namespace printing {

// static
  PrintingContext* PrintingContext::Create(const std::string& app_locale) {
  return static_cast<PrintingContext*>(new PrintingContextCairo(app_locale));
}

PrintingContextCairo::PrintingContextCairo(const std::string& app_locale)
#if defined(OS_CHROMEOS)
    : PrintingContext(app_locale) {
#else
    : PrintingContext(app_locale),
      print_dialog_(NULL) {
#endif
}

PrintingContextCairo::~PrintingContextCairo() {
  ReleaseContext();
}

#if !defined(OS_CHROMEOS)
// static
void PrintingContextCairo::SetPrintingFunctions(
    void* (*create_dialog_func)(PrintSettingsCallback* callback,
                                PrintingContextCairo* context),
    void (*print_document_func)(void* print_dialog,
                                const NativeMetafile* metafile,
                                const string16& document_name)) {
  DCHECK(create_dialog_func);
  DCHECK(print_document_func);
  DCHECK(!create_dialog_func_);
  DCHECK(!print_document_func_);
  create_dialog_func_ = create_dialog_func;
  print_document_func_ = print_document_func;
}

void PrintingContextCairo::PrintDocument(const NativeMetafile* metafile) {
  DCHECK(print_dialog_);
  DCHECK(metafile);
  print_document_func_(print_dialog_, metafile, document_name_);
}
#endif  // !defined(OS_CHROMEOS)

void PrintingContextCairo::AskUserForSettings(
    gfx::NativeView parent_view,
    int max_pages,
    bool has_selection,
    PrintSettingsCallback* callback) {
#if defined(OS_CHROMEOS)
  callback->Run(OK);
#else
  print_dialog_ = create_dialog_func_(callback, this);
#endif  // defined(OS_CHROMEOS)
}

PrintingContext::Result PrintingContextCairo::UseDefaultSettings() {
  DCHECK(!in_print_job_);

  ResetSettings();
#if defined(OS_CHROMEOS)
  // For Chrome OS use default values based on the app locale rather than rely
  // on GTK. Note that relying on the app locale does not work well if it is
  // different from the system locale, e.g. a user using Chinese ChromeOS in the
  // US. Eventually we need to get the defaults from the printer.
  // TODO(sanjeevr): We need a better feedback loop between the cloud print
  // dialog and this code.
  int dpi = 300;
  gfx::Size physical_size_device_units;
  gfx::Rect printable_area_device_units;
  int32_t width = 0;
  int32_t height = 0;
  UErrorCode error = U_ZERO_ERROR;
  ulocdata_getPaperSize(app_locale_.c_str(), &height, &width, &error);
  if (error != U_ZERO_ERROR) {
    // If the call failed, assume a paper size of 8.5 x 11 inches.
    LOG(WARNING) << "ulocdata_getPaperSize failed, using 8.5 x 11, error: "
                 << error;
    width = static_cast<int>(8.5 * dpi);
    height = static_cast<int>(11 * dpi);
  } else {
    // ulocdata_getPaperSize returns the width and height in mm.
    // Convert this to pixels based on the dpi.
    width = static_cast<int>(ConvertUnitDouble(width, 25.4, 1.0) * dpi);
    height = static_cast<int>(ConvertUnitDouble(height, 25.4, 1.0) * dpi);
  }

  physical_size_device_units.SetSize(width, height);
  printable_area_device_units.SetRect(
      static_cast<int>(PrintSettingsInitializerGtk::kLeftMarginInInch * dpi),
      static_cast<int>(PrintSettingsInitializerGtk::kTopMarginInInch * dpi),
      width - (PrintSettingsInitializerGtk::kLeftMarginInInch +
          PrintSettingsInitializerGtk::kRightMarginInInch) * dpi,
      height - (PrintSettingsInitializerGtk::kTopMarginInInch +
          PrintSettingsInitializerGtk::kBottomMarginInInch) * dpi);

  settings_.set_dpi(dpi);
  settings_.SetPrinterPrintableArea(physical_size_device_units,
                                    printable_area_device_units,
                                    dpi);
#else  // defined(OS_CHROMEOS)
  GtkWidget* dialog = gtk_print_unix_dialog_new(NULL, NULL);
  GtkPrintSettings* settings =
      gtk_print_unix_dialog_get_settings(GTK_PRINT_UNIX_DIALOG(dialog));
  GtkPageSetup* page_setup =
      gtk_print_unix_dialog_get_page_setup(GTK_PRINT_UNIX_DIALOG(dialog));

  PageRanges ranges_vector;  // Nothing to initialize for default settings.
  PrintSettingsInitializerGtk::InitPrintSettings(
          settings, page_setup, ranges_vector, false, &settings_);

  g_object_unref(settings);
  // |page_setup| is owned by dialog, so it does not need to be unref'ed.
  gtk_widget_destroy(dialog);
#endif  // defined(OS_CHROMEOS)

  return OK;
}

PrintingContext::Result PrintingContextCairo::UpdatePrintSettings(
    const DictionaryValue& job_settings, const PageRanges& ranges) {
  DCHECK(!in_print_job_);

  settings_.ranges = ranges;

  NOTIMPLEMENTED();

  return FAILED;
}

PrintingContext::Result PrintingContextCairo::InitWithSettings(
    const PrintSettings& settings) {
  DCHECK(!in_print_job_);

  settings_ = settings;

  return OK;
}

PrintingContext::Result PrintingContextCairo::NewDocument(
    const string16& document_name) {
  DCHECK(!in_print_job_);
  in_print_job_ = true;

#if !defined(OS_CHROMEOS)
  document_name_ = document_name;
#endif  // !defined(OS_CHROMEOS)

  return OK;
}

PrintingContext::Result PrintingContextCairo::NewPage() {
  if (abort_printing_)
    return CANCEL;
  DCHECK(in_print_job_);

  // Intentional No-op.

  return OK;
}

PrintingContext::Result PrintingContextCairo::PageDone() {
  if (abort_printing_)
    return CANCEL;
  DCHECK(in_print_job_);

  // Intentional No-op.

  return OK;
}

PrintingContext::Result PrintingContextCairo::DocumentDone() {
  if (abort_printing_)
    return CANCEL;
  DCHECK(in_print_job_);

  ResetSettings();
  return OK;
}

void PrintingContextCairo::Cancel() {
  abort_printing_ = true;
  in_print_job_ = false;
}

void PrintingContextCairo::ReleaseContext() {
  // Intentional No-op.
}

gfx::NativeDrawingContext PrintingContextCairo::context() const {
  // Intentional No-op.
  return NULL;
}

}  // namespace printing
<commit_msg>PrintPreview: Remove NOTIMPLEMENTED() function call in PrintingContextCairo::UpdatePrintSettings().<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "printing/printing_context_cairo.h"

#include "base/logging.h"
#include "base/values.h"
#include "printing/units.h"
#include "printing/print_settings_initializer_gtk.h"

#if defined(OS_CHROMEOS)
#include <unicode/ulocdata.h>
#else
#include <gtk/gtk.h>
#include <gtk/gtkprintunixdialog.h>
#endif  // defined(OS_CHROMEOS)

#if !defined(OS_CHROMEOS)
namespace {
  // Function pointer for creating print dialogs.
  static void* (*create_dialog_func_)(
      printing::PrintingContext::PrintSettingsCallback* callback,
      printing::PrintingContextCairo* context) = NULL;
  // Function pointer for printing documents.
  static void (*print_document_func_)(
      void* print_dialog,
      const printing::NativeMetafile* metafile,
      const string16& document_name) = NULL;
}  // namespace
#endif  // !defined(OS_CHROMEOS)

namespace printing {

// static
  PrintingContext* PrintingContext::Create(const std::string& app_locale) {
  return static_cast<PrintingContext*>(new PrintingContextCairo(app_locale));
}

PrintingContextCairo::PrintingContextCairo(const std::string& app_locale)
#if defined(OS_CHROMEOS)
    : PrintingContext(app_locale) {
#else
    : PrintingContext(app_locale),
      print_dialog_(NULL) {
#endif
}

PrintingContextCairo::~PrintingContextCairo() {
  ReleaseContext();
}

#if !defined(OS_CHROMEOS)
// static
void PrintingContextCairo::SetPrintingFunctions(
    void* (*create_dialog_func)(PrintSettingsCallback* callback,
                                PrintingContextCairo* context),
    void (*print_document_func)(void* print_dialog,
                                const NativeMetafile* metafile,
                                const string16& document_name)) {
  DCHECK(create_dialog_func);
  DCHECK(print_document_func);
  DCHECK(!create_dialog_func_);
  DCHECK(!print_document_func_);
  create_dialog_func_ = create_dialog_func;
  print_document_func_ = print_document_func;
}

void PrintingContextCairo::PrintDocument(const NativeMetafile* metafile) {
  DCHECK(print_dialog_);
  DCHECK(metafile);
  print_document_func_(print_dialog_, metafile, document_name_);
}
#endif  // !defined(OS_CHROMEOS)

void PrintingContextCairo::AskUserForSettings(
    gfx::NativeView parent_view,
    int max_pages,
    bool has_selection,
    PrintSettingsCallback* callback) {
#if defined(OS_CHROMEOS)
  callback->Run(OK);
#else
  print_dialog_ = create_dialog_func_(callback, this);
#endif  // defined(OS_CHROMEOS)
}

PrintingContext::Result PrintingContextCairo::UseDefaultSettings() {
  DCHECK(!in_print_job_);

  ResetSettings();
#if defined(OS_CHROMEOS)
  // For Chrome OS use default values based on the app locale rather than rely
  // on GTK. Note that relying on the app locale does not work well if it is
  // different from the system locale, e.g. a user using Chinese ChromeOS in the
  // US. Eventually we need to get the defaults from the printer.
  // TODO(sanjeevr): We need a better feedback loop between the cloud print
  // dialog and this code.
  int dpi = 300;
  gfx::Size physical_size_device_units;
  gfx::Rect printable_area_device_units;
  int32_t width = 0;
  int32_t height = 0;
  UErrorCode error = U_ZERO_ERROR;
  ulocdata_getPaperSize(app_locale_.c_str(), &height, &width, &error);
  if (error != U_ZERO_ERROR) {
    // If the call failed, assume a paper size of 8.5 x 11 inches.
    LOG(WARNING) << "ulocdata_getPaperSize failed, using 8.5 x 11, error: "
                 << error;
    width = static_cast<int>(8.5 * dpi);
    height = static_cast<int>(11 * dpi);
  } else {
    // ulocdata_getPaperSize returns the width and height in mm.
    // Convert this to pixels based on the dpi.
    width = static_cast<int>(ConvertUnitDouble(width, 25.4, 1.0) * dpi);
    height = static_cast<int>(ConvertUnitDouble(height, 25.4, 1.0) * dpi);
  }

  physical_size_device_units.SetSize(width, height);
  printable_area_device_units.SetRect(
      static_cast<int>(PrintSettingsInitializerGtk::kLeftMarginInInch * dpi),
      static_cast<int>(PrintSettingsInitializerGtk::kTopMarginInInch * dpi),
      width - (PrintSettingsInitializerGtk::kLeftMarginInInch +
          PrintSettingsInitializerGtk::kRightMarginInInch) * dpi,
      height - (PrintSettingsInitializerGtk::kTopMarginInInch +
          PrintSettingsInitializerGtk::kBottomMarginInInch) * dpi);

  settings_.set_dpi(dpi);
  settings_.SetPrinterPrintableArea(physical_size_device_units,
                                    printable_area_device_units,
                                    dpi);
#else  // defined(OS_CHROMEOS)
  GtkWidget* dialog = gtk_print_unix_dialog_new(NULL, NULL);
  GtkPrintSettings* settings =
      gtk_print_unix_dialog_get_settings(GTK_PRINT_UNIX_DIALOG(dialog));
  GtkPageSetup* page_setup =
      gtk_print_unix_dialog_get_page_setup(GTK_PRINT_UNIX_DIALOG(dialog));

  PageRanges ranges_vector;  // Nothing to initialize for default settings.
  PrintSettingsInitializerGtk::InitPrintSettings(
          settings, page_setup, ranges_vector, false, &settings_);

  g_object_unref(settings);
  // |page_setup| is owned by dialog, so it does not need to be unref'ed.
  gtk_widget_destroy(dialog);
#endif  // defined(OS_CHROMEOS)

  return OK;
}

PrintingContext::Result PrintingContextCairo::UpdatePrintSettings(
    const DictionaryValue& job_settings, const PageRanges& ranges) {
  DCHECK(!in_print_job_);

  settings_.ranges = ranges;

  // TODO(kmadhusu): Update other print settings such as number of copies,
  // collate, duplex printing, etc.,

  return OK;
}

PrintingContext::Result PrintingContextCairo::InitWithSettings(
    const PrintSettings& settings) {
  DCHECK(!in_print_job_);

  settings_ = settings;

  return OK;
}

PrintingContext::Result PrintingContextCairo::NewDocument(
    const string16& document_name) {
  DCHECK(!in_print_job_);
  in_print_job_ = true;

#if !defined(OS_CHROMEOS)
  document_name_ = document_name;
#endif  // !defined(OS_CHROMEOS)

  return OK;
}

PrintingContext::Result PrintingContextCairo::NewPage() {
  if (abort_printing_)
    return CANCEL;
  DCHECK(in_print_job_);

  // Intentional No-op.

  return OK;
}

PrintingContext::Result PrintingContextCairo::PageDone() {
  if (abort_printing_)
    return CANCEL;
  DCHECK(in_print_job_);

  // Intentional No-op.

  return OK;
}

PrintingContext::Result PrintingContextCairo::DocumentDone() {
  if (abort_printing_)
    return CANCEL;
  DCHECK(in_print_job_);

  ResetSettings();
  return OK;
}

void PrintingContextCairo::Cancel() {
  abort_printing_ = true;
  in_print_job_ = false;
}

void PrintingContextCairo::ReleaseContext() {
  // Intentional No-op.
}

gfx::NativeDrawingContext PrintingContextCairo::context() const {
  // Intentional No-op.
  return NULL;
}

}  // namespace printing
<|endoftext|>


<commit_before>// Texture.hh for Fluxbox Window Manager
// Copyright (c) 2002 Henrik Kinnunen (fluxgen@users.sourceforge.net)
//
// from Image.cc for Blackbox - an X11 Window manager
// Copyright (c) 1997 - 2000 Brad Hughes (bhughes@tcac.net)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

// $Id: Texture.cc,v 1.2 2002/11/30 14:13:43 rathnor Exp $

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif // HAVE_CONFIG_H

#include "Texture.hh"

#include <cstring>
#include <cctype>

namespace FbTk {

void Texture::setFromString(const char * const texture_str) {
	if (texture_str == 0)
		return;
	int t_len = strlen(texture_str) + 1;
	char *ts = new char[t_len];
	strcpy(ts, texture_str);

	// to lower
	for (size_t byte_pos = 0; byte_pos < strlen(ts); ++byte_pos)
		ts[byte_pos] = tolower(ts[byte_pos]);

	if (strstr(ts, "parentrelative")) {
		setType(Texture::PARENTRELATIVE);
	} else {
		setType(Texture::NONE);

		if (strstr(ts, "solid"))
			addType(Texture::SOLID);
		else if (strstr(ts, "gradient")) {
			addType(Texture::GRADIENT);
			if (strstr(ts, "crossdiagonal"))
				addType(Texture::CROSSDIAGONAL);
			else if (strstr(ts, "rectangle"))
				addType(Texture::RECTANGLE);
			else if (strstr(ts, "pyramid"))
				addType(Texture::PYRAMID);
			else if (strstr(ts, "pipecross"))
				addType(Texture::PIPECROSS);
			else if (strstr(ts, "elliptic"))
				addType(Texture::ELLIPTIC);
			else if (strstr(ts, "diagonal"))
				addType(Texture::DIAGONAL);
			else if (strstr(ts, "horizontal"))
				addType(Texture::HORIZONTAL);
			else if (strstr(ts, "vertical"))
				addType(Texture::VERTICAL);
			else
				addType(Texture::DIAGONAL);
		} else
			addType(Texture::SOLID);

		if (strstr(ts, "raised"))
			addType(Texture::RAISED);
		else if (strstr(ts, "sunken"))
			addType(Texture::SUNKEN);
		else if (strstr(ts, "flat"))
			addType(Texture::FLAT);
		else
			addType(Texture::RAISED);

		if (! (type() & Texture::FLAT))
			if (strstr(ts, "bevel2"))
				addType(Texture::BEVEL2);
			else
				addType(Texture::BEVEL1);

#ifdef INTERLACE
		if (strstr(ts, "interlaced"))
			addType(Texture::INTERLACED);
#endif // INTERLACE
	}

	delete [] ts;
}

}; // end namespace FbTk
<commit_msg>no need for interlace compiletime option<commit_after>// Texture.hh for Fluxbox Window Manager
// Copyright (c) 2002 Henrik Kinnunen (fluxgen@users.sourceforge.net)
//
// from Image.cc for Blackbox - an X11 Window manager
// Copyright (c) 1997 - 2000 Brad Hughes (bhughes@tcac.net)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

// $Id: Texture.cc,v 1.3 2002/11/30 20:34:27 fluxgen Exp $

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif // HAVE_CONFIG_H

#include "Texture.hh"

#include <cstring>
#include <cctype>

namespace FbTk {

void Texture::setFromString(const char * const texture_str) {
	if (texture_str == 0)
		return;
	int t_len = strlen(texture_str) + 1;
	char *ts = new char[t_len];
	strcpy(ts, texture_str);

	// to lower
	for (size_t byte_pos = 0; byte_pos < strlen(ts); ++byte_pos)
		ts[byte_pos] = tolower(ts[byte_pos]);

	if (strstr(ts, "parentrelative")) {
		setType(Texture::PARENTRELATIVE);
	} else {
		setType(Texture::NONE);

		if (strstr(ts, "solid"))
			addType(Texture::SOLID);
		else if (strstr(ts, "gradient")) {
			addType(Texture::GRADIENT);
			if (strstr(ts, "crossdiagonal"))
				addType(Texture::CROSSDIAGONAL);
			else if (strstr(ts, "rectangle"))
				addType(Texture::RECTANGLE);
			else if (strstr(ts, "pyramid"))
				addType(Texture::PYRAMID);
			else if (strstr(ts, "pipecross"))
				addType(Texture::PIPECROSS);
			else if (strstr(ts, "elliptic"))
				addType(Texture::ELLIPTIC);
			else if (strstr(ts, "diagonal"))
				addType(Texture::DIAGONAL);
			else if (strstr(ts, "horizontal"))
				addType(Texture::HORIZONTAL);
			else if (strstr(ts, "vertical"))
				addType(Texture::VERTICAL);
			else
				addType(Texture::DIAGONAL);
		} else
			addType(Texture::SOLID);

		if (strstr(ts, "raised"))
			addType(Texture::RAISED);
		else if (strstr(ts, "sunken"))
			addType(Texture::SUNKEN);
		else if (strstr(ts, "flat"))
			addType(Texture::FLAT);
		else
			addType(Texture::RAISED);

		if (! (type() & Texture::FLAT))
			if (strstr(ts, "bevel2"))
				addType(Texture::BEVEL2);
			else
				addType(Texture::BEVEL1);

		if (strstr(ts, "interlaced"))
			addType(Texture::INTERLACED);
	}

	delete [] ts;
}

}; // end namespace FbTk
<|endoftext|>


<commit_before>/***
 * testSDLScreenManager
 *
 * Testing SDLScreenManager class, which deals with SDL output and RdScreen management
 *
 * This test is NOT AUTOMATIC, not suitable for running it with a CI server
 *
 ***/

#include "ScreenManager.hpp"
#include "SDLScreenManager.hpp"
#include "RdScreen.hpp"
#include "MockupScreen.hpp"

#include <yarp/os/Time.h>

using namespace rd;

int main()
{
    //-- Start SDL, Create SDLScreen Manager
    SDLScreenManager::RegisterManager();
    ScreenManager * screenManager = ScreenManager::getScreenManager("SDL");
    screenManager->start();

    //-- Create a RdScreen to check the ScreenManager
    RdScreen * screen = new MockupScreen();
    screen->init();
    screen->update(MockupScreen::PARAM_MESSAGE, "Test screen");

    RdScreen * screen2 = new MockupScreen();
    screen2->init();
    screen2->update(MockupScreen::PARAM_MESSAGE, "Another test screen");

    //-- Set the first Screen in the ScreenManager
    screenManager->setCurrentScreen(screen);

    //-- Loop to display the first Screen
    for (int i = 0; i < 10; i++)
    {
        screenManager->show();
        yarp::os::Time::delay(0.2);
    }

    //-- Set the second Screen in the ScreenManager
    screenManager->setCurrentScreen(screen2);

    //-- Loop to display the first second
    for (int i = 0; i < 10; i++)
    {
        screenManager->show();
        yarp::os::Time::delay(0.2);
    }

    screenManager->stop();

    screen->cleanup();
    screen2->cleanup();

    return 0;
}
<commit_msg>Change testSDLScreenManager to test update() delegation<commit_after>/***
 * testSDLScreenManager
 *
 * Testing SDLScreenManager class, which deals with SDL output and RdScreen management
 *
 * This test is NOT AUTOMATIC, not suitable for running it with a CI server
 *
 ***/

#include "ScreenManager.hpp"
#include "SDLScreenManager.hpp"
#include "RdScreen.hpp"
#include "MockupScreen.hpp"

#include <yarp/os/Time.h>

using namespace rd;

int main()
{
    //-- Start SDL, Create SDLScreen Manager
    SDLScreenManager::RegisterManager();
    ScreenManager * screenManager = ScreenManager::getScreenManager("SDL");
    screenManager->start();

    //-- Create a RdScreen to check the ScreenManager
    RdScreen * screen = new MockupScreen();
    screen->init();
    RdScreen * screen2 = new MockupScreen();
    screen2->init();

    //-- Set the first Screen in the ScreenManager
    screenManager->setCurrentScreen(screen);
    screenManager->update(MockupScreen::PARAM_MESSAGE, "Test screen");

    //-- Loop to display the first Screen
    for (int i = 0; i < 10; i++)
    {
        screenManager->show();
        yarp::os::Time::delay(0.2);
    }

    //-- Set the second Screen in the ScreenManager
    screenManager->setCurrentScreen(screen2);
    screenManager->update(MockupScreen::PARAM_MESSAGE, "Another test screen");

    //-- Loop to display the first second
    for (int i = 0; i < 10; i++)
    {
        screenManager->show();
        yarp::os::Time::delay(0.2);
    }

    screenManager->stop();

    screen->cleanup();
    screen2->cleanup();

    return 0;
}
<|endoftext|>


<commit_before>#include "AppDelegate.h"
#include "../../../Classes/AppDelegate.h"
#include "cocos2d.h"
#include "platform/android/jni/JniHelper.h"
#include <jni.h>
#include <android/log.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

#define  LOG_TAG    "main"
#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)

using namespace cocos2d;

void cocos_android_app_init(JNIEnv* env) {
	CCLOG("cocos_android_app_init");

        int out = open("/sdcard/LudoMuse/run.log", O_RDWR|O_CREAT, 0600);
        int err = open("/sdcard/LudoMuse/error.log", O_RDWR|O_CREAT, 0600);
        if (out == -1 || err == -1)
        {
          perror("cannot open log files");
          return;
        }

        // to still output to real stdout/stderr use these
        // int save_out = dup(fileno(stdout));
        // int save_err = dup(fileno(stderr));

        if (dup2(out, fileno(stdout)) == -1)
        {
          perror("cannot redirect stdout");
          return;
        }
        if (dup2(err, fileno(stderr)) == -1)
        {
          perror("cannot redirect stderr");
          return;
        }

        puts("successfully redirected outputs");

        fflush(stdout);
        fflush(stderr);

	AppDelegate *pAppDelegate = new AppDelegate(false, "/sdcard/LudoMuse/main.json");

        close(out);
        close(err);
}
<commit_msg>changed how main ludomuse json file is handled<commit_after>#include "AppDelegate.h"
#include "../../../Classes/AppDelegate.h"
#include "cocos2d.h"
#include "platform/android/jni/JniHelper.h"
#include <jni.h>
#include <android/log.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <fstream>
#include <sstream>

#define  LOG_TAG    "main"
#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)

using namespace cocos2d;

void cocos_android_app_init(JNIEnv* env) {
	CCLOG("cocos_android_app_init");

        int out = open("/sdcard/LudoMuse/run.log", O_RDWR|O_CREAT, 0600);
        int err = open("/sdcard/LudoMuse/error.log", O_RDWR|O_CREAT, 0600);
        if (out == -1 || err == -1)
        {
          perror("cannot open log files");
          return;
        }

        // to still output to real stdout/stderr use these
        // int save_out = dup(fileno(stdout));
        // int save_err = dup(fileno(stderr));

        if (dup2(out, fileno(stdout)) == -1)
        {
          perror("cannot redirect stdout");
          return;
        }
        if (dup2(err, fileno(stderr)) == -1)
        {
          perror("cannot redirect stderr");
          return;
        }

        puts("successfully redirected outputs");

        fflush(stdout);
        fflush(stderr);

		std::ifstream infile("/sdcard/LudoMuse/LudoMuse.conf");
		std::string line;
		std::string filename = "/sdcard/LudoMuse/";
		if (std::getline(infile, line))
		{
			std::stringstream ss(line);
			filename += ss.str();
		}

		AppDelegate *pAppDelegate = new AppDelegate(false, filename);

        close(out);
        close(err);
}
<|endoftext|>


<commit_before>// vim : set fileencoding=utf-8 expandtab noai ts=4 sw=4 :
/// @addtogroup ahbprof
/// @{
/// @file ahbprof.cpp
///
///
/// @date 2010-2014
/// @copyright All rights reserved.
///            Any reproduction, use, distribution or disclosure of this
///            program, without the express, prior written consent of the
///            authors is strictly prohibited.
/// @author Rolf Meyer
///

#include <ctime>
#include <fstream>
#include <iostream>
#include "gaisler/ahbprof/ahbprof.h"
#include "core/common/vendian.h"
#include "core/common/verbose.h"

// / Constructor
AHBProf::AHBProf(const ModuleName nm,  // Module name
  uint32_t index,
  uint16_t addr,                                    // AMBA AHB address (12 bit)
  uint16_t mask,                                    // AMBA AHB address mask (12 bit)
  AbstractionLayer ambaLayer) :                 // abstraction layer
  AHBSlave<>(nm,
    index,
    0xce,                                           // Vendor: c3e
    0x0FE,                                          // Device: OutFileDevice,
    0,
    0,
    ambaLayer,
    BAR(AHBMEM, mask, 0, 0, addr)),
  m_addr(addr),
  m_mask(mask) {
  // haddr and hmask must be 12 bit
  assert(!((m_addr | m_mask) >> 12));

  // Display AHB slave information
  v::info << name() << "********************************************************************" << v::endl;
  v::info << name() << "* Create AHB Profiling device with following parameters:            " << v::endl;
  v::info << name() << "* haddr/hmask: " << v::uint32 << m_addr << "/" << v::uint32 << m_mask << v::endl;
  v::info << name() << "* Slave base address: 0x" << std::setw(8) << std::setfill('0') << hex <<
    get_ahb_base_addr()                     << v::endl;
  v::info << name() << "* Slave size (bytes): 0x" << std::setw(8) << std::setfill('0') << hex <<
    get_ahb_size()                          << v::endl;
  v::info << name() << "********************************************************************" << v::endl;
}

// / Destructor
AHBProf::~AHBProf() {
}

// / Encapsulated functionality
uint32_t AHBProf::exec_func(
    tlm::tlm_generic_payload &trans,  // NOLINT(runtime/references)
    sc_core::sc_time &delay,          // NOLINT(runtime/references)
    bool debug) {
  if (!((m_addr ^ (trans.get_address() >> 20)) & m_mask)) {
    uint32_t address = (trans.get_address() - ((m_addr & m_mask) << 20)) >> 2;
    if (address > 16) {
      v::warn << name() << "Address offset bigger than 16" << v::endl;
    }

    if (trans.get_data_length() > 4) {
      v::warn << name() << "Transaction exceeds slave memory region" << v::endl;
    }

    if (trans.is_write()) {
      unsigned int state = *((unsigned int *)trans.get_data_ptr());
      swap_Endianess(state);
      info[address].state = state;
      // v::info << name() << "Address: " << address << " -- State: " << state << v::endl;
      switch (state) {
      case 1:
        info[address].real_start = std::clock();
        info[address].sim_start = sc_time_stamp();
        break;
      case 2:
        info[address].real_end = std::clock();
        info[address].sim_end = sc_time_stamp();
        break;
      case 3:
        v::report << name() << "********************************************************************" << v::endl;
        v::report << name() << "* real time (" << address << "): " << info[address].real_end << " - " <<
          info[address].real_start << " = " << (info[address].real_end - info[address].real_start) << v::endl;
        v::report << name() << "* simulated time (" << address << "): " << info[address].sim_end << " - " <<
          info[address].sim_start << " = " << (info[address].sim_end - info[address].sim_start) << v::endl;
        v::report << name() << "********************************************************************" << v::endl;

        break;
      case 255:
        sc_core::sc_stop();
        break;
      default: {
        }
      }

      delay += clock_cycle * 4;
      trans.set_response_status(tlm::TLM_OK_RESPONSE);
    } else {
      // We don't support reading. We are an output device.
      // So return 0x0
      for (uint32_t i = 0; i < trans.get_data_length(); i++) {
        *(trans.get_data_ptr() + i) = 0;
      }

      // Total delay is base delay + 4 wait states
      delay += clock_cycle * 4;
      trans.set_response_status(tlm::TLM_OK_RESPONSE);
    }
  } else {
    // address not valid
    v::error << name() << "Address not within permissable slave memory space" << v::endl;
    trans.set_response_status(tlm::TLM_ADDRESS_ERROR_RESPONSE);
  }
  return trans.get_data_length();
}

sc_core::sc_time AHBProf::get_clock() {
  return clock_cycle;
}
// / @}
<commit_msg>Adding AHBProf as sr_registry model<commit_after>// vim : set fileencoding=utf-8 expandtab noai ts=4 sw=4 :
/// @addtogroup ahbprof
/// @{
/// @file ahbprof.cpp
///
///
/// @date 2010-2014
/// @copyright All rights reserved.
///            Any reproduction, use, distribution or disclosure of this
///            program, without the express, prior written consent of the
///            authors is strictly prohibited.
/// @author Rolf Meyer
///

#include <ctime>
#include <fstream>
#include <iostream>
#include "gaisler/ahbprof/ahbprof.h"
#include "core/common/vendian.h"
#include "core/common/verbose.h"

SR_HAS_MODULE(AHBProf);

// / Constructor
AHBProf::AHBProf(const ModuleName nm,  // Module name
  uint32_t index,
  uint16_t addr,                                    // AMBA AHB address (12 bit)
  uint16_t mask,                                    // AMBA AHB address mask (12 bit)
  AbstractionLayer ambaLayer) :                 // abstraction layer
  AHBSlave<>(nm,
    index,
    0xce,                                           // Vendor: c3e
    0x0FE,                                          // Device: OutFileDevice,
    0,
    0,
    ambaLayer,
    BAR(AHBMEM, mask, 0, 0, addr)),
  m_addr(addr),
  m_mask(mask) {
  // haddr and hmask must be 12 bit
  assert(!((m_addr | m_mask) >> 12));

  // Display AHB slave information
  v::info << name() << "********************************************************************" << v::endl;
  v::info << name() << "* Create AHB Profiling device with following parameters:            " << v::endl;
  v::info << name() << "* haddr/hmask: " << v::uint32 << m_addr << "/" << v::uint32 << m_mask << v::endl;
  v::info << name() << "* Slave base address: 0x" << std::setw(8) << std::setfill('0') << hex <<
    get_ahb_base_addr()                     << v::endl;
  v::info << name() << "* Slave size (bytes): 0x" << std::setw(8) << std::setfill('0') << hex <<
    get_ahb_size()                          << v::endl;
  v::info << name() << "********************************************************************" << v::endl;
}

// / Destructor
AHBProf::~AHBProf() {
}

// / Encapsulated functionality
uint32_t AHBProf::exec_func(
    tlm::tlm_generic_payload &trans,  // NOLINT(runtime/references)
    sc_core::sc_time &delay,          // NOLINT(runtime/references)
    bool debug) {
  if (!((m_addr ^ (trans.get_address() >> 20)) & m_mask)) {
    uint32_t address = (trans.get_address() - ((m_addr & m_mask) << 20)) >> 2;
    if (address > 16) {
      v::warn << name() << "Address offset bigger than 16" << v::endl;
    }

    if (trans.get_data_length() > 4) {
      v::warn << name() << "Transaction exceeds slave memory region" << v::endl;
    }

    if (trans.is_write()) {
      unsigned int state = *((unsigned int *)trans.get_data_ptr());
      swap_Endianess(state);
      info[address].state = state;
      // v::info << name() << "Address: " << address << " -- State: " << state << v::endl;
      switch (state) {
      case 1:
        info[address].real_start = std::clock();
        info[address].sim_start = sc_time_stamp();
        break;
      case 2:
        info[address].real_end = std::clock();
        info[address].sim_end = sc_time_stamp();
        break;
      case 3:
        v::report << name() << "********************************************************************" << v::endl;
        v::report << name() << "* real time (" << address << "): " << info[address].real_end << " - " <<
          info[address].real_start << " = " << (info[address].real_end - info[address].real_start) << v::endl;
        v::report << name() << "* simulated time (" << address << "): " << info[address].sim_end << " - " <<
          info[address].sim_start << " = " << (info[address].sim_end - info[address].sim_start) << v::endl;
        v::report << name() << "********************************************************************" << v::endl;

        break;
      case 255:
        sc_core::sc_stop();
        break;
      default: {
        }
      }

      delay += clock_cycle * 4;
      trans.set_response_status(tlm::TLM_OK_RESPONSE);
    } else {
      // We don't support reading. We are an output device.
      // So return 0x0
      for (uint32_t i = 0; i < trans.get_data_length(); i++) {
        *(trans.get_data_ptr() + i) = 0;
      }

      // Total delay is base delay + 4 wait states
      delay += clock_cycle * 4;
      trans.set_response_status(tlm::TLM_OK_RESPONSE);
    }
  } else {
    // address not valid
    v::error << name() << "Address not within permissable slave memory space" << v::endl;
    trans.set_response_status(tlm::TLM_ADDRESS_ERROR_RESPONSE);
  }
  return trans.get_data_length();
}

sc_core::sc_time AHBProf::get_clock() {
  return clock_cycle;
}
// / @}
<|endoftext|>


<commit_before>#ifndef ID_HXX_HQ5DONMJ
#define ID_HXX_HQ5DONMJ

#include "string.hxx"
#include "ptr.hxx"
#include "ppr.hxx"

#include <string>
#include <ostream>
#include <functional>

namespace miniml
{

/// Identifiers keep a hash for quick equality testing.
class Id final
{
public:
  Id(const Id&) = default;
  Id(Id&&) = default;

  Id &operator=(const Id&) = default;
  Id &operator=(Id&&) = default;

  /// Creates an identifier. \a str isn't copied.
  Id(const Ptr<String> str):
    m_val(str),
    m_hash(make_hash(*str))
  { }

  /// Copies a string onto the heap and constructs an identifier from it.
  Id(const String &str):
    Id(ptr<String>(str))
  { }

  /// If the hashes are the same then the values are also checked in case of a
  /// collision.
  /// \return Whether the two identifiers are the same.
  bool operator==(const Id &other) const
  { return m_hash == other.m_hash && *m_val == *other.m_val; }

  /// \return The value of the identifier.
  Ptr<String> val() const { return m_val; }

  size_t hash() const { return m_hash; }

  /// \return The identifier in \ref String form.
  operator const Ptr<String>() const { return val(); }

  /// Pretty prints an identifier.
  /// \relates PprString
  Ptr<Ppr> ppr() const { return ppr::string(*val()); }

private:
  /// Hash function for \ref String.
  static std::hash<String> make_hash;

  Ptr<String> m_val;  ///< Value.
  size_t m_hash;     ///< Hash.
};

/// Outputs an identifier to the given output stream.
inline OStream& operator<<(OStream &out, const Id &id)
{
  return out << *id.val();
}

}

namespace std
{

template <>
struct hash<miniml::Id>
{
  typedef miniml::Id argument_type;
  typedef size_t result_type;
  size_t operator()(const miniml::Id &i) const { return i.hash(); }
};

}

#endif /* end of include guard: ID_HXX_HQ5DONMJ */
<commit_msg>Make Id inherit Pretty<commit_after>#ifndef ID_HXX_HQ5DONMJ
#define ID_HXX_HQ5DONMJ

#include "string.hxx"
#include "ptr.hxx"
#include "ppr.hxx"

#include <string>
#include <ostream>
#include <functional>

namespace miniml
{

/// Identifiers keep a hash for quick equality testing.
class Id final: public Pretty
{
public:
  Id(const Id&) = default;
  Id(Id&&) = default;

  Id &operator=(const Id&) = default;
  Id &operator=(Id&&) = default;

  /// Creates an identifier. \a str isn't copied.
  Id(const Ptr<String> str):
    m_val(str),
    m_hash(make_hash(*str))
  { }

  /// Copies a string onto the heap and constructs an identifier from it.
  Id(const String &str):
    Id(ptr<String>(str))
  { }

  /// If the hashes are the same then the values are also checked in case of a
  /// collision.
  /// \return Whether the two identifiers are the same.
  bool operator==(const Id &other) const
  { return m_hash == other.m_hash && *m_val == *other.m_val; }

  /// \return The value of the identifier.
  Ptr<String> val() const { return m_val; }

  size_t hash() const { return m_hash; }

  /// \return The identifier in \ref String form.
  operator const Ptr<String>() const { return val(); }

  /// Pretty prints an identifier.
  /// \relates PprString
  Ptr<Ppr> ppr(unsigned prec = 0) const override
  { return ppr::string(*val()); }

private:
  /// Hash function for \ref String.
  static std::hash<String> make_hash;

  Ptr<String> m_val;  ///< Value.
  size_t m_hash;     ///< Hash.
};

/// Outputs an identifier to the given output stream.
inline OStream& operator<<(OStream &out, const Id &id)
{
  return out << *id.val();
}

}

namespace std
{

template <>
struct hash<miniml::Id>
{
  typedef miniml::Id argument_type;
  typedef size_t result_type;
  size_t operator()(const miniml::Id &i) const { return i.hash(); }
};

}

#endif /* end of include guard: ID_HXX_HQ5DONMJ */
<|endoftext|>


<commit_before>#include <algorithm>
#include <iomanip>
#include <iostream>
#include <ostream>
#include <sstream>
#include <vector>
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkSubtractImageFilter.h"
#include "itkBinaryDilateImageFilter.h"
#include "itkBinaryBallStructuringElement.h"
#include "antsUtilities.h"
#include "itkMaskImageFilter.h"
#include "itkConnectedComponentImageFilter.h"
#include "itkBinaryThresholdImageFilter.h"
#include "itkImageRegionIterator.h"

namespace ants
{
template <unsigned int Dimension>
int LesionFilling( int argc, char * argv[] )
{
  typedef int                                   LesionType;
  typedef itk::Image<LesionType, Dimension> LesionImageType;
  typedef itk::ImageFileReader<LesionImageType>  LesionReaderType;

  typedef int                                   T1Type;
  typedef itk::Image<LesionType, Dimension> T1ImageType;
  typedef itk::ImageFileReader<LesionImageType>  T1ReaderType;

  typedef double           RealPixelType;  //  Operations
  typedef itk::Image< PixelType, Dimension >          ImageType;
  typedef itk::ImageRegionIterator< LesionImageType> IteratorType;
  typedef unsigned char PixelType;
  typedef itk::Image< PixelType, Dimension > ImageType;
  const int * Dimension = argv[1];
  const char * LesionMapFileName = argv[3];
  if (method == "-neighbourVoxels")
  {
         const char * T1FileName = argv[4]
  }
  else
  {
         const char * WMFileName = argv[4]
         const char * T1FileName = argv[5]
  }

  typename LesionReaderType::Pointer LesionReader = LesionReaderType::New();
  LesionReader->SetFileName( LesionMapFileName );
  LesionReader->Update();

  typedef itk::CastImageFilter< LesionImageType, RealImageType>
                                                         CastToRealFilterType;
  CastToRealFilterType::Pointer toReal = CastToRealFilterType::New();
  toReal->SetInput( LesionReader->GetOutput() );

  typedef itk::BinaryThresholdImageFilter <LesionImageType, LesionImageType>
                     BinaryThresholdImageFilterType;
  typedef itk::BinaryBallStructuringElement<
                               LesionImageType,
                               Dimension  >             StructuringElementType;
  typedef itk::BinaryDilateImageFilter<
                               LesionImageType,
                               LesionImageType,
                               StructuringElementType >  DilateFilterType;
  typedef itk::SubtractImageFilter <LesionImageType, LesionImageType>
                               SubtractImageFilterType;

  //finding connected components, we assume each component is one lesion
  typedef itk::ConnectedComponentImageFilter <LesionImageType, LesionImageType>
              ConnectedComponentImageFilterType;
  ConnectedComponentImageFilterType::Pointer connected =
              ConnectedComponentImageFilterType::New ();
  connected->SetInput( LesionReader->GetOutput() ) ;
  connected->Update();
  const int LesionNumber = connected->GetObjectCount() ;
  std::cout << "Number of lesions: " << LesionNumber << std::endl;
  std::vector<double> outervoxels;
  for ( int i = 1; i < LesionNumber; i++)
  {
     BinaryThresholdImageFilterType::Pointer thresholdFilter
                = BinaryThresholdImageFilterType::New();
     thresholdFilter->SetInput(connected->GetOutput());
     thresholdFilter->SetLowerThreshold( (double) i + 0.1);
     thresholdFilter->SetInsideValue  ( 1 );
     thresholdFilter->SetOutsideValue ( 0 );
     //Neighbouring voxel
     //filling lesions with the voxels surrounding them
     //first finding the edges of lesions
     //by subtracting dilated lesion map from lesion map itself
     DilateFilterType::Pointer binaryDilate = DilateFilterType::New();
     structuringElement.SetRadius( 1 );  // 3x3 structuring element
     structuringElement.CreateStructuringElement();
     binaryDilate->SetKernel( structuringElement );
     binaryDilate->SetInput( thresholdFilter->GetOutput() );
     binaryDilate->SetDilateValue( 1 );
     // subtract dilated image form non-dilated one
     SubtractImageFilterType::Pointer subtractFilter
                   = SubtractImageFilterType::New ();
     //output = image1 - image2
     subtractFilter->SetInput1(thresholdFilter->GetOutput() );
     subtractFilter->SetInput2(binaryDilate->GetOutput());
     subtractFilter->Update();
     //multiply the outer lesion mask with T1 to get only the neighbouring voxels
     typedef itk::MaskImageFilter< ImageType, ImageType > MaskFilterType;
     MaskFilterType::Pointer maskFilter = MaskFilterType::New();
     maskFilter->SetInput( thresholdFilter->GetOutput() );
     maskFilter->SetMaskImage( subtractFilter->GetOutput() );
     //collecting non-zero voxels
     IteratorType it( maskFilter->GetOutput(),
                       maskFilter->GetOutput()->GetLargestPossibleRegion() );
     it.GoToBegin();
     /** Walk over the image. */
     while ( !it.IsAtEnd() )
       {
         if( it.Value() )
         {
           outervoxels.push_back ( it.Get() );
         }
         ++it;
       } // end while

     for( It.GoToBegin() ; !It.IsAtEnd(); ++It )
      {
      if( ItM.Get() != 0 )
        {

        }
      }

  }

  /* LesionFilling d -neighbourVoxels binaryLeisonMap T1
   * LesionFilling d -mean binaryLesionMap AtroposWM T1
   * LesionFilling d -median binaryLesionmap AtroposWM T1
   * LesionFilling d -randomSample binaryLesionMap AtroposWM T1
   */
<commit_msg>Calculating meen lesion intensity<commit_after>#include <algorithm>
#include <iomanip>
#include <iostream>
#include <ostream>
#include <sstream>
#include <vector>
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkSubtractImageFilter.h"
#include "itkBinaryDilateImageFilter.h"
#include "itkBinaryBallStructuringElement.h"
#include "antsUtilities.h"
#include "itkMaskImageFilter.h"
#include "itkConnectedComponentImageFilter.h"
#include "itkBinaryThresholdImageFilter.h"
#include "itkImageRegionIterator.h"

namespace ants
{
template <unsigned int Dimension>
int LesionFilling( int argc, char * argv[] )
{
  typedef unsigned char PixelType;
  typedef itk::Image<PixelType, Dimension> ImageType;
  typedef itk::ImageFileReader<ImageType>  ImageReaderType;

  typedef double           RealPixelType;  //  Operations
  typedef itk::ImageRegionIterator< LesionImageType> IteratorType;
  const int * Dimension = argv[1];
  const char * LesionMapFileName = argv[3];
  if (method == "-neighbourVoxels")
  {
         const char * T1FileName = argv[4]
  }
  else
  {
         const char * WMFileName = argv[4]
         const char * T1FileName = argv[5]
  }

  typename ImageReaderType::Pointer LesionReader = ImageReaderType::New();
  LesionReader->SetFileName( LesionMapFileName );
  LesionReader->Update();

  typename ImageReaderType::Pointer T1Reader = ImageReaderType::New();
  T1Reader->SetFileName( T1FileName);
  T1Reader->Update();

  typedef itk::CastImageFilter< LesionImageType, RealImageType>
                                                         CastToRealFilterType;
  CastToRealFilterType::Pointer toReal = CastToRealFilterType::New();
  toReal->SetInput( LesionReader->GetOutput() );

  typedef itk::BinaryThresholdImageFilter <LesionImageType, LesionImageType>
                     BinaryThresholdImageFilterType;
  typedef itk::BinaryBallStructuringElement<
                               LesionImageType,
                               Dimension  >             StructuringElementType;
  typedef itk::BinaryDilateImageFilter<
                               LesionImageType,
                               LesionImageType,
                               StructuringElementType >  DilateFilterType;
  typedef itk::SubtractImageFilter <LesionImageType, LesionImageType>
                               SubtractImageFilterType;
  //finding connected components, we assume each component is one lesion
  typedef itk::ConnectedComponentImageFilter <LesionImageType, LesionImageType>
              ConnectedComponentImageFilterType;
  ConnectedComponentImageFilterType::Pointer connected =
              ConnectedComponentImageFilterType::New ();
  connected->SetInput( LesionReader->GetOutput() ) ;
  connected->Update();
  const int LesionNumber = connected->GetObjectCount() ;
  std::cout << "Number of lesions: " << LesionNumber << std::endl;
  std::vector<double> outervoxels;
  for ( int i = 1; i < LesionNumber; i++)
  {
     BinaryThresholdImageFilterType::Pointer thresholdFilter
                = BinaryThresholdImageFilterType::New();
     thresholdFilter->SetInput(connected->GetOutput());
     thresholdFilter->SetLowerThreshold( (double) i + 0.1);
     thresholdFilter->SetInsideValue  ( 1 );
     thresholdFilter->SetOutsideValue ( 0 );
     //Neighbouring voxel
     //filling lesions with the voxels surrounding them
     //first finding the edges of lesions
     //by subtracting dilated lesion map from lesion map itself
     DilateFilterType::Pointer binaryDilate = DilateFilterType::New();
     structuringElement.SetRadius( 1 );  // 3x3 structuring element
     structuringElement.CreateStructuringElement();
     binaryDilate->SetKernel( structuringElement );
     binaryDilate->SetInput( thresholdFilter->GetOutput() );
     binaryDilate->SetDilateValue( 1 );
     // subtract dilated image form non-dilated one
     SubtractImageFilterType::Pointer subtractFilter
                   = SubtractImageFilterType::New ();
     //output = image1 - image2
     subtractFilter->SetInput1(thresholdFilter->GetOutput() );
     subtractFilter->SetInput2(binaryDilate->GetOutput());
     subtractFilter->Update();
     //multiply the outer lesion mask with T1 to get only the neighbouring voxels
     typedef itk::MaskImageFilter< ImageType, ImageType > MaskFilterType;
     MaskFilterType::Pointer maskFilter = MaskFilterType::New();
     maskFilter->SetInput( mask t1 );
     maskFilter->SetMaskImage( subtractFilter->GetOutput() );
     //collecting non-zero voxels
     IteratorType it( maskFilter->GetOutput(),
                       maskFilter->GetOutput()->GetLargestPossibleRegion() );
     it.GoToBegin();
     /** Walk over the image. */
     while ( !it.IsAtEnd() )
       {
         if( it.Value() )
         {
           outervoxels.push_back ( it.Get() );
         }
         ++it;
       } // end while
     //calculating mean lesion intesity
     //Note: lesions should not be filled with values
     //less than their originial values, this is a
     //trick to exclude any CSF voxels in the outer mask (if any)
     MaskFilterType::Pointer maskFilterLesion = MaskFilterType::New();
     maskFilter->SetInput(

  }

<|endoftext|>


<commit_before>/***
 * testSDLScreenManager
 *
 * Testing SDLScreenManager class, which deals with SDL output and RdScreen management
 *
 * This test is NOT AUTOMATIC, not suitable for running it with a CI server
 *
 ***/

//#include "ScreenManager.hpp"
//#include "SDLScreenManager.hpp"
#include "RdScreen.hpp"
//#include "MockupRdScreen.hpp"

using namespace rd;

int main()
{
    //-- Start SDL, Create SDLScreen Manager
    SDLScreenManager::initSDL();
    SDLScreenManager::RegisterManager();
    ScreenManager * screenManager = ScreenManager::getScreenManager("SDL");

    //-- Create a RdScreen to check the ScreenManager
    RdScreen * screen = new MockupRdScreen();
    screen->update(MockupRdScreen::MESSAGE, "Test screen");

    RdScreen * screen2 = new MockupRdScreen();
    screen2->update(MockupRdScreen::MESSAGE, "Another test screen");

    //-- Set the first Screen in the ScreenManager
    screenManager->setCurrentScreen(screen);

    //-- Lopp to display the first Screen

    //-- (loop goes here)
    screenManager->show();

    //-- Set the second Screen in the ScreenManager
    screenManager->setCurrentScreen(screen2);

    //-- Lopp to display the first second

    //-- (loop goes here)
    screenManager->show();

    SLDScreenManager::cleanSDL();

    return 0;
}
<commit_msg>Add remaining code for testSDLScreenManager skeleton file<commit_after>/***
 * testSDLScreenManager
 *
 * Testing SDLScreenManager class, which deals with SDL output and RdScreen management
 *
 * This test is NOT AUTOMATIC, not suitable for running it with a CI server
 *
 ***/

//#include "ScreenManager.hpp"
//#include "SDLScreenManager.hpp"
#include "RdScreen.hpp"
//#include "MockupRdScreen.hpp"

#include <yarp/os/Time.h>

using namespace rd;

int main()
{
    //-- Start SDL, Create SDLScreen Manager
    SDLScreenManager::initSDL();
    SDLScreenManager::RegisterManager();
    ScreenManager * screenManager = ScreenManager::getScreenManager("SDL");

    //-- Create a RdScreen to check the ScreenManager
    RdScreen * screen = new MockupRdScreen();
    screen->init();
    screen->update(MockupRdScreen::MESSAGE, "Test screen");

    RdScreen * screen2 = new MockupRdScreen();
    screen2->init();
    screen2->update(MockupRdScreen::MESSAGE, "Another test screen");

    //-- Set the first Screen in the ScreenManager
    screenManager->setCurrentScreen(screen);

    //-- Loop to display the first Screen
    for (int i = 0; i < 10; i++)
    {
        screenManager->show();
        yarp::os::Time::delay(0.2);
    }

    //-- Set the second Screen in the ScreenManager
    screenManager->setCurrentScreen(screen2);

    //-- Loop to display the first second
    for (int i = 0; i < 10; i++)
    {
        screenManager->show();
        yarp::os::Time::delay(0.2);
    }

    screen->cleanup();
    screen2->cleanup();
    SLDScreenManager::cleanSDL();

    return 0;
}
<|endoftext|>