<commit_before>#ifndef PROTOZERO_DATA_VIEW_HPP
#define PROTOZERO_DATA_VIEW_HPP

/*****************************************************************************

protozero - Minimalistic protocol buffer decoder and encoder in C++.

This file is from https://github.com/mapbox/protozero where you can find more
documentation.

*****************************************************************************/

/**
 * @file data_view.hpp
 *
 * @brief Contains the implementation of the data_view class.
 */

#include <algorithm>
#include <cstddef>
#include <cstring>
#include <string>
#include <utility>

#include <protozero/config.hpp>

namespace protozero {

#ifdef PROTOZERO_USE_VIEW
using data_view = PROTOZERO_USE_VIEW;
#else

/**
 * Holds a pointer to some data and a length.
 *
 * This class is supposed to be compatible with the std::string_view
 * that will be available in C++17.
 */
class data_view {

    const char* m_data = nullptr;
    std::size_t m_size = 0;

public:

    /**
     * Default constructor. Construct an empty data_view.
     */
    constexpr data_view() noexcept = default;

    /**
     * Create data_view from pointer and size.
     *
     * @param ptr Pointer to the data.
     * @param length Length of the data.
     */
    constexpr data_view(const char* ptr, std::size_t length) noexcept
        : m_data(ptr),
          m_size(length) {
    }

    /**
     * Create data_view from string.
     *
     * @param str String with the data.
     */
    data_view(const std::string& str) noexcept // NOLINT clang-tidy: google-explicit-constructor
        : m_data(str.data()),
          m_size(str.size()) {
    }

    /**
     * Create data_view from zero-terminated string.
     *
     * @param ptr Pointer to the data.
     */
    data_view(const char* ptr) noexcept // NOLINT clang-tidy: google-explicit-constructor
        : m_data(ptr),
          m_size(std::strlen(ptr)) {
    }

    /**
     * Swap the contents of this object with the other.
     *
     * @param other Other object to swap data with.
     */
    void swap(data_view& other) noexcept {
        using std::swap;
        swap(m_data, other.m_data);
        swap(m_size, other.m_size);
    }

    /// Return pointer to data.
    constexpr const char* data() const noexcept {
        return m_data;
    }

    /// Return length of data in bytes.
    constexpr std::size_t size() const noexcept {
        return m_size;
    }

    /// Returns true if size is 0.
    constexpr bool empty() const noexcept {
        return m_size == 0;
    }

#ifndef PROTOZERO_STRICT_API
    /**
     * Convert data view to string.
     *
     * @pre Must not be default constructed data_view.
     *
     * @deprecated to_string() is not available in C++17 string_view so it
     *             should not be used to make conversion to that class easier
     *             in the future.
     */
    std::string to_string() const {
        protozero_assert(m_data);
        return {m_data, m_size};
    }
#endif

    /**
     * Convert data view to string.
     *
     * @pre Must not be default constructed data_view.
     */
    explicit operator std::string() const {
        protozero_assert(m_data);
        return {m_data, m_size};
    }

    /**
     * Compares the contents of this object with the given other object.
     *
     * @returns 0 if they are the same, <0 if this object is smaller than
     *          the other or >0 if it is larger. If both objects have the
     *          same size returns <0 if this object is lexicographically
     *          before the other, >0 otherwise.
     *
     * @pre Must not be default constructed data_view.
     */
    int compare(data_view other) const {
        protozero_assert(m_data && other.m_data);
        const int cmp = std::memcmp(data(), other.data(),
                                    std::min(size(), other.size()));
        if (cmp == 0) {
            if (size() == other.size()) {
                return 0;
            }
            return size() < other.size() ? -1 : 1;
        }
        return cmp;
    }

}; // class data_view

/**
 * Swap two data_view objects.
 *
 * @param lhs First object.
 * @param rhs Second object.
 */
inline void swap(data_view& lhs, data_view& rhs) noexcept {
    lhs.swap(rhs);
}

/**
 * Two data_view instances are equal if they have the same size and the
 * same content.
 *
 * @param lhs First object.
 * @param rhs Second object.
 */
inline bool operator==(const data_view lhs, const data_view rhs) noexcept {
    return lhs.size() == rhs.size() &&
           std::equal(lhs.data(), lhs.data() + lhs.size(), rhs.data());
}

/**
 * Two data_view instances are not equal if they have different sizes or the
 * content differs.
 *
 * @param lhs First object.
 * @param rhs Second object.
 */
inline bool operator!=(const data_view lhs, const data_view rhs) noexcept {
    return !(lhs == rhs);
}

/**
 * Returns true if lhs.compare(rhs) < 0.
 *
 * @param lhs First object.
 * @param rhs Second object.
 */
inline bool operator<(const data_view lhs, const data_view rhs) noexcept {
    return lhs.compare(rhs) < 0;
}

/**
 * Returns true if lhs.compare(rhs) <= 0.
 *
 * @param lhs First object.
 * @param rhs Second object.
 */
inline bool operator<=(const data_view lhs, const data_view rhs) noexcept {
    return lhs.compare(rhs) <= 0;
}

/**
 * Returns true if lhs.compare(rhs) > 0.
 *
 * @param lhs First object.
 * @param rhs Second object.
 */
inline bool operator>(const data_view lhs, const data_view rhs) noexcept {
    return lhs.compare(rhs) > 0;
}

/**
 * Returns true if lhs.compare(rhs) >= 0.
 *
 * @param lhs First object.
 * @param rhs Second object.
 */
inline bool operator>=(const data_view lhs, const data_view rhs) noexcept {
    return lhs.compare(rhs) >= 0;
}

#endif

} // end namespace protozero

#endif // PROTOZERO_DATA_VIEW_HPP
<commit_msg>Make operator== and operator!= on data_view constexpr.<commit_after>#ifndef PROTOZERO_DATA_VIEW_HPP
#define PROTOZERO_DATA_VIEW_HPP

/*****************************************************************************

protozero - Minimalistic protocol buffer decoder and encoder in C++.

This file is from https://github.com/mapbox/protozero where you can find more
documentation.

*****************************************************************************/

/**
 * @file data_view.hpp
 *
 * @brief Contains the implementation of the data_view class.
 */

#include <algorithm>
#include <cstddef>
#include <cstring>
#include <string>
#include <utility>

#include <protozero/config.hpp>

namespace protozero {

#ifdef PROTOZERO_USE_VIEW
using data_view = PROTOZERO_USE_VIEW;
#else

/**
 * Holds a pointer to some data and a length.
 *
 * This class is supposed to be compatible with the std::string_view
 * that will be available in C++17.
 */
class data_view {

    const char* m_data = nullptr;
    std::size_t m_size = 0;

public:

    /**
     * Default constructor. Construct an empty data_view.
     */
    constexpr data_view() noexcept = default;

    /**
     * Create data_view from pointer and size.
     *
     * @param ptr Pointer to the data.
     * @param length Length of the data.
     */
    constexpr data_view(const char* ptr, std::size_t length) noexcept
        : m_data(ptr),
          m_size(length) {
    }

    /**
     * Create data_view from string.
     *
     * @param str String with the data.
     */
    data_view(const std::string& str) noexcept // NOLINT clang-tidy: google-explicit-constructor
        : m_data(str.data()),
          m_size(str.size()) {
    }

    /**
     * Create data_view from zero-terminated string.
     *
     * @param ptr Pointer to the data.
     */
    data_view(const char* ptr) noexcept // NOLINT clang-tidy: google-explicit-constructor
        : m_data(ptr),
          m_size(std::strlen(ptr)) {
    }

    /**
     * Swap the contents of this object with the other.
     *
     * @param other Other object to swap data with.
     */
    void swap(data_view& other) noexcept {
        using std::swap;
        swap(m_data, other.m_data);
        swap(m_size, other.m_size);
    }

    /// Return pointer to data.
    constexpr const char* data() const noexcept {
        return m_data;
    }

    /// Return length of data in bytes.
    constexpr std::size_t size() const noexcept {
        return m_size;
    }

    /// Returns true if size is 0.
    constexpr bool empty() const noexcept {
        return m_size == 0;
    }

#ifndef PROTOZERO_STRICT_API
    /**
     * Convert data view to string.
     *
     * @pre Must not be default constructed data_view.
     *
     * @deprecated to_string() is not available in C++17 string_view so it
     *             should not be used to make conversion to that class easier
     *             in the future.
     */
    std::string to_string() const {
        protozero_assert(m_data);
        return {m_data, m_size};
    }
#endif

    /**
     * Convert data view to string.
     *
     * @pre Must not be default constructed data_view.
     */
    explicit operator std::string() const {
        protozero_assert(m_data);
        return {m_data, m_size};
    }

    /**
     * Compares the contents of this object with the given other object.
     *
     * @returns 0 if they are the same, <0 if this object is smaller than
     *          the other or >0 if it is larger. If both objects have the
     *          same size returns <0 if this object is lexicographically
     *          before the other, >0 otherwise.
     *
     * @pre Must not be default constructed data_view.
     */
    int compare(data_view other) const {
        protozero_assert(m_data && other.m_data);
        const int cmp = std::memcmp(data(), other.data(),
                                    std::min(size(), other.size()));
        if (cmp == 0) {
            if (size() == other.size()) {
                return 0;
            }
            return size() < other.size() ? -1 : 1;
        }
        return cmp;
    }

}; // class data_view

/**
 * Swap two data_view objects.
 *
 * @param lhs First object.
 * @param rhs Second object.
 */
inline void swap(data_view& lhs, data_view& rhs) noexcept {
    lhs.swap(rhs);
}

/**
 * Two data_view instances are equal if they have the same size and the
 * same content.
 *
 * @param lhs First object.
 * @param rhs Second object.
 */
inline constexpr bool operator==(const data_view lhs, const data_view rhs) noexcept {
    return lhs.size() == rhs.size() &&
           std::equal(lhs.data(), lhs.data() + lhs.size(), rhs.data());
}

/**
 * Two data_view instances are not equal if they have different sizes or the
 * content differs.
 *
 * @param lhs First object.
 * @param rhs Second object.
 */
inline constexpr bool operator!=(const data_view lhs, const data_view rhs) noexcept {
    return !(lhs == rhs);
}

/**
 * Returns true if lhs.compare(rhs) < 0.
 *
 * @param lhs First object.
 * @param rhs Second object.
 */
inline bool operator<(const data_view lhs, const data_view rhs) noexcept {
    return lhs.compare(rhs) < 0;
}

/**
 * Returns true if lhs.compare(rhs) <= 0.
 *
 * @param lhs First object.
 * @param rhs Second object.
 */
inline bool operator<=(const data_view lhs, const data_view rhs) noexcept {
    return lhs.compare(rhs) <= 0;
}

/**
 * Returns true if lhs.compare(rhs) > 0.
 *
 * @param lhs First object.
 * @param rhs Second object.
 */
inline bool operator>(const data_view lhs, const data_view rhs) noexcept {
    return lhs.compare(rhs) > 0;
}

/**
 * Returns true if lhs.compare(rhs) >= 0.
 *
 * @param lhs First object.
 * @param rhs Second object.
 */
inline bool operator>=(const data_view lhs, const data_view rhs) noexcept {
    return lhs.compare(rhs) >= 0;
}

#endif

} // end namespace protozero

#endif // PROTOZERO_DATA_VIEW_HPP
<|endoftext|>


<commit_before>//----------------------------------------------------------------------------
/// \file  Performance histogram printer of usec latencies.
//----------------------------------------------------------------------------
/// \brief Performance histogram printer.
//
// When building include -lrt
//----------------------------------------------------------------------------
// Copyright (c) 2012 Omnibius, LLC
// Author: Serge Aleynikov <saleyn@gmail.com>
// Created: 2012-03-20
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****

This file is part of utxx open-source project.

Copyright (C) 2012 Serge Aleynikov <saleyn@gmail.com>

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

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

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

***** END LICENSE BLOCK *****
*/

#ifndef _UTXX_PERF_HISTOGRAM_HPP_
#define _UTXX_PERF_HISTOGRAM_HPP_

#include <string>
#include <cstring>
#include <time.h>
#include <ostream>
#include <iomanip>
#include <boost/concept_check.hpp>

namespace utxx {

struct perf_histogram {
    enum clock_type {
          REALTIME      = CLOCK_REALTIME
        , MONOTONIC     = CLOCK_MONOTONIC
        , HIGH_RES      = CLOCK_PROCESS_CPUTIME_ID
        , THREAD_SPEC   = CLOCK_THREAD_CPUTIME_ID
    };

private:
    enum {
          MIN_RES = 10
        , MAX_RES = MIN_RES + 500/25 + 1000/250
        , BUCKETS = MAX_RES+1
    };

    int                 m_latencies[BUCKETS];
    double              m_minTime, m_maxTime, m_sumTime;
    struct timespec     m_last_start;
    int                 m_count;
    const std::string   m_header;
    const clock_type    m_clock_type;

    static int to_bucket(double d)
    {
        if (d < 0.000001 * MIN_RES) return (int) (d * 1000000.0);
        else if (d < 0.000500)      return MIN_RES + (int)(d * 1000000.0) / 25;
        else if (d > 1.0)           return MIN_RES + 500/25 + 1000/250;
        else                        return MIN_RES + 500/25 + (int)(d * 1000000.0) / 250;
    }

    static int from_bucket(int i)
    {
        if (i < MIN_RES)            return i;
        else if (i < MIN_RES + 24)  return MIN_RES + (i-MIN_RES)*25;
        else                        return MIN_RES + 500/25 + (i - MIN_RES - 500/25)*250;
    }

public:

    class sample {
        perf_histogram& h;
    public:
        sample(perf_histogram& a_h) : h(a_h) { h.start(); }
        ~sample() { h.stop(); }
    };

    perf_histogram(const std::string& header = std::string(), clock_type ct = HIGH_RES)
        : m_header(header)
        , m_clock_type(ct)
    {
        reset();
    }

    /// Reset internal statistics counters
    void reset() {
        m_count   = 0;
        m_minTime = 9999999;
        m_maxTime = m_sumTime = 0;
        memset(m_latencies,   0, sizeof(m_latencies));
        memset(&m_last_start, 0, sizeof(struct timespec));
    }

    /// Start a measurement sample
    void start() {
        clock_gettime(m_clock_type, &m_last_start);
    }

    /// Stop the measurement sample started with start().
    void stop() {
        struct timespec now;
        clock_gettime(m_clock_type, &now);

        static const double fraction = 1 / 1000000000.0;
        double diff = (double)(now.tv_sec  - m_last_start.tv_sec)
                    + (double)(now.tv_nsec - m_last_start.tv_nsec) * fraction;
        if (diff < 0)
            return;
        if (m_minTime > diff) m_minTime = diff;
        if (m_maxTime < diff) m_maxTime = diff;
        m_sumTime += diff;
        m_count++;
        int k = to_bucket(diff);
        if (k < BUCKETS)
            m_latencies[k]++;
    }

    /// Add statistics from another histogram
    void operator+= (const perf_histogram& a_rhs) {
        if (!a_rhs.m_count) return;

        if (m_maxTime < a_rhs.m_maxTime) m_maxTime = a_rhs.m_maxTime;
        if (m_minTime > a_rhs.m_minTime) m_minTime = a_rhs.m_minTime;
        m_sumTime += a_rhs.m_sumTime;
        m_count   += a_rhs.m_count;

        for (int i = 0; i < BUCKETS; i++)
            m_latencies[i] += a_rhs.m_latencies[i];
    }

    /// Dump a latency report to stdout
    void dump(std::ostream& out, int a_filter = -1) {
        if (m_count == 0) {
            out << "  No data samples" << std::endl;
            return;
        }

        out << m_header.c_str() << std::endl << std::fixed << std::setprecision(6)
            << "  MinTime = " << m_minTime << std::endl
            << "  MaxTime = " << m_maxTime << std::endl
            << "  AvgTime = " << m_sumTime / m_count << std::endl;

        double tot = 0;
        for (int i = 0; i < BUCKETS; i++)
            if (m_latencies[i] > 0 && (a_filter < 0 || from_bucket(i) < a_filter)) {
                double pcnt = 100.0 * (double)m_latencies[i] / m_count;
                tot += pcnt;
                out << "    " << std::setw(6) << from_bucket(i) << "us = "
                    << std::setw(9) << m_latencies[i]
                    << '(' << std::setw(6) << std::setprecision(3)
                    << pcnt << ") (total: "
                    << std::setw(7) << std::setprecision(3)
                    << tot << ') '
                    << std::string('*', (int)(30*pcnt/100))
                    << std::endl;
            }
    }
};

} // namespace utxx

#endif  // _UTXX_PERF_HISTOGRAM_HPP_
<commit_msg>Output enhancement in perf_histogram<commit_after>//----------------------------------------------------------------------------
/// \file  Performance histogram printer of usec latencies.
//----------------------------------------------------------------------------
/// \brief Performance histogram printer.
//
// When building include -lrt
//----------------------------------------------------------------------------
// Copyright (c) 2012 Omnibius, LLC
// Author: Serge Aleynikov <saleyn@gmail.com>
// Created: 2012-03-20
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****

This file is part of utxx open-source project.

Copyright (C) 2012 Serge Aleynikov <saleyn@gmail.com>

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

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

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

***** END LICENSE BLOCK *****
*/

#ifndef _UTXX_PERF_HISTOGRAM_HPP_
#define _UTXX_PERF_HISTOGRAM_HPP_

#include <string>
#include <cstring>
#include <time.h>
#include <ostream>
#include <iomanip>
#include <boost/concept_check.hpp>

namespace utxx {

struct perf_histogram {
    enum clock_type {
          REALTIME      = CLOCK_REALTIME
        , MONOTONIC     = CLOCK_MONOTONIC
        , HIGH_RES      = CLOCK_PROCESS_CPUTIME_ID
        , THREAD_SPEC   = CLOCK_THREAD_CPUTIME_ID
    };

private:
    enum {
          MIN_RES = 10
        , MAX_RES = MIN_RES + 500/25 + 1000/250
        , BUCKETS = MAX_RES+1
    };

    int                 m_latencies[BUCKETS];
    double              m_minTime, m_maxTime, m_sumTime;
    struct timespec     m_last_start;
    int                 m_count;
    const std::string   m_header;
    const clock_type    m_clock_type;

    static int to_bucket(double d)
    {
        if (d < 0.000001 * MIN_RES) return (int) (d * 1000000.0);
        else if (d < 0.000500)      return MIN_RES + (int)(d * 1000000.0) / 25;
        else if (d > 1.0)           return MIN_RES + 500/25 + 1000/250;
        else                        return MIN_RES + 500/25 + (int)(d * 1000000.0) / 250;
    }

    static int from_bucket(int i)
    {
        if (i < MIN_RES)            return i;
        else if (i < MIN_RES + 24)  return MIN_RES + (i-MIN_RES)*25;
        else                        return MIN_RES + 500/25 + (i - MIN_RES - 500/25)*250;
    }

public:

    class sample {
        perf_histogram& h;
    public:
        sample(perf_histogram& a_h) : h(a_h) { h.start(); }
        ~sample() { h.stop(); }
    };

    perf_histogram(const std::string& header = std::string(), clock_type ct = HIGH_RES)
        : m_header(header)
        , m_clock_type(ct)
    {
        reset();
    }

    /// Reset internal statistics counters
    void reset() {
        m_count   = 0;
        m_minTime = 9999999;
        m_maxTime = m_sumTime = 0;
        memset(m_latencies,   0, sizeof(m_latencies));
        memset(&m_last_start, 0, sizeof(struct timespec));
    }

    /// Start a measurement sample
    void start() {
        clock_gettime(m_clock_type, &m_last_start);
    }

    /// Stop the measurement sample started with start().
    void stop() {
        struct timespec now;
        clock_gettime(m_clock_type, &now);

        static const double fraction = 1 / 1000000000.0;
        double diff = (double)(now.tv_sec  - m_last_start.tv_sec)
                    + (double)(now.tv_nsec - m_last_start.tv_nsec) * fraction;
        if (diff < 0)
            return;
        if (m_minTime > diff) m_minTime = diff;
        if (m_maxTime < diff) m_maxTime = diff;
        m_sumTime += diff;
        m_count++;
        int k = to_bucket(diff);
        if (k < BUCKETS)
            m_latencies[k]++;
    }

    /// Add statistics from another histogram
    void operator+= (const perf_histogram& a_rhs) {
        if (!a_rhs.m_count) return;

        if (m_maxTime < a_rhs.m_maxTime) m_maxTime = a_rhs.m_maxTime;
        if (m_minTime > a_rhs.m_minTime) m_minTime = a_rhs.m_minTime;
        m_sumTime += a_rhs.m_sumTime;
        m_count   += a_rhs.m_count;

        for (int i = 0; i < BUCKETS; i++)
            m_latencies[i] += a_rhs.m_latencies[i];
    }

    /// Dump a latency report to stdout
    void dump(std::ostream& out, int a_filter = -1) {
        if (m_count == 0) {
            out << "  No data samples" << std::endl;
            return;
        }

        out << m_header.c_str() << std::endl << std::fixed << std::setprecision(6)
            << "  MinTime = " << m_minTime << std::endl
            << "  MaxTime = " << m_maxTime << std::endl
            << "  AvgTime = " << m_sumTime / m_count << std::endl;

        double tot = 0;
        for (int i = 0; i < BUCKETS; i++)
            if (m_latencies[i] > 0 && (a_filter < 0 || from_bucket(i) < a_filter)) {
                double pcnt = 100.0 * (double)m_latencies[i] / m_count;
                tot += pcnt;
                out << "    " << std::setw(6) << from_bucket(i) << "us = "
                    << std::setw(9) << m_latencies[i]
                    << '(' << std::setw(6) << std::setprecision(3)
                    << pcnt << ") (total: "
                    << std::setw(7) << std::setprecision(3)
                    << tot << ') '
                    << std::string((int)(30*pcnt/100), '*')
                    << std::endl;
            }
    }
};

} // namespace utxx

#endif  // _UTXX_PERF_HISTOGRAM_HPP_
<|endoftext|>


<commit_before>#pragma once

#include <type_traits>
namespace gcl::mp::type_traits
{
    template <class T>
    struct is_template : std::false_type {};
    template <class... T_args, template <class...> class T>
    struct is_template<T<T_args...>> : std::true_type {};
    template <auto... values, template <auto...> class T>
    struct is_template<T<values...>> : std::true_type {};
    template <class T>
    static inline constexpr auto is_template_v = is_template<T>::value;

    template <class T_concrete, template <class...> class T>
    struct is_instance_of : std::false_type {};
    template <template <class...> class T, class... T_args>
    struct is_instance_of<T<T_args...>, T> : std::true_type {};
    template <class T_concrete, template <class...> class T>
    static inline constexpr auto is_instance_of_v = is_instance_of<T_concrete, T>::value;

    template <class T, typename... Args>
    class is_brace_constructible {
        template <typename /*= void*/, typename U, typename... U_args>
        struct impl : std::false_type {};
        template <typename U, typename... U_args>
        struct impl<std::void_t<decltype(U{std::declval<U_args>()...})>, U, U_args...> : std::true_type {};

      public:
        constexpr inline static auto value = impl<std::void_t<>, T, Args...>::value;
    };
    template <class T, typename... Args>
    constexpr static inline auto is_brace_constructible_v = is_brace_constructible<T, Args...>::value;

    template <bool evaluation>
    using if_t = std::conditional_t<evaluation, std::true_type, std::false_type>;
    template <bool evaluation>
    constexpr static inline auto if_v = std::conditional_t<evaluation, std::true_type, std::false_type>::value;
}
#include <bitset>
#include <tuple>
#include <array>
namespace gcl::mp::type_traits
{
    template <template <typename> class trait, typename... Ts>
    struct trait_result {
        constexpr static auto as_bitset_v = []() consteval
        {
            using bitset_type = std::bitset<sizeof...(Ts)>;
            using bitset_initializer_t = unsigned long long;
            bitset_initializer_t value{0};
            return bitset_type{((value = (value << 1 | trait<Ts>::value)), ...)};
        }
        ();

        template <template <typename...> class T>
        using as_t = T<typename trait<Ts>::type...>;
        template <template <typename...> class T>
        constexpr static auto as_v = T{trait<Ts>::value...};

        using as_tuple_t = as_t<std::tuple>;
        constexpr static auto as_tuple_v = std::tuple{trait<Ts>::value...};

        template <class Int = int>
        using as_integer_sequence = std::integer_sequence<Int, trait<Ts>::value...>;

        // constexpr static auto as_array_v = std::array{trait<Ts>::value...}; // OK with GCC 10.2
        using as_array_t = std::array<std::tuple_element_t<0, decltype(std::tuple{trait<Ts>::value...})>, sizeof...(Ts)>;
        constexpr static auto as_array_v = as_array_t{trait<Ts>::value...};
    };
}

namespace gcl::mp::type_traits::tests::is_brace_constructible_v
{
    struct toto {
        int i;
    };
    struct titi {
        explicit titi(int) {}
    };

    static_assert(type_traits::is_brace_constructible_v<toto>);
    static_assert(type_traits::is_brace_constructible_v<toto, int>);
    static_assert(type_traits::is_brace_constructible_v<toto, char>);
    static_assert(not type_traits::is_brace_constructible_v<toto, char*>);
    static_assert(not type_traits::is_brace_constructible_v<titi>);
    static_assert(type_traits::is_brace_constructible_v<titi, int>);
    static_assert(type_traits::is_brace_constructible_v<titi, char>);
    static_assert(not type_traits::is_brace_constructible_v<titi, char*>);
}
namespace gcl::mp::type_traits::tests::if_t
{
    static_assert(std::is_same_v<type_traits::if_t<true>, std::true_type>);
    static_assert(std::is_same_v<type_traits::if_t<false>, std::false_type>);
    static_assert(type_traits::if_v<true> == true);
    static_assert(type_traits::if_v<false> == false);
}
#if __cpp_concepts
#include <concepts>
namespace gcl::mp::type_traits::tests::if_t
{
    // clang-format off
    template <typename T>
    concept is_red_colored = requires(T)
    {
        { T::color == decltype(T::color)::red } -> std::convertible_to<bool>;
        { type_traits::if_t<T::color == decltype(T::color)::red>{}} -> std::same_as<std::true_type>;
    };
    enum colors { red, blue, green };
    struct smthg_blue { constexpr static auto color = colors::blue; };
    struct smthg_red { constexpr static auto color = colors::red; };
    // clang-format on

    static_assert(not is_red_colored<smthg_blue>);
    static_assert(is_red_colored<smthg_red>);
}
#endif
namespace gcl::mp::type_traits::tests::trait_results
{
    template <typename T>
    using is_int = std::is_same<int, T>;
    using results = trait_result<is_int, char, int, bool>;
    using results_as_tuple = results::as_t<std::tuple>;
    using results_as_tuple_value_type = std::decay_t<decltype(results::as_v<std::tuple>)>;

    static_assert(std::tuple_size_v<results_as_tuple> == std::tuple_size_v<results_as_tuple_value_type>);

    // WIP
}<commit_msg>[gcl::mp] trait_result : add tests<commit_after>#pragma once

#include <type_traits>
namespace gcl::mp::type_traits
{
    template <class T>
    struct is_template : std::false_type {};
    template <class... T_args, template <class...> class T>
    struct is_template<T<T_args...>> : std::true_type {};
    template <auto... values, template <auto...> class T>
    struct is_template<T<values...>> : std::true_type {};
    template <class T>
    static inline constexpr auto is_template_v = is_template<T>::value;

    template <class T_concrete, template <class...> class T>
    struct is_instance_of : std::false_type {};
    template <template <class...> class T, class... T_args>
    struct is_instance_of<T<T_args...>, T> : std::true_type {};
    template <class T_concrete, template <class...> class T>
    static inline constexpr auto is_instance_of_v = is_instance_of<T_concrete, T>::value;

    template <class T, typename... Args>
    class is_brace_constructible {
        template <typename /*= void*/, typename U, typename... U_args>
        struct impl : std::false_type {};
        template <typename U, typename... U_args>
        struct impl<std::void_t<decltype(U{std::declval<U_args>()...})>, U, U_args...> : std::true_type {};

      public:
        constexpr inline static auto value = impl<std::void_t<>, T, Args...>::value;
    };
    template <class T, typename... Args>
    constexpr static inline auto is_brace_constructible_v = is_brace_constructible<T, Args...>::value;

    template <bool evaluation>
    using if_t = std::conditional_t<evaluation, std::true_type, std::false_type>;
    template <bool evaluation>
    constexpr static inline auto if_v = std::conditional_t<evaluation, std::true_type, std::false_type>::value;
}
#include <bitset>
#include <tuple>
#include <array>
namespace gcl::mp::type_traits
{
    template <template <typename> class trait, typename... Ts>
    struct trait_result {
        constexpr static auto as_bitset_v = []() consteval
        {
            using bitset_type = std::bitset<sizeof...(Ts)>;
            using bitset_initializer_t = unsigned long long;
            bitset_initializer_t value{0};
            return bitset_type{((value = (value << 1 | trait<Ts>::value)), ...)};
        }
        ();

        template <template <typename...> class T>
        using as_t = T<typename trait<Ts>::type...>;
        template <template <typename...> class T>
        constexpr static auto as_v = T{trait<Ts>::value...};

        using as_tuple_t = as_t<std::tuple>;
        constexpr static auto as_tuple_v = std::tuple{trait<Ts>::value...};

        template <class Int = int>
        using as_integer_sequence = std::integer_sequence<Int, trait<Ts>::value...>;

        // constexpr static auto as_array_v = std::array{trait<Ts>::value...}; // OK with GCC 10.2
        using as_array_t = std::array<std::tuple_element_t<0, decltype(std::tuple{trait<Ts>::value...})>, sizeof...(Ts)>;
        constexpr static auto as_array_v = as_array_t{trait<Ts>::value...};
    };
}

namespace gcl::mp::type_traits::tests::is_brace_constructible_v
{
    struct toto {
        int i;
    };
    struct titi {
        explicit titi(int) {}
    };

    static_assert(type_traits::is_brace_constructible_v<toto>);
    static_assert(type_traits::is_brace_constructible_v<toto, int>);
    static_assert(type_traits::is_brace_constructible_v<toto, char>);
    static_assert(not type_traits::is_brace_constructible_v<toto, char*>);
    static_assert(not type_traits::is_brace_constructible_v<titi>);
    static_assert(type_traits::is_brace_constructible_v<titi, int>);
    static_assert(type_traits::is_brace_constructible_v<titi, char>);
    static_assert(not type_traits::is_brace_constructible_v<titi, char*>);
}
namespace gcl::mp::type_traits::tests::if_t
{
    static_assert(std::is_same_v<type_traits::if_t<true>, std::true_type>);
    static_assert(std::is_same_v<type_traits::if_t<false>, std::false_type>);
    static_assert(type_traits::if_v<true> == true);
    static_assert(type_traits::if_v<false> == false);
}
#if __cpp_concepts
#include <concepts>
namespace gcl::mp::type_traits::tests::if_t
{
    // clang-format off
    template <typename T>
    concept is_red_colored = requires(T)
    {
        { T::color == decltype(T::color)::red } -> std::convertible_to<bool>;
        { type_traits::if_t<T::color == decltype(T::color)::red>{}} -> std::same_as<std::true_type>;
    };
    enum colors { red, blue, green };
    struct smthg_blue { constexpr static auto color = colors::blue; };
    struct smthg_red { constexpr static auto color = colors::red; };
    // clang-format on

    static_assert(not is_red_colored<smthg_blue>);
    static_assert(is_red_colored<smthg_red>);
}
#endif
namespace gcl::mp::type_traits::tests::trait_results
{
    template <typename T>
    using is_int = std::is_same<int, T>;
    using results = trait_result<is_int, char, int, bool>;

    // static_assert(decltype(results::as_bitset_v){2UL} == results::as_bitset_v); // std::bitset::operator== is not cx
    constexpr auto expected_result_as_bitset = decltype(results::as_bitset_v){2UL};
    static_assert(expected_result_as_bitset[0] == results::as_bitset_v[0]);
    static_assert(expected_result_as_bitset[1] == results::as_bitset_v[1]);
    static_assert(expected_result_as_bitset[2] == results::as_bitset_v[2]);

    using results_as_tuple = results::as_t<std::tuple>;
    using results_as_tuple_value_type = std::decay_t<decltype(results::as_v<std::tuple>)>;
    static_assert(std::tuple_size_v<results_as_tuple> == std::tuple_size_v<results_as_tuple_value_type>);

    using expected_result_as_tuple = std::tuple<std::false_type, std::true_type, std::false_type>;
    static_assert(std::is_same_v<results::as_t<std::tuple>, expected_result_as_tuple>);
    static_assert(std::is_same_v<results::as_integer_sequence<int>, std::integer_sequence<int, 0, 1, 0>>);
    static_assert(results::as_array_v == std::array{false, true, false});

    template <typename... Ts>
    struct type_pack {};
    using results_as_type_pack = results::as_t<type_pack>;
    using expected_result_as_type_pack = type_pack<std::false_type, std::true_type, std::false_type>;
    static_assert(std::is_same_v<results_as_type_pack, expected_result_as_type_pack>);
}<|endoftext|>


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

#include "config.h"

#include "auto_mem.hh"
#include "ansi_scrubber.hh"
#include "view_curses.hh"
#include "attr_line.hh"

attr_line_t &attr_line_t::with_ansi_string(const char *str, ...)
{
    auto_mem<char> formatted_str;
    va_list args;

    va_start(args, str);
    auto ret = vasprintf(formatted_str.out(), str, args);
    va_end(args);

    if (ret >= 0 && formatted_str != nullptr) {
        this->al_string = formatted_str;
        scrub_ansi_string(this->al_string, this->al_attrs);
    }

    return *this;
}

attr_line_t &attr_line_t::with_ansi_string(const std::string &str)
{
    this->al_string = str;
    scrub_ansi_string(this->al_string, this->al_attrs);

    return *this;
}

attr_line_t &attr_line_t::insert(size_t index, const attr_line_t &al, text_wrap_settings *tws)
{
    if (index < this->al_string.length()) {
        shift_string_attrs(this->al_attrs, index, al.al_string.length());
    }

    this->al_string.insert(index, al.al_string);

    for (auto &sa : al.al_attrs) {
        this->al_attrs.emplace_back(sa);

        line_range &lr = this->al_attrs.back().sa_range;

        lr.shift(0, index);
        if (lr.lr_end == -1) {
            lr.lr_end = index + al.al_string.length();
        }
    }

    if (tws != nullptr && (int)this->al_string.length() > tws->tws_width) {
        ssize_t start_pos = index;
        ssize_t line_start = this->al_string.rfind('\n', start_pos);

        if (line_start == (ssize_t) std::string::npos) {
            line_start = 0;
        } else {
            line_start += 1;
        }

        ssize_t line_len = index - line_start;
        ssize_t usable_width = tws->tws_width - tws->tws_indent;
        ssize_t avail = std::max((ssize_t) 0, (ssize_t) tws->tws_width - line_len);

        if (avail == 0) {
            avail = INT_MAX;
        }

        while (start_pos < (int)this->al_string.length()) {
            ssize_t lpc;

            // Find the end of a word or a breakpoint.
            for (lpc = start_pos;
                 lpc < (int)this->al_string.length() &&
                 (isalnum(this->al_string[lpc]) ||
                  this->al_string[lpc] == ',' ||
                  this->al_string[lpc] == '_' ||
                  this->al_string[lpc] == '.' ||
                  this->al_string[lpc] == ';');
                 lpc++) {
                if (this->al_string[lpc] == '-' ||
                    this->al_string[lpc] == '.') {
                    lpc += 1;
                    break;
                }
            }

            if ((avail != usable_width) && (lpc - start_pos > avail)) {
                // Need to wrap the word.  Do the wrap.
                this->insert(start_pos, 1, '\n')
                    .insert(start_pos + 1, tws->tws_indent, ' ');
                start_pos += 1 + tws->tws_indent;
                avail = tws->tws_width - tws->tws_indent;
            } else {
                // There's still room to add stuff.
                avail -= (lpc - start_pos);
                while (lpc < (int)this->al_string.length() && avail) {
                    if (this->al_string[lpc] == '\n') {
                        this->insert(lpc + 1, tws->tws_indent, ' ');
                        avail = usable_width;
                        lpc += 1 + tws->tws_indent;
                        break;
                    }
                    if (isalnum(this->al_string[lpc]) ||
                        this->al_string[lpc] == '_') {
                        break;
                    }
                    avail -= 1;
                    lpc += 1;
                }
                start_pos = lpc;
                if (!avail) {
                    this->insert(start_pos, 1, '\n')
                        .insert(start_pos + 1, tws->tws_indent, ' ');
                    start_pos += 1 + tws->tws_indent;
                    avail = usable_width;

                    for (lpc = start_pos;
                         lpc < (int)this->al_string.length() &&
                         this->al_string[lpc] == ' ';
                         lpc++) {
                    }

                    if (lpc != start_pos) {
                        this->erase(start_pos, (lpc - start_pos));
                    }
                }
            }
        }
    }

    return *this;
}

attr_line_t attr_line_t::subline(size_t start, size_t len) const
{
    if (len == std::string::npos) {
        len = this->al_string.length() - start;
    }

    line_range lr{(int) start, (int) (start + len)};
    attr_line_t retval;

    retval.al_string = this->al_string.substr(start, len);
    for (auto &sa : this->al_attrs) {
        if (!lr.intersects(sa.sa_range)) {
            continue;
        }

        retval.al_attrs.emplace_back(lr.intersection(sa.sa_range)
                                         .shift(lr.lr_start, -lr.lr_start),
                                     sa.sa_type, sa.sa_value);

        line_range &last_lr = retval.al_attrs.back().sa_range;

        ensure(last_lr.lr_end <= (int) retval.al_string.length());
    }

    return retval;
}

void attr_line_t::split_lines(std::vector<attr_line_t> &lines) const
{
    size_t pos = 0, next_line;

    while ((next_line = this->al_string.find('\n', pos)) != std::string::npos) {
        lines.emplace_back(this->subline(pos, next_line - pos));
        pos = next_line + 1;
    }
    lines.emplace_back(this->subline(pos));
}

attr_line_t &attr_line_t::right_justify(unsigned long width)
{
    long padding = width - this->length();
    if (padding > 0) {
        this->al_string.insert(0, padding, ' ');
        for (auto &al_attr : this->al_attrs) {
            if (al_attr.sa_range.lr_start > 0) {
                al_attr.sa_range.lr_start += padding;
            }
            if (al_attr.sa_range.lr_end != -1) {
                al_attr.sa_range.lr_end += padding;
            }
        }
    }

    return *this;
}

size_t attr_line_t::nearest_text(size_t x) const
{
    if (x > 0 && (int)x >= this->length()) {
        if (this->empty()) {
            x = 0;
        } else {
            x = this->length() - 1;
        }
    }

    while (x > 0 && isspace(this->al_string[x])) {
        x -= 1;
    }

    return x;
}

void attr_line_t::apply_hide()
{
    auto& vc = view_colors::singleton();
    auto& sa = this->al_attrs;

    for (auto &sattr : sa) {
        if (sattr.sa_type == &SA_HIDDEN &&
            sattr.sa_range.length() > 3) {
            struct line_range &lr = sattr.sa_range;

            std::for_each(sa.begin(), sa.end(), [&] (string_attr &attr) {
                if (attr.sa_type == &view_curses::VC_STYLE &&
                    lr.contains(attr.sa_range)) {
                    attr.sa_type = &SA_REMOVED;
                }
            });

            this->al_string.replace(lr.lr_start, lr.length(), "\xE2\x8B\xAE");
            shift_string_attrs(sa, lr.lr_start + 1, -(lr.length() - 3));
            sattr.sa_type = &view_curses::VC_STYLE;
            sattr.sa_value.sav_int = vc.attrs_for_role(view_colors::VCR_HIDDEN);
            lr.lr_end = lr.lr_start + 3;

        }
    }
}
<commit_msg>[build] missing include<commit_after>/**
 * Copyright (c) 2020, Timothy Stack
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 * * Neither the name of Timothy Stack nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"

#include <algorithm>

#include "auto_mem.hh"
#include "ansi_scrubber.hh"
#include "view_curses.hh"
#include "attr_line.hh"

attr_line_t &attr_line_t::with_ansi_string(const char *str, ...)
{
    auto_mem<char> formatted_str;
    va_list args;

    va_start(args, str);
    auto ret = vasprintf(formatted_str.out(), str, args);
    va_end(args);

    if (ret >= 0 && formatted_str != nullptr) {
        this->al_string = formatted_str;
        scrub_ansi_string(this->al_string, this->al_attrs);
    }

    return *this;
}

attr_line_t &attr_line_t::with_ansi_string(const std::string &str)
{
    this->al_string = str;
    scrub_ansi_string(this->al_string, this->al_attrs);

    return *this;
}

attr_line_t &attr_line_t::insert(size_t index, const attr_line_t &al, text_wrap_settings *tws)
{
    if (index < this->al_string.length()) {
        shift_string_attrs(this->al_attrs, index, al.al_string.length());
    }

    this->al_string.insert(index, al.al_string);

    for (auto &sa : al.al_attrs) {
        this->al_attrs.emplace_back(sa);

        line_range &lr = this->al_attrs.back().sa_range;

        lr.shift(0, index);
        if (lr.lr_end == -1) {
            lr.lr_end = index + al.al_string.length();
        }
    }

    if (tws != nullptr && (int)this->al_string.length() > tws->tws_width) {
        ssize_t start_pos = index;
        ssize_t line_start = this->al_string.rfind('\n', start_pos);

        if (line_start == (ssize_t) std::string::npos) {
            line_start = 0;
        } else {
            line_start += 1;
        }

        ssize_t line_len = index - line_start;
        ssize_t usable_width = tws->tws_width - tws->tws_indent;
        ssize_t avail = std::max((ssize_t) 0, (ssize_t) tws->tws_width - line_len);

        if (avail == 0) {
            avail = INT_MAX;
        }

        while (start_pos < (int)this->al_string.length()) {
            ssize_t lpc;

            // Find the end of a word or a breakpoint.
            for (lpc = start_pos;
                 lpc < (int)this->al_string.length() &&
                 (isalnum(this->al_string[lpc]) ||
                  this->al_string[lpc] == ',' ||
                  this->al_string[lpc] == '_' ||
                  this->al_string[lpc] == '.' ||
                  this->al_string[lpc] == ';');
                 lpc++) {
                if (this->al_string[lpc] == '-' ||
                    this->al_string[lpc] == '.') {
                    lpc += 1;
                    break;
                }
            }

            if ((avail != usable_width) && (lpc - start_pos > avail)) {
                // Need to wrap the word.  Do the wrap.
                this->insert(start_pos, 1, '\n')
                    .insert(start_pos + 1, tws->tws_indent, ' ');
                start_pos += 1 + tws->tws_indent;
                avail = tws->tws_width - tws->tws_indent;
            } else {
                // There's still room to add stuff.
                avail -= (lpc - start_pos);
                while (lpc < (int)this->al_string.length() && avail) {
                    if (this->al_string[lpc] == '\n') {
                        this->insert(lpc + 1, tws->tws_indent, ' ');
                        avail = usable_width;
                        lpc += 1 + tws->tws_indent;
                        break;
                    }
                    if (isalnum(this->al_string[lpc]) ||
                        this->al_string[lpc] == '_') {
                        break;
                    }
                    avail -= 1;
                    lpc += 1;
                }
                start_pos = lpc;
                if (!avail) {
                    this->insert(start_pos, 1, '\n')
                        .insert(start_pos + 1, tws->tws_indent, ' ');
                    start_pos += 1 + tws->tws_indent;
                    avail = usable_width;

                    for (lpc = start_pos;
                         lpc < (int)this->al_string.length() &&
                         this->al_string[lpc] == ' ';
                         lpc++) {
                    }

                    if (lpc != start_pos) {
                        this->erase(start_pos, (lpc - start_pos));
                    }
                }
            }
        }
    }

    return *this;
}

attr_line_t attr_line_t::subline(size_t start, size_t len) const
{
    if (len == std::string::npos) {
        len = this->al_string.length() - start;
    }

    line_range lr{(int) start, (int) (start + len)};
    attr_line_t retval;

    retval.al_string = this->al_string.substr(start, len);
    for (auto &sa : this->al_attrs) {
        if (!lr.intersects(sa.sa_range)) {
            continue;
        }

        retval.al_attrs.emplace_back(lr.intersection(sa.sa_range)
                                         .shift(lr.lr_start, -lr.lr_start),
                                     sa.sa_type, sa.sa_value);

        line_range &last_lr = retval.al_attrs.back().sa_range;

        ensure(last_lr.lr_end <= (int) retval.al_string.length());
    }

    return retval;
}

void attr_line_t::split_lines(std::vector<attr_line_t> &lines) const
{
    size_t pos = 0, next_line;

    while ((next_line = this->al_string.find('\n', pos)) != std::string::npos) {
        lines.emplace_back(this->subline(pos, next_line - pos));
        pos = next_line + 1;
    }
    lines.emplace_back(this->subline(pos));
}

attr_line_t &attr_line_t::right_justify(unsigned long width)
{
    long padding = width - this->length();
    if (padding > 0) {
        this->al_string.insert(0, padding, ' ');
        for (auto &al_attr : this->al_attrs) {
            if (al_attr.sa_range.lr_start > 0) {
                al_attr.sa_range.lr_start += padding;
            }
            if (al_attr.sa_range.lr_end != -1) {
                al_attr.sa_range.lr_end += padding;
            }
        }
    }

    return *this;
}

size_t attr_line_t::nearest_text(size_t x) const
{
    if (x > 0 && (int)x >= this->length()) {
        if (this->empty()) {
            x = 0;
        } else {
            x = this->length() - 1;
        }
    }

    while (x > 0 && isspace(this->al_string[x])) {
        x -= 1;
    }

    return x;
}

void attr_line_t::apply_hide()
{
    auto& vc = view_colors::singleton();
    auto& sa = this->al_attrs;

    for (auto &sattr : sa) {
        if (sattr.sa_type == &SA_HIDDEN &&
            sattr.sa_range.length() > 3) {
            struct line_range &lr = sattr.sa_range;

            std::for_each(sa.begin(), sa.end(), [&] (string_attr &attr) {
                if (attr.sa_type == &view_curses::VC_STYLE &&
                    lr.contains(attr.sa_range)) {
                    attr.sa_type = &SA_REMOVED;
                }
            });

            this->al_string.replace(lr.lr_start, lr.length(), "\xE2\x8B\xAE");
            shift_string_attrs(sa, lr.lr_start + 1, -(lr.length() - 3));
            sattr.sa_type = &view_curses::VC_STYLE;
            sattr.sa_value.sav_int = vc.attrs_for_role(view_colors::VCR_HIDDEN);
            lr.lr_end = lr.lr_start + 3;

        }
    }
}
<|endoftext|>


<commit_before>
#include "rtkTestConfiguration.h"
#include "rtkThreeDCircularProjectionGeometryXMLFile.h"
#include "rtkRayBoxIntersectionImageFilter.h"
#include "rtkSheppLoganPhantomFilter.h"
#include "rtkDrawSheppLoganFilter.h"
#include "rtkConstantImageSource.h"

#ifdef USE_CUDA
#  include "rtkCudaForwardProjectionImageFilter.h"
#else
#  include "rtkJosephForwardProjectionImageFilter.h"
#endif

template<class TImage1, class TImage2>
#if FAST_TESTS_NO_CHECKS
void CheckImageQuality(typename TImage::Pointer itkNotUsed(recon), typename TImage::Pointer itkNotUsed(ref))
{
}
#else
void CheckImageQuality(typename TImage1::Pointer recon, typename TImage2::Pointer ref)
{
  typedef itk::ImageRegionConstIterator<TImage1> ImageIteratorType1;
  typedef itk::ImageRegionConstIterator<TImage2> ImageIteratorType2;
  ImageIteratorType1 itTest( recon, recon->GetBufferedRegion() );
  ImageIteratorType2 itRef( ref, ref->GetBufferedRegion() );

  typedef double ErrorType;
  ErrorType TestError = 0.;
  ErrorType EnerError = 0.;

  itTest.GoToBegin();
  itRef.GoToBegin();

  while( !itRef.IsAtEnd() )
    {
    typename TImage1::PixelType TestVal = itTest.Get();
    typename TImage2::PixelType RefVal = itRef.Get();

    if( TestVal != RefVal )
      {
      TestError += vcl_abs(RefVal - TestVal);
      EnerError += vcl_pow(ErrorType(RefVal - TestVal), 2.);
      }
    ++itTest;
    ++itRef;
    }
  // Error per Pixel
  ErrorType ErrorPerPixel = TestError/recon->GetBufferedRegion().GetNumberOfPixels();
  std::cout << "\nError per Pixel = " << ErrorPerPixel << std::endl;
  // MSE
  ErrorType MSE = EnerError/ref->GetBufferedRegion().GetNumberOfPixels();
  std::cout << "MSE = " << MSE << std::endl;
  // PSNR
  ErrorType PSNR = 20*log10(255.0) - 10*log10(MSE);
  std::cout << "PSNR = " << PSNR << "dB" << std::endl;
  // QI
  ErrorType QI = (255.0-ErrorPerPixel)/255.0;
  std::cout << "QI = " << QI << std::endl;

  // Checking results
  if (ErrorPerPixel > 1.28)
    {
    std::cerr << "Test Failed, Error per pixel not valid! "
              << ErrorPerPixel << " instead of 1.28" << std::endl;
    //exit( EXIT_FAILURE);
    }
  if (PSNR < 44.)
    {
    std::cerr << "Test Failed, PSNR not valid! "
              << PSNR << " instead of 44" << std::endl;
    //exit( EXIT_FAILURE);
    }
#endif
}

int main(int , char** )
{
  const unsigned int Dimension = 3;
  typedef float                                    OutputPixelType;

#ifdef USE_CUDA
  typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType;
#else
  typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
#endif

  typedef itk::Image< OutputPixelType, Dimension > OutputImageType2;

  typedef itk::Vector<double, 3>                   VectorType;
#if FAST_TESTS_NO_CHECKS
  const unsigned int NumberOfProjectionImages = 3;
#else
  const unsigned int NumberOfProjectionImages = 45;
#endif

  // Constant image sources
  typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType;
  ConstantImageSourceType::PointType origin;
  ConstantImageSourceType::SizeType size;
  ConstantImageSourceType::SpacingType spacing;

  // The test projects a volume filled with ones. The forward projector should
  // then return the intersection of the ray with the box and it is compared
  // with the analytical intersection of a box with a ray.

  // Create Joseph Forward Projector volume input.
  const ConstantImageSourceType::Pointer volInput = ConstantImageSourceType::New();
  origin[0] = -126;
  origin[1] = -126;
  origin[2] = -126;
#if FAST_TESTS_NO_CHECKS
  size[0] = 2;
  size[1] = 2;
  size[2] = 2;
  spacing[0] = 252.;
  spacing[1] = 252.;
  spacing[2] = 252.;
#else
  size[0] = 64;
  size[1] = 64;
  size[2] = 64;
  spacing[0] = 4.;
  spacing[1] = 4.;
  spacing[2] = 4.;
#endif
  volInput->SetOrigin( origin );
  volInput->SetSpacing( spacing );
  volInput->SetSize( size );
  volInput->SetConstant( 1. );
  volInput->UpdateOutputInformation();

  // Initialization Volume, it is used in the Joseph Forward Projector and in the
  // Ray Box Intersection Filter in order to initialize the stack of projections.
  const ConstantImageSourceType::Pointer projInput = ConstantImageSourceType::New();
  size[2] = NumberOfProjectionImages;
  projInput->SetOrigin( origin );
  projInput->SetSpacing( spacing );
  projInput->SetSize( size );
  projInput->SetConstant( 0. );
  projInput->Update();

  // Joseph Forward Projection filter
#ifdef USE_CUDA
  typedef rtk::CudaForwardProjectionImageFilter JFPType;
#else
  typedef rtk::JosephForwardProjectionImageFilter<OutputImageType, OutputImageType> JFPType;
#endif
  JFPType::Pointer jfp = JFPType::New();
  jfp->InPlaceOff();
  jfp->SetInput( projInput->GetOutput() );
  jfp->SetInput( 1, volInput->GetOutput() );

  // Ray Box Intersection filter (reference)
  typedef rtk::RayBoxIntersectionImageFilter<OutputImageType2, OutputImageType2> RBIType;
  RBIType::Pointer rbi = RBIType::New();
  rbi->InPlaceOff();
  rbi->SetInput( projInput->GetOutput() );
  VectorType boxMin, boxMax;
  boxMin[0] = -126.0;
  boxMin[1] = -126.0;
  boxMin[2] = -126.0;
  boxMax[0] =  126.0;
  boxMax[1] =  126.0;
  boxMax[2] =   47.6;
  rbi->SetBoxMin(boxMin);
  rbi->SetBoxMax(boxMax);

  std::cout << "\n\n****** Case 1: inner ray source ******" << std::endl;
  // The circle is divided in 4 quarters
  for(int q=0; q<4; q++) {
    // Geometry
    typedef rtk::ThreeDCircularProjectionGeometry GeometryType;
    GeometryType::Pointer geometry = GeometryType::New();
    for(unsigned int i=0; i<NumberOfProjectionImages;i++)
      {
      const double angle = -45. + i*2.;
      geometry->AddProjection(47.6 / vcl_cos(angle*itk::Math::pi/180.), 1000., q*90+angle);
      }

    if(q==0) {
      rbi->SetGeometry( geometry );
      rbi->Update();
    }

    jfp->SetGeometry(geometry);
    jfp->Update();

    CheckImageQuality<OutputImageType2, OutputImageType>(rbi->GetOutput(), jfp->GetOutput());
    std::cout << "\n\nTest of quarter #" << q << " PASSED! " << std::endl;
  }

  std::cout << "\n\n****** Case 2: outer ray source ******" << std::endl;
  boxMax[2] = 126.0;
  rbi->SetBoxMax(boxMax);

  // Geometry
  typedef rtk::ThreeDCircularProjectionGeometry GeometryType;
  GeometryType::Pointer geometry = GeometryType::New();
  for(unsigned int i=0; i<NumberOfProjectionImages; i++)
    geometry->AddProjection(500., 1000., i*8.);

  rbi->SetGeometry( geometry );
  rbi->Update();

  jfp->SetGeometry( geometry );
  jfp->Update();

  CheckImageQuality<OutputImageType2, OutputImageType>(rbi->GetOutput(), jfp->GetOutput());
  std::cout << "\n\nTest PASSED! " << std::endl;

  std::cout << "\n\n****** Case 3: Shepp-Logan, outer ray source ******" << std::endl;

  // Create Shepp Logan reference projections
  typedef rtk::SheppLoganPhantomFilter<OutputImageType2, OutputImageType2> SLPType;
  SLPType::Pointer slp = SLPType::New();
  slp->InPlaceOff();
  slp->SetInput( projInput->GetOutput() );
  slp->SetGeometry(geometry);
  slp->Update();

  // Create a Shepp Logan reference volume (finer resolution)
  origin.Fill(-127);
  size.Fill(128);
  spacing.Fill(2.);
  volInput->SetOrigin( origin );
  volInput->SetSpacing( spacing );
  volInput->SetSize( size );
  volInput->SetConstant( 0. );

  typedef rtk::DrawSheppLoganFilter<OutputImageType2, OutputImageType> DSLType;
  DSLType::Pointer dsl = DSLType::New();
  dsl->InPlaceOff();
  dsl->SetInput( volInput->GetOutput() );
  dsl->Update();

  // Forward projection
  jfp->SetInput( 1, dsl->GetOutput() );
  jfp->Update();

  CheckImageQuality<OutputImageType2, OutputImageType>(slp->GetOutput(), jfp->GetOutput());
  std::cout << "\n\nTest PASSED! " << std::endl;

  std::cout << "\n\n****** Case 4: Shepp-Logan, inner ray source ******" << std::endl;
  geometry = GeometryType::New();
  for(unsigned int i=0; i<NumberOfProjectionImages; i++)
    geometry->AddProjection(120., 1000., i*8.);

  slp->SetGeometry(geometry);
  slp->Update();

  jfp->SetGeometry( geometry );
  jfp->Update();

  CheckImageQuality<OutputImageType2, OutputImageType>(slp->GetOutput(), jfp->GetOutput());
  std::cout << "\n\nTest PASSED! " << std::endl;

  return EXIT_SUCCESS;
}
<commit_msg>Fixed compilation error in rtkforwardprojectiontest<commit_after>
#include "rtkTestConfiguration.h"
#include "rtkThreeDCircularProjectionGeometryXMLFile.h"
#include "rtkRayBoxIntersectionImageFilter.h"
#include "rtkSheppLoganPhantomFilter.h"
#include "rtkDrawSheppLoganFilter.h"
#include "rtkConstantImageSource.h"

#ifdef USE_CUDA
#  include "rtkCudaForwardProjectionImageFilter.h"
#else
#  include "rtkJosephForwardProjectionImageFilter.h"
#endif

template<class TImage1, class TImage2>
#if FAST_TESTS_NO_CHECKS
void CheckImageQuality(typename TImage::Pointer itkNotUsed(recon), typename TImage::Pointer itkNotUsed(ref))
{
}
#else
void CheckImageQuality(typename TImage1::Pointer recon, typename TImage2::Pointer ref)
{
  typedef itk::ImageRegionConstIterator<TImage1> ImageIteratorType1;
  typedef itk::ImageRegionConstIterator<TImage2> ImageIteratorType2;
  ImageIteratorType1 itTest( recon, recon->GetBufferedRegion() );
  ImageIteratorType2 itRef( ref, ref->GetBufferedRegion() );

  typedef double ErrorType;
  ErrorType TestError = 0.;
  ErrorType EnerError = 0.;

  itTest.GoToBegin();
  itRef.GoToBegin();

  while( !itRef.IsAtEnd() )
    {
    typename TImage1::PixelType TestVal = itTest.Get();
    typename TImage2::PixelType RefVal = itRef.Get();

    if( TestVal != RefVal )
      {
      TestError += vcl_abs(RefVal - TestVal);
      EnerError += vcl_pow(ErrorType(RefVal - TestVal), 2.);
      }
    ++itTest;
    ++itRef;
    }
  // Error per Pixel
  ErrorType ErrorPerPixel = TestError/recon->GetBufferedRegion().GetNumberOfPixels();
  std::cout << "\nError per Pixel = " << ErrorPerPixel << std::endl;
  // MSE
  ErrorType MSE = EnerError/ref->GetBufferedRegion().GetNumberOfPixels();
  std::cout << "MSE = " << MSE << std::endl;
  // PSNR
  ErrorType PSNR = 20*log10(255.0) - 10*log10(MSE);
  std::cout << "PSNR = " << PSNR << "dB" << std::endl;
  // QI
  ErrorType QI = (255.0-ErrorPerPixel)/255.0;
  std::cout << "QI = " << QI << std::endl;

  // Checking results
  if (ErrorPerPixel > 1.28)
    {
    std::cerr << "Test Failed, Error per pixel not valid! "
              << ErrorPerPixel << " instead of 1.28" << std::endl;
    //exit( EXIT_FAILURE);
    }
  if (PSNR < 44.)
    {
    std::cerr << "Test Failed, PSNR not valid! "
              << PSNR << " instead of 44" << std::endl;
    //exit( EXIT_FAILURE);
    }
}
#endif

int main(int , char** )
{
  const unsigned int Dimension = 3;
  typedef float                                    OutputPixelType;

#ifdef USE_CUDA
  typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType;
#else
  typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
#endif

  typedef itk::Image< OutputPixelType, Dimension > OutputImageType2;

  typedef itk::Vector<double, 3>                   VectorType;
#if FAST_TESTS_NO_CHECKS
  const unsigned int NumberOfProjectionImages = 3;
#else
  const unsigned int NumberOfProjectionImages = 45;
#endif

  // Constant image sources
  typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType;
  ConstantImageSourceType::PointType origin;
  ConstantImageSourceType::SizeType size;
  ConstantImageSourceType::SpacingType spacing;

  // The test projects a volume filled with ones. The forward projector should
  // then return the intersection of the ray with the box and it is compared
  // with the analytical intersection of a box with a ray.

  // Create Joseph Forward Projector volume input.
  const ConstantImageSourceType::Pointer volInput = ConstantImageSourceType::New();
  origin[0] = -126;
  origin[1] = -126;
  origin[2] = -126;
#if FAST_TESTS_NO_CHECKS
  size[0] = 2;
  size[1] = 2;
  size[2] = 2;
  spacing[0] = 252.;
  spacing[1] = 252.;
  spacing[2] = 252.;
#else
  size[0] = 64;
  size[1] = 64;
  size[2] = 64;
  spacing[0] = 4.;
  spacing[1] = 4.;
  spacing[2] = 4.;
#endif
  volInput->SetOrigin( origin );
  volInput->SetSpacing( spacing );
  volInput->SetSize( size );
  volInput->SetConstant( 1. );
  volInput->UpdateOutputInformation();

  // Initialization Volume, it is used in the Joseph Forward Projector and in the
  // Ray Box Intersection Filter in order to initialize the stack of projections.
  const ConstantImageSourceType::Pointer projInput = ConstantImageSourceType::New();
  size[2] = NumberOfProjectionImages;
  projInput->SetOrigin( origin );
  projInput->SetSpacing( spacing );
  projInput->SetSize( size );
  projInput->SetConstant( 0. );
  projInput->Update();

  // Joseph Forward Projection filter
#ifdef USE_CUDA
  typedef rtk::CudaForwardProjectionImageFilter JFPType;
#else
  typedef rtk::JosephForwardProjectionImageFilter<OutputImageType, OutputImageType> JFPType;
#endif
  JFPType::Pointer jfp = JFPType::New();
  jfp->InPlaceOff();
  jfp->SetInput( projInput->GetOutput() );
  jfp->SetInput( 1, volInput->GetOutput() );

  // Ray Box Intersection filter (reference)
  typedef rtk::RayBoxIntersectionImageFilter<OutputImageType2, OutputImageType2> RBIType;
  RBIType::Pointer rbi = RBIType::New();
  rbi->InPlaceOff();
  rbi->SetInput( projInput->GetOutput() );
  VectorType boxMin, boxMax;
  boxMin[0] = -126.0;
  boxMin[1] = -126.0;
  boxMin[2] = -126.0;
  boxMax[0] =  126.0;
  boxMax[1] =  126.0;
  boxMax[2] =   47.6;
  rbi->SetBoxMin(boxMin);
  rbi->SetBoxMax(boxMax);

  std::cout << "\n\n****** Case 1: inner ray source ******" << std::endl;
  // The circle is divided in 4 quarters
  for(int q=0; q<4; q++) {
    // Geometry
    typedef rtk::ThreeDCircularProjectionGeometry GeometryType;
    GeometryType::Pointer geometry = GeometryType::New();
    for(unsigned int i=0; i<NumberOfProjectionImages;i++)
      {
      const double angle = -45. + i*2.;
      geometry->AddProjection(47.6 / vcl_cos(angle*itk::Math::pi/180.), 1000., q*90+angle);
      }

    if(q==0) {
      rbi->SetGeometry( geometry );
      rbi->Update();
    }

    jfp->SetGeometry(geometry);
    jfp->Update();

    CheckImageQuality<OutputImageType2, OutputImageType>(rbi->GetOutput(), jfp->GetOutput());
    std::cout << "\n\nTest of quarter #" << q << " PASSED! " << std::endl;
  }

  std::cout << "\n\n****** Case 2: outer ray source ******" << std::endl;
  boxMax[2] = 126.0;
  rbi->SetBoxMax(boxMax);

  // Geometry
  typedef rtk::ThreeDCircularProjectionGeometry GeometryType;
  GeometryType::Pointer geometry = GeometryType::New();
  for(unsigned int i=0; i<NumberOfProjectionImages; i++)
    geometry->AddProjection(500., 1000., i*8.);

  rbi->SetGeometry( geometry );
  rbi->Update();

  jfp->SetGeometry( geometry );
  jfp->Update();

  CheckImageQuality<OutputImageType2, OutputImageType>(rbi->GetOutput(), jfp->GetOutput());
  std::cout << "\n\nTest PASSED! " << std::endl;

  std::cout << "\n\n****** Case 3: Shepp-Logan, outer ray source ******" << std::endl;

  // Create Shepp Logan reference projections
  typedef rtk::SheppLoganPhantomFilter<OutputImageType2, OutputImageType2> SLPType;
  SLPType::Pointer slp = SLPType::New();
  slp->InPlaceOff();
  slp->SetInput( projInput->GetOutput() );
  slp->SetGeometry(geometry);
  slp->Update();

  // Create a Shepp Logan reference volume (finer resolution)
  origin.Fill(-127);
  size.Fill(128);
  spacing.Fill(2.);
  volInput->SetOrigin( origin );
  volInput->SetSpacing( spacing );
  volInput->SetSize( size );
  volInput->SetConstant( 0. );

  typedef rtk::DrawSheppLoganFilter<OutputImageType2, OutputImageType> DSLType;
  DSLType::Pointer dsl = DSLType::New();
  dsl->InPlaceOff();
  dsl->SetInput( volInput->GetOutput() );
  dsl->Update();

  // Forward projection
  jfp->SetInput( 1, dsl->GetOutput() );
  jfp->Update();

  CheckImageQuality<OutputImageType2, OutputImageType>(slp->GetOutput(), jfp->GetOutput());
  std::cout << "\n\nTest PASSED! " << std::endl;

  std::cout << "\n\n****** Case 4: Shepp-Logan, inner ray source ******" << std::endl;
  geometry = GeometryType::New();
  for(unsigned int i=0; i<NumberOfProjectionImages; i++)
    geometry->AddProjection(120., 1000., i*8.);

  slp->SetGeometry(geometry);
  slp->Update();

  jfp->SetGeometry( geometry );
  jfp->Update();

  CheckImageQuality<OutputImageType2, OutputImageType>(slp->GetOutput(), jfp->GetOutput());
  std::cout << "\n\nTest PASSED! " << std::endl;

  return EXIT_SUCCESS;
}
<|endoftext|>


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

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

#ifndef _XMLOFF_XMLPAGEEXPORT_HXX
#include <xmloff/XMLPageExport.hxx>
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif

#ifndef _COM_SUN_STAR_STYLE_XSTYLEFAMILIESSUPPLIER_HPP_
#include <com/sun/star/style/XStyleFamiliesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_STYLE_XSTYLE_HPP_
#include <com/sun/star/style/XStyle.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XINDEXREPLACE_HPP_
#include <com/sun/star/container/XIndexReplace.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#ifndef _XMLOFF_FAMILIES_HXX_
#include <xmloff/families.hxx>
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include <xmloff/xmlexp.hxx>
#endif
#ifndef _XMLOFF_PAGEMASTERPROPHDLFACTORY_HXX
#include "PageMasterPropHdlFactory.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTERSTYLEMAP_HXX
#include <xmloff/PageMasterStyleMap.hxx>
#endif
#ifndef _XMLOFF_PAGEMASTERPROPMAPPER_HXX
#include "PageMasterPropMapper.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTEREXPORTPROPMAPPER_HXX
#include "PageMasterExportPropMapper.hxx"
#endif
#ifndef _XMLOFF_PAGEMASTEREXPORTPROPMAPPER_HXX
#include "PageMasterExportPropMapper.hxx"
#endif

using ::rtl::OUString;
using ::rtl::OUStringBuffer;

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::style;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::beans;
using namespace ::xmloff::token;

//______________________________________________________________________________

sal_Bool XMLPageExport::findPageMasterName( const OUString& rStyleName, OUString& rPMName ) const
{
    for( ::std::vector< XMLPageExportNameEntry >::const_iterator pEntry = aNameVector.begin();
            pEntry != aNameVector.end(); pEntry++ )
    {
        if( pEntry->sStyleName == rStyleName )
        {
            rPMName = pEntry->sPageMasterName;
            return sal_True;
        }
    }
    return sal_False;
}

void XMLPageExport::collectPageMasterAutoStyle(
        const Reference < XPropertySet > & rPropSet,
        OUString& rPageMasterName )
{
    DBG_ASSERT( xPageMasterPropSetMapper.is(), "page master family/XMLPageMasterPropSetMapper not found" );
    if( xPageMasterPropSetMapper.is() )
    {
        ::std::vector<XMLPropertyState> xPropStates = xPageMasterExportPropMapper->Filter( rPropSet );
        if( !xPropStates.empty())
        {
            OUString sParent;
            rPageMasterName = rExport.GetAutoStylePool()->Find( XML_STYLE_FAMILY_PAGE_MASTER, sParent, xPropStates );
            if (!rPageMasterName.getLength())
                rPageMasterName = rExport.GetAutoStylePool()->Add(XML_STYLE_FAMILY_PAGE_MASTER, sParent, xPropStates);
        }
    }
}

void XMLPageExport::exportMasterPageContent(
                const Reference < XPropertySet > &,
                sal_Bool /*bAutoStyles*/ )
{

}

sal_Bool XMLPageExport::exportStyle(
            const Reference< XStyle >& rStyle,
            sal_Bool bAutoStyles )
{
    Reference< XPropertySet > xPropSet( rStyle, UNO_QUERY );
    Reference< XPropertySetInfo > xPropSetInfo = xPropSet->getPropertySetInfo();

    // Don't export styles that aren't existing really. This may be the
    // case for StarOffice Writer's pool styles.
    if( xPropSetInfo->hasPropertyByName( sIsPhysical ) )
    {
        Any aAny = xPropSet->getPropertyValue( sIsPhysical );
        if( !*(sal_Bool *)aAny.getValue() )
            return sal_False;
    }

    if( bAutoStyles )
    {
        XMLPageExportNameEntry aEntry;
        collectPageMasterAutoStyle( xPropSet, aEntry.sPageMasterName );
        aEntry.sStyleName = rStyle->getName();
        aNameVector.push_back( aEntry );

        exportMasterPageContent( xPropSet, sal_True );
    }
    else
    {
        OUString sName( rStyle->getName() );
        sal_Bool bEncoded = sal_False;
        GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_NAME,
                          GetExport().EncodeStyleName( sName, &bEncoded ) );

        if( bEncoded )
            GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_DISPLAY_NAME,
                                   sName);

        OUString sPMName;
        if( findPageMasterName( sName, sPMName ) )
            GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_PAGE_LAYOUT_NAME, GetExport().EncodeStyleName( sPMName ) );

        Reference<XPropertySetInfo> xInfo = xPropSet->getPropertySetInfo();
        if ( xInfo.is() && xInfo->hasPropertyByName(sFollowStyle) )
        {
            OUString sNextName;
            xPropSet->getPropertyValue( sFollowStyle ) >>= sNextName;

            if( sName != sNextName && sNextName.getLength() )
            {
                GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_NEXT_STYLE_NAME,
                    GetExport().EncodeStyleName( sNextName ) );
            }
        }
//      OUString sPageMaster = GetExport().GetAutoStylePool()->Find(
//                                          XML_STYLE_FAMILY_PAGE_MASTER,
//                                          xPropSet );
//      if( sPageMaster.getLength() )
//          GetExport().AddAttribute( XML_NAMESPACE_STYLE,
//                                    XML_PAGE_MASTER_NAME,
//                                    sPageMaster );

        SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_STYLE,
                                  XML_MASTER_PAGE, sal_True, sal_True );

        exportMasterPageContent( xPropSet, sal_False );
    }

    return sal_True;
}

XMLPageExport::XMLPageExport( SvXMLExport& rExp ) :
    rExport( rExp ),
    sIsPhysical( RTL_CONSTASCII_USTRINGPARAM( "IsPhysical" ) ),
    sFollowStyle( RTL_CONSTASCII_USTRINGPARAM( "FollowStyle" ) )
{
    xPageMasterPropHdlFactory = new XMLPageMasterPropHdlFactory;
    xPageMasterPropSetMapper = new XMLPageMasterPropSetMapper(
                                (XMLPropertyMapEntry*) aXMLPageMasterStyleMap,
                                xPageMasterPropHdlFactory  );
    xPageMasterExportPropMapper = new XMLPageMasterExportPropMapper(
                                    xPageMasterPropSetMapper, rExp);

    rExport.GetAutoStylePool()->AddFamily( XML_STYLE_FAMILY_PAGE_MASTER, OUString( RTL_CONSTASCII_USTRINGPARAM( XML_STYLE_FAMILY_PAGE_MASTER_NAME ) ),
        xPageMasterExportPropMapper, OUString( RTL_CONSTASCII_USTRINGPARAM( XML_STYLE_FAMILY_PAGE_MASTER_PREFIX ) ), sal_False );

    Reference< XStyleFamiliesSupplier > xFamiliesSupp( GetExport().GetModel(),
                                                       UNO_QUERY );
    DBG_ASSERT( xFamiliesSupp.is(),
                "No XStyleFamiliesSupplier from XModel for export!" );
    if( xFamiliesSupp.is() )
    {
        Reference< XNameAccess > xFamilies( xFamiliesSupp->getStyleFamilies() );
        DBG_ASSERT( xFamiliesSupp.is(),
                    "getStyleFamilies() from XModel failed for export!" );
        if( xFamilies.is() )
        {
            const OUString aPageStyleName(
                        RTL_CONSTASCII_USTRINGPARAM( "PageStyles" ));

            if( xFamilies->hasByName( aPageStyleName ) )
            {
                xPageStyles.set(xFamilies->getByName( aPageStyleName ),uno::UNO_QUERY);

                DBG_ASSERT( xPageStyles.is(),
                            "Page Styles not found for export!" );
            }
        }
    }
}

XMLPageExport::~XMLPageExport()
{
}

void XMLPageExport::exportStyles( sal_Bool bUsed, sal_Bool bAutoStyles )
{
    if( xPageStyles.is() )
    {
        uno::Sequence< ::rtl::OUString> aSeq = xPageStyles->getElementNames();
        const ::rtl::OUString* pIter = aSeq.getConstArray();
        const ::rtl::OUString* pEnd   = pIter + aSeq.getLength();
        for(;pIter != pEnd;++pIter)
        {
            Reference< XStyle > xStyle(xPageStyles->getByName( *pIter ),uno::UNO_QUERY);
            if( !bUsed || xStyle->isInUse() )
                exportStyle( xStyle, bAutoStyles );
        }
    }
}

void XMLPageExport::exportAutoStyles()
{
    rExport.GetAutoStylePool()->exportXML(XML_STYLE_FAMILY_PAGE_MASTER
        , rExport.GetDocHandler(), rExport.GetMM100UnitConverter(),
        rExport.GetNamespaceMap()
        );
}

void XMLPageExport::exportDefaultStyle()
{
    Reference < lang::XMultiServiceFactory > xFactory (GetExport().GetModel(), UNO_QUERY);
    if (xFactory.is())
    {
        OUString sTextDefaults ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.text.Defaults" ) );
        Reference < XPropertySet > xPropSet (xFactory->createInstance ( sTextDefaults ), UNO_QUERY);
        if (xPropSet.is())
        {
            // <style:default-style ...>
            GetExport().CheckAttrList();

            ::std::vector< XMLPropertyState > xPropStates =
                xPageMasterExportPropMapper->FilterDefaults( xPropSet );

            sal_Bool bExport = sal_False;
            UniReference < XMLPropertySetMapper > aPropMapper(xPageMasterExportPropMapper->getPropertySetMapper());
            for( ::std::vector< XMLPropertyState >::iterator aIter = xPropStates.begin(); aIter != xPropStates.end(); ++aIter )
            {
                XMLPropertyState *pProp = &(*aIter);
                sal_Int16 nContextId    = aPropMapper->GetEntryContextId( pProp->mnIndex );
                if( nContextId == CTF_PM_STANDARD_MODE )
                {
                    bExport = sal_True;
                    break;
                }
            }

        //  if ( xPropStates.size() != 0 &&
          //          ( xPropStates.size() != 1 || xPropStates[0].mnIndex != -1 ) )
            if( bExport )
            {
                //<style:default-page-layout>
                SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_STYLE,
                                          XML_DEFAULT_PAGE_LAYOUT,
                                          sal_True, sal_True );

                xPageMasterExportPropMapper->exportXML( GetExport(), xPropStates,
                                             XML_EXPORT_FLAG_IGN_WS );
            }
        }
    }
}
<commit_msg>INTEGRATION: CWS changefileheader (1.19.18); FILE MERGED 2008/04/01 16:09:54 thb 1.19.18.3: #i85898# Stripping all external header guards 2008/04/01 13:05:00 thb 1.19.18.2: #i85898# Stripping all external header guards 2008/03/31 16:28:21 rt 1.19.18.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: XMLPageExport.cxx,v $
 * $Revision: 1.20 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#include <xmloff/XMLPageExport.hxx>
#include <tools/debug.hxx>
#include "xmlnmspe.hxx"
#include <xmloff/xmltoken.hxx>
#include <com/sun/star/style/XStyleFamiliesSupplier.hpp>
#include <com/sun/star/style/XStyle.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/container/XIndexReplace.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <xmloff/families.hxx>
#include <xmloff/xmlexp.hxx>
#include "PageMasterPropHdlFactory.hxx"
#ifndef _XMLOFF_PAGEMASTERSTYLEMAP_HXX
#include <xmloff/PageMasterStyleMap.hxx>
#endif
#ifndef _XMLOFF_PAGEMASTERPROPMAPPER_HXX
#include "PageMasterPropMapper.hxx"
#endif
#include "PageMasterExportPropMapper.hxx"
#include "PageMasterExportPropMapper.hxx"

using ::rtl::OUString;
using ::rtl::OUStringBuffer;

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::style;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::beans;
using namespace ::xmloff::token;

//______________________________________________________________________________

sal_Bool XMLPageExport::findPageMasterName( const OUString& rStyleName, OUString& rPMName ) const
{
    for( ::std::vector< XMLPageExportNameEntry >::const_iterator pEntry = aNameVector.begin();
            pEntry != aNameVector.end(); pEntry++ )
    {
        if( pEntry->sStyleName == rStyleName )
        {
            rPMName = pEntry->sPageMasterName;
            return sal_True;
        }
    }
    return sal_False;
}

void XMLPageExport::collectPageMasterAutoStyle(
        const Reference < XPropertySet > & rPropSet,
        OUString& rPageMasterName )
{
    DBG_ASSERT( xPageMasterPropSetMapper.is(), "page master family/XMLPageMasterPropSetMapper not found" );
    if( xPageMasterPropSetMapper.is() )
    {
        ::std::vector<XMLPropertyState> xPropStates = xPageMasterExportPropMapper->Filter( rPropSet );
        if( !xPropStates.empty())
        {
            OUString sParent;
            rPageMasterName = rExport.GetAutoStylePool()->Find( XML_STYLE_FAMILY_PAGE_MASTER, sParent, xPropStates );
            if (!rPageMasterName.getLength())
                rPageMasterName = rExport.GetAutoStylePool()->Add(XML_STYLE_FAMILY_PAGE_MASTER, sParent, xPropStates);
        }
    }
}

void XMLPageExport::exportMasterPageContent(
                const Reference < XPropertySet > &,
                sal_Bool /*bAutoStyles*/ )
{

}

sal_Bool XMLPageExport::exportStyle(
            const Reference< XStyle >& rStyle,
            sal_Bool bAutoStyles )
{
    Reference< XPropertySet > xPropSet( rStyle, UNO_QUERY );
    Reference< XPropertySetInfo > xPropSetInfo = xPropSet->getPropertySetInfo();

    // Don't export styles that aren't existing really. This may be the
    // case for StarOffice Writer's pool styles.
    if( xPropSetInfo->hasPropertyByName( sIsPhysical ) )
    {
        Any aAny = xPropSet->getPropertyValue( sIsPhysical );
        if( !*(sal_Bool *)aAny.getValue() )
            return sal_False;
    }

    if( bAutoStyles )
    {
        XMLPageExportNameEntry aEntry;
        collectPageMasterAutoStyle( xPropSet, aEntry.sPageMasterName );
        aEntry.sStyleName = rStyle->getName();
        aNameVector.push_back( aEntry );

        exportMasterPageContent( xPropSet, sal_True );
    }
    else
    {
        OUString sName( rStyle->getName() );
        sal_Bool bEncoded = sal_False;
        GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_NAME,
                          GetExport().EncodeStyleName( sName, &bEncoded ) );

        if( bEncoded )
            GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_DISPLAY_NAME,
                                   sName);

        OUString sPMName;
        if( findPageMasterName( sName, sPMName ) )
            GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_PAGE_LAYOUT_NAME, GetExport().EncodeStyleName( sPMName ) );

        Reference<XPropertySetInfo> xInfo = xPropSet->getPropertySetInfo();
        if ( xInfo.is() && xInfo->hasPropertyByName(sFollowStyle) )
        {
            OUString sNextName;
            xPropSet->getPropertyValue( sFollowStyle ) >>= sNextName;

            if( sName != sNextName && sNextName.getLength() )
            {
                GetExport().AddAttribute( XML_NAMESPACE_STYLE, XML_NEXT_STYLE_NAME,
                    GetExport().EncodeStyleName( sNextName ) );
            }
        }
//      OUString sPageMaster = GetExport().GetAutoStylePool()->Find(
//                                          XML_STYLE_FAMILY_PAGE_MASTER,
//                                          xPropSet );
//      if( sPageMaster.getLength() )
//          GetExport().AddAttribute( XML_NAMESPACE_STYLE,
//                                    XML_PAGE_MASTER_NAME,
//                                    sPageMaster );

        SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_STYLE,
                                  XML_MASTER_PAGE, sal_True, sal_True );

        exportMasterPageContent( xPropSet, sal_False );
    }

    return sal_True;
}

XMLPageExport::XMLPageExport( SvXMLExport& rExp ) :
    rExport( rExp ),
    sIsPhysical( RTL_CONSTASCII_USTRINGPARAM( "IsPhysical" ) ),
    sFollowStyle( RTL_CONSTASCII_USTRINGPARAM( "FollowStyle" ) )
{
    xPageMasterPropHdlFactory = new XMLPageMasterPropHdlFactory;
    xPageMasterPropSetMapper = new XMLPageMasterPropSetMapper(
                                (XMLPropertyMapEntry*) aXMLPageMasterStyleMap,
                                xPageMasterPropHdlFactory  );
    xPageMasterExportPropMapper = new XMLPageMasterExportPropMapper(
                                    xPageMasterPropSetMapper, rExp);

    rExport.GetAutoStylePool()->AddFamily( XML_STYLE_FAMILY_PAGE_MASTER, OUString( RTL_CONSTASCII_USTRINGPARAM( XML_STYLE_FAMILY_PAGE_MASTER_NAME ) ),
        xPageMasterExportPropMapper, OUString( RTL_CONSTASCII_USTRINGPARAM( XML_STYLE_FAMILY_PAGE_MASTER_PREFIX ) ), sal_False );

    Reference< XStyleFamiliesSupplier > xFamiliesSupp( GetExport().GetModel(),
                                                       UNO_QUERY );
    DBG_ASSERT( xFamiliesSupp.is(),
                "No XStyleFamiliesSupplier from XModel for export!" );
    if( xFamiliesSupp.is() )
    {
        Reference< XNameAccess > xFamilies( xFamiliesSupp->getStyleFamilies() );
        DBG_ASSERT( xFamiliesSupp.is(),
                    "getStyleFamilies() from XModel failed for export!" );
        if( xFamilies.is() )
        {
            const OUString aPageStyleName(
                        RTL_CONSTASCII_USTRINGPARAM( "PageStyles" ));

            if( xFamilies->hasByName( aPageStyleName ) )
            {
                xPageStyles.set(xFamilies->getByName( aPageStyleName ),uno::UNO_QUERY);

                DBG_ASSERT( xPageStyles.is(),
                            "Page Styles not found for export!" );
            }
        }
    }
}

XMLPageExport::~XMLPageExport()
{
}

void XMLPageExport::exportStyles( sal_Bool bUsed, sal_Bool bAutoStyles )
{
    if( xPageStyles.is() )
    {
        uno::Sequence< ::rtl::OUString> aSeq = xPageStyles->getElementNames();
        const ::rtl::OUString* pIter = aSeq.getConstArray();
        const ::rtl::OUString* pEnd   = pIter + aSeq.getLength();
        for(;pIter != pEnd;++pIter)
        {
            Reference< XStyle > xStyle(xPageStyles->getByName( *pIter ),uno::UNO_QUERY);
            if( !bUsed || xStyle->isInUse() )
                exportStyle( xStyle, bAutoStyles );
        }
    }
}

void XMLPageExport::exportAutoStyles()
{
    rExport.GetAutoStylePool()->exportXML(XML_STYLE_FAMILY_PAGE_MASTER
        , rExport.GetDocHandler(), rExport.GetMM100UnitConverter(),
        rExport.GetNamespaceMap()
        );
}

void XMLPageExport::exportDefaultStyle()
{
    Reference < lang::XMultiServiceFactory > xFactory (GetExport().GetModel(), UNO_QUERY);
    if (xFactory.is())
    {
        OUString sTextDefaults ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.text.Defaults" ) );
        Reference < XPropertySet > xPropSet (xFactory->createInstance ( sTextDefaults ), UNO_QUERY);
        if (xPropSet.is())
        {
            // <style:default-style ...>
            GetExport().CheckAttrList();

            ::std::vector< XMLPropertyState > xPropStates =
                xPageMasterExportPropMapper->FilterDefaults( xPropSet );

            sal_Bool bExport = sal_False;
            UniReference < XMLPropertySetMapper > aPropMapper(xPageMasterExportPropMapper->getPropertySetMapper());
            for( ::std::vector< XMLPropertyState >::iterator aIter = xPropStates.begin(); aIter != xPropStates.end(); ++aIter )
            {
                XMLPropertyState *pProp = &(*aIter);
                sal_Int16 nContextId    = aPropMapper->GetEntryContextId( pProp->mnIndex );
                if( nContextId == CTF_PM_STANDARD_MODE )
                {
                    bExport = sal_True;
                    break;
                }
            }

        //  if ( xPropStates.size() != 0 &&
          //          ( xPropStates.size() != 1 || xPropStates[0].mnIndex != -1 ) )
            if( bExport )
            {
                //<style:default-page-layout>
                SvXMLElementExport aElem( GetExport(), XML_NAMESPACE_STYLE,
                                          XML_DEFAULT_PAGE_LAYOUT,
                                          sal_True, sal_True );

                xPageMasterExportPropMapper->exportXML( GetExport(), xPropStates,
                                             XML_EXPORT_FLAG_IGN_WS );
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Moved the definition of the UserViewMap to the IPTVTopologyOracle, as it belonged here, and added a comment to explain its functionality<commit_after><|endoftext|>