<commit_before>#include "sess.h"
#include "encoding.h"
#include <iostream>
#include <sys/socket.h>
#include <sys/fcntl.h>
#include <arpa/inet.h>
#include <unistd.h>

UDPSession *
UDPSession::Dial(const char *ip, uint16_t port) {
    struct sockaddr_in saddr;
    memset(&saddr, 0, sizeof(saddr));
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(port);
    int ret = inet_pton(AF_INET, ip, &(saddr.sin_addr));

    if (ret == 1) { // do nothing
    } else if (ret == 0) { // try ipv6
        return UDPSession::dialIPv6(ip, port);
    } else if (ret == -1) {
        return nullptr;
    }

    int sockfd = socket(PF_INET, SOCK_DGRAM, 0);
    if (sockfd == -1) {
        return nullptr;
    }
    if (connect(sockfd, (struct sockaddr *) &saddr, sizeof(struct sockaddr)) < 0) {
        close(sockfd);
        return nullptr;
    }

    UDPSession *sess = UDPSession::createSession(sockfd);
    if (sess == nullptr) {
        close(sockfd);
        return nullptr;
    }
    return sess;
}

UDPSession *
UDPSession::DialWithOptions(const char *ip, uint16_t port, size_t dataShards, size_t parityShards) {
    auto sess = UDPSession::Dial(ip, port);
    if (sess == nullptr) {
        return nullptr;
    }

    if (dataShards >0 && parityShards > 0) {
        sess->fec = FEC::New(3*(dataShards + parityShards), dataShards, parityShards);
        sess->shards.resize(dataShards + parityShards, nullptr);
        sess->dataShards = dataShards;
        sess->parityShards = parityShards;
    }
    return sess;
};

UDPSession *
UDPSession::dialIPv6(const char *ip, uint16_t port) {
    struct sockaddr_in6 saddr;
    memset(&saddr, 0, sizeof(saddr));
    saddr.sin6_family = AF_INET6;
    saddr.sin6_port = htons(port);
    if (inet_pton(AF_INET6, ip, &(saddr.sin6_addr)) != 1) {
        return nullptr;
    }

    int sockfd = socket(PF_INET6, SOCK_DGRAM, 0);
    if (sockfd == -1) {
        return nullptr;
    }
    if (connect(sockfd, (struct sockaddr *) &saddr, sizeof(struct sockaddr_in6)) < 0) {
        close(sockfd);
        return nullptr;
    }

    UDPSession *sess = UDPSession::createSession(sockfd);
    if (sess == nullptr) {
        close(sockfd);
        return nullptr;
    }
    return sess;
}

UDPSession *
UDPSession::createSession(int sockfd) {
    int flags = fcntl(sockfd, F_GETFL, 0);
    if (flags < 0) {
        return nullptr;
    }

    if (fcntl(sockfd, F_SETFL, flags | O_NONBLOCK) < 0) {
        return nullptr;
    }

    UDPSession *sess = new(UDPSession);
    sess->m_sockfd = sockfd;
    sess->m_kcp = ikcp_create(IUINT32(rand()), sess);
    sess->m_kcp->output = sess->out_wrapper;

    if (sess->m_kcp == nullptr ) {
        ikcp_release(sess->m_kcp);
        return nullptr;
    }
    return sess;
}

void
UDPSession::Update(uint32_t current) noexcept {
    for (;;) {
        ssize_t n = recv(m_sockfd, m_buf, sizeof(m_buf), 0);
        if (n > 0) {
            if (fec.isEnabled()) {
                // decode FEC packet
                auto pkt = fec.Decode(m_buf, n);
                if (pkt.flag == typeData) {
                    auto ptr = pkt.data->data();
                    // we have 2B size, ignore for typeData
                    ikcp_input(m_kcp, (char *)(ptr+ 2), pkt.data->size() - 2);
                }

                // input to FEC, and see if we can recover data.
                auto recovered = fec.Input(pkt);

                if (recovered.size() > 0) { // some data recovered
                    for (int i =0;i<recovered.size();i++) {
                        auto ptr = recovered[i]->data();
                        uint16_t sz;
                        decode16u(ptr, &sz);
                        if (sz <= recovered[i]->size()) {
                            auto ret = ikcp_input(m_kcp, (char *) (ptr + 2), sz-2);
                            if (ret != 0) {
                                std::cout << "ikcp_input failed for recovered packet:" << ret << std::endl;
                            } else {
                                std::cout << "ikcp_input succeed for recovered packet:" << sz << ","  << n << std::endl;
                            }
                        }
                    }
                }
            } else {
                ikcp_input(m_kcp, (char *)(m_buf), n);
            }
        } else {
            break;
        }
    }
    ikcp_update(m_kcp, current);
}

void
UDPSession::Destroy(UDPSession *sess) {
    if (nullptr == sess) return;
    if (0 != sess->m_sockfd) { close(sess->m_sockfd); }
    if (nullptr != sess->m_kcp) { ikcp_release(sess->m_kcp); }
    delete sess;
}

ssize_t
UDPSession::Read(char *buf, size_t sz) noexcept {
    if (m_streambufsiz > 0) {
        size_t n = m_streambufsiz;
        if (n > sz) {
            n = sz;
        }
        memcpy(buf, m_streambuf, n);

        m_streambufsiz -= n;
        if (m_streambufsiz != 0) {
            memmove(m_streambuf, m_streambuf + n, m_streambufsiz);
        }
        return n;
    }

    int psz = ikcp_peeksize(m_kcp);
    if (psz <= 0) {
        return 0;
    }

    if (psz <= sz) {
        return (ssize_t) ikcp_recv(m_kcp, buf, int(sz));
    } else {
        ikcp_recv(m_kcp, (char*)m_streambuf, sizeof(m_streambuf));
        memcpy(buf, m_streambuf, sz);
        m_streambufsiz = psz - sz;
        memmove(m_streambuf, m_streambuf + sz, psz - sz);
        return sz;
    }
}

ssize_t
UDPSession::Write(const char *buf, size_t sz) noexcept {
    int n = ikcp_send(m_kcp, const_cast<char *>(buf), int(sz));
    if (n == 0) {
        return sz;
    } else return n;
}

int
UDPSession::SetDSCP(int iptos) noexcept {
    iptos = (iptos << 2) & 0xFF;
    return setsockopt(this->m_sockfd, IPPROTO_IP, IP_TOS,  &iptos, sizeof(iptos));
}

int
UDPSession::out_wrapper(const char *buf, int len, struct IKCPCB *, void *user) {
    assert(user != nullptr);
    UDPSession *sess = static_cast<UDPSession *>(user);

    if (sess->fec.isEnabled()) {    // append FEC header
        // extend to len + fecHeaderSizePlus2
        // i.e. 4B seqid + 2B flag + 2B size
        memcpy(sess->m_buf+fecHeaderSizePlus2, buf, static_cast<size_t>(len));
        sess->fec.MarkData(sess->m_buf, static_cast<size_t>(len));
        sess->output(sess->m_buf, len + fecHeaderSizePlus2);

        // FEC calculation
        // copy "2B size + data" to shards
        auto slen = len + 2;
        sess->shards[sess->pkt_idx] = std::make_shared<std::vector<byte>>(slen);
        sess->shards[sess->pkt_idx]->assign(sess->m_buf + fecHeaderSize, sess->m_buf + fecHeaderSize + slen);

        std::cout << "out_wrapper data packet size:" << len + fecHeaderSizePlus2 << std::endl;

        // count number of data shards
        sess->pkt_idx++;
        if (sess->pkt_idx == sess->dataShards) { // we've collected enough data shards
            auto ret = sess->fec.Encode(sess->shards);
            if (ret == 0 ) {
                // send parity shards
                for (size_t i = sess->dataShards;i<sess->dataShards+sess->parityShards;i++) {
                    // append header to parity shards
                    // i.e. fecHeaderSize + data(2B size included)
                    memcpy(sess->m_buf+fecHeaderSize, sess->shards[i]->data(), sess->shards[i]->size());
                    sess->fec.MarkFEC(sess->m_buf);
                    sess->output(sess->m_buf, sess->shards[i]->size() + fecHeaderSize);
                    std::cout << "out_wrapper parity packet size:" <<  sess->shards[i]->size() + fecHeaderSize << std::endl;
                }
            }

            // reset counting
            sess->pkt_idx = 0;
        }
    } else { // No FEC, just send raw bytes,
        sess->output(buf, static_cast<size_t>(len));
    }
    return 0;
}

ssize_t
UDPSession::output(const void *buffer, size_t length) {
    ssize_t n = send(m_sockfd, buffer, length, 0);
    return n;
}
<commit_msg>optimize<commit_after>#include "sess.h"
#include "encoding.h"
#include <iostream>
#include <sys/socket.h>
#include <sys/fcntl.h>
#include <arpa/inet.h>
#include <unistd.h>

UDPSession *
UDPSession::Dial(const char *ip, uint16_t port) {
    struct sockaddr_in saddr;
    memset(&saddr, 0, sizeof(saddr));
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(port);
    int ret = inet_pton(AF_INET, ip, &(saddr.sin_addr));

    if (ret == 1) { // do nothing
    } else if (ret == 0) { // try ipv6
        return UDPSession::dialIPv6(ip, port);
    } else if (ret == -1) {
        return nullptr;
    }

    int sockfd = socket(PF_INET, SOCK_DGRAM, 0);
    if (sockfd == -1) {
        return nullptr;
    }
    if (connect(sockfd, (struct sockaddr *) &saddr, sizeof(struct sockaddr)) < 0) {
        close(sockfd);
        return nullptr;
    }

    UDPSession *sess = UDPSession::createSession(sockfd);
    if (sess == nullptr) {
        close(sockfd);
        return nullptr;
    }
    return sess;
}

UDPSession *
UDPSession::DialWithOptions(const char *ip, uint16_t port, size_t dataShards, size_t parityShards) {
    auto sess = UDPSession::Dial(ip, port);
    if (sess == nullptr) {
        return nullptr;
    }

    if (dataShards >0 && parityShards > 0) {
        sess->fec = FEC::New(3*(dataShards + parityShards), dataShards, parityShards);
        sess->shards.resize(dataShards + parityShards, nullptr);
        sess->dataShards = dataShards;
        sess->parityShards = parityShards;
    }
    return sess;
};

UDPSession *
UDPSession::dialIPv6(const char *ip, uint16_t port) {
    struct sockaddr_in6 saddr;
    memset(&saddr, 0, sizeof(saddr));
    saddr.sin6_family = AF_INET6;
    saddr.sin6_port = htons(port);
    if (inet_pton(AF_INET6, ip, &(saddr.sin6_addr)) != 1) {
        return nullptr;
    }

    int sockfd = socket(PF_INET6, SOCK_DGRAM, 0);
    if (sockfd == -1) {
        return nullptr;
    }
    if (connect(sockfd, (struct sockaddr *) &saddr, sizeof(struct sockaddr_in6)) < 0) {
        close(sockfd);
        return nullptr;
    }

    UDPSession *sess = UDPSession::createSession(sockfd);
    if (sess == nullptr) {
        close(sockfd);
        return nullptr;
    }
    return sess;
}

UDPSession *
UDPSession::createSession(int sockfd) {
    int flags = fcntl(sockfd, F_GETFL, 0);
    if (flags < 0) {
        return nullptr;
    }

    if (fcntl(sockfd, F_SETFL, flags | O_NONBLOCK) < 0) {
        return nullptr;
    }

    UDPSession *sess = new(UDPSession);
    sess->m_sockfd = sockfd;
    sess->m_kcp = ikcp_create(IUINT32(rand()), sess);
    sess->m_kcp->output = sess->out_wrapper;

    if (sess->m_kcp == nullptr ) {
        ikcp_release(sess->m_kcp);
        return nullptr;
    }
    return sess;
}

void
UDPSession::Update(uint32_t current) noexcept {
    for (;;) {
        ssize_t n = recv(m_sockfd, m_buf, sizeof(m_buf), 0);
        if (n > 0) {
            if (fec.isEnabled()) {
                // decode FEC packet
                auto pkt = fec.Decode(m_buf, n);
                if (pkt.flag == typeData) {
                    auto ptr = pkt.data->data();
                    // we have 2B size, ignore for typeData
                    ikcp_input(m_kcp, (char *)(ptr+ 2), pkt.data->size() - 2);
                }

                // input to FEC, and see if we can recover data.
                auto recovered = fec.Input(pkt);

                if (recovered.size() > 0) { // some data recovered
                    for (int i =0;i<recovered.size();i++) {
                        auto ptr = recovered[i]->data();
                        uint16_t sz;
                        decode16u(ptr, &sz);
                        if (sz <= recovered[i]->size()) {
                            auto ret = ikcp_input(m_kcp, (char *) (ptr + 2), sz-2);
                            if (ret != 0) {
                                std::cout << "ikcp_input failed for recovered packet:" << ret << std::endl;
                            } else {
                                std::cout << "ikcp_input succeed for recovered packet:" << sz << ","  << n << std::endl;
                            }
                        }
                    }
                }
            } else {
                ikcp_input(m_kcp, (char *)(m_buf), n);
            }
        } else {
            break;
        }
    }
    ikcp_update(m_kcp, current);
}

void
UDPSession::Destroy(UDPSession *sess) {
    if (nullptr == sess) return;
    if (0 != sess->m_sockfd) { close(sess->m_sockfd); }
    if (nullptr != sess->m_kcp) { ikcp_release(sess->m_kcp); }
    delete sess;
}

ssize_t
UDPSession::Read(char *buf, size_t sz) noexcept {
    if (m_streambufsiz > 0) {
        size_t n = m_streambufsiz;
        if (n > sz) {
            n = sz;
        }
        memcpy(buf, m_streambuf, n);

        m_streambufsiz -= n;
        if (m_streambufsiz != 0) {
            memmove(m_streambuf, m_streambuf + n, m_streambufsiz);
        }
        return n;
    }

    int psz = ikcp_peeksize(m_kcp);
    if (psz <= 0) {
        return 0;
    }

    if (psz <= sz) {
        return (ssize_t) ikcp_recv(m_kcp, buf, int(sz));
    } else {
        ikcp_recv(m_kcp, (char*)m_streambuf, sizeof(m_streambuf));
        memcpy(buf, m_streambuf, sz);
        m_streambufsiz = psz - sz;
        memmove(m_streambuf, m_streambuf + sz, psz - sz);
        return sz;
    }
}

ssize_t
UDPSession::Write(const char *buf, size_t sz) noexcept {
    int n = ikcp_send(m_kcp, const_cast<char *>(buf), int(sz));
    if (n == 0) {
        return sz;
    } else return n;
}

int
UDPSession::SetDSCP(int iptos) noexcept {
    iptos = (iptos << 2) & 0xFF;
    return setsockopt(this->m_sockfd, IPPROTO_IP, IP_TOS,  &iptos, sizeof(iptos));
}

int
UDPSession::out_wrapper(const char *buf, int len, struct IKCPCB *, void *user) {
    assert(user != nullptr);
    UDPSession *sess = static_cast<UDPSession *>(user);

    if (sess->fec.isEnabled()) {    // append FEC header
        // extend to len + fecHeaderSizePlus2
        // i.e. 4B seqid + 2B flag + 2B size
        memcpy(sess->m_buf+fecHeaderSizePlus2, buf, static_cast<size_t>(len));
        sess->fec.MarkData(sess->m_buf, static_cast<size_t>(len));
        sess->output(sess->m_buf, len + fecHeaderSizePlus2);

        // FEC calculation
        // copy "2B size + data" to shards
        auto slen = len + 2;
        sess->shards[sess->pkt_idx] = std::make_shared<std::vector<byte>>();
        sess->shards[sess->pkt_idx]->assign(sess->m_buf + fecHeaderSize, sess->m_buf + fecHeaderSize + slen);

        std::cout << "out_wrapper data packet size:" << len + fecHeaderSizePlus2 << std::endl;

        // count number of data shards
        sess->pkt_idx++;
        if (sess->pkt_idx == sess->dataShards) { // we've collected enough data shards
            auto ret = sess->fec.Encode(sess->shards);
            if (ret == 0 ) {
                // send parity shards
                for (size_t i = sess->dataShards;i<sess->dataShards+sess->parityShards;i++) {
                    // append header to parity shards
                    // i.e. fecHeaderSize + data(2B size included)
                    memcpy(sess->m_buf+fecHeaderSize, sess->shards[i]->data(), sess->shards[i]->size());
                    sess->fec.MarkFEC(sess->m_buf);
                    sess->output(sess->m_buf, sess->shards[i]->size() + fecHeaderSize);
                    std::cout << "out_wrapper parity packet size:" <<  sess->shards[i]->size() + fecHeaderSize << std::endl;
                }
            }

            // reset counting
            sess->pkt_idx = 0;
        }
    } else { // No FEC, just send raw bytes,
        sess->output(buf, static_cast<size_t>(len));
    }
    return 0;
}

ssize_t
UDPSession::output(const void *buffer, size_t length) {
    ssize_t n = send(m_sockfd, buffer, length, 0);
    return n;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2018 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include <type_traits>
#include <seastar/core/future.hh>

namespace sstables {

class random_access_reader;

// Utilities for reading integral values in variable-length format
// See vint-serialization.hh for more details
future<uint64_t> read_unsigned_vint(random_access_reader& in);
future<int64_t> read_signed_vint(random_access_reader& in);

template <typename T>
typename std::enable_if_t<!std::is_integral_v<T>>
read_vint(random_access_reader& in, T& t) = delete;

template <typename T>
inline future<> read_vint(random_access_reader& in, T& value) {
    static_assert(std::is_integral_v<T>, "Non-integral values can't be read using read_vint");
    if constexpr(std::is_unsigned_v<T>) {
        return read_unsigned_vint(in).then([&value] (uint64_t res) {
            value = res;
        });
    } else {
        return read_signed_vint(in).then([&value] (int64_t res) {
            value = res;
        });
    }
}

};   // namespace sstables
<commit_msg>Add helper methods for parsing simple types.<commit_after>/*
 * Copyright (C) 2018 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include <limits>
#include <type_traits>
#include <seastar/core/future.hh>
#include "gc_clock.hh"
#include "timestamp.hh"
#include "sstables/types.hh"
#include "sstables/exceptions.hh"

namespace sstables {

class random_access_reader;

// Utilities for reading integral values in variable-length format
// See vint-serialization.hh for more details
future<uint64_t> read_unsigned_vint(random_access_reader& in);
future<int64_t> read_signed_vint(random_access_reader& in);

template <typename T>
typename std::enable_if_t<!std::is_integral_v<T>>
read_vint(random_access_reader& in, T& t) = delete;

template <typename T>
inline future<> read_vint(random_access_reader& in, T& value) {
    static_assert(std::is_integral_v<T>, "Non-integral values can't be read using read_vint");
    if constexpr(std::is_unsigned_v<T>) {
        return read_unsigned_vint(in).then([&value] (uint64_t res) {
            value = res;
        });
    } else {
        return read_signed_vint(in).then([&value] (int64_t res) {
            value = res;
        });
    }
}

inline api::timestamp_type parse_timestamp(uint64_t value) {
    if (value > api::max_timestamp) {
        throw malformed_sstable_exception("Too big timestamp: " + value);
    }
    return static_cast<api::timestamp_type >(value);
}

inline api::timestamp_type parse_timestamp(const serialization_header& header,
                                           uint64_t delta) {
    return parse_timestamp(header.min_timestamp.value + delta);
}

inline gc_clock::duration parse_ttl(uint32_t value) {
    if (value > std::numeric_limits<gc_clock::duration::rep>::max()) {
        throw malformed_sstable_exception("Too big ttl: " + value);
    }
    return gc_clock::duration(value);
}

inline gc_clock::duration parse_ttl(const serialization_header& header,
                                    uint32_t delta) {
    return parse_ttl(header.min_ttl.value + delta);
}

inline gc_clock::time_point parse_expiry(uint32_t value) {
    if (value > std::numeric_limits<gc_clock::duration::rep>::max()) {
        throw malformed_sstable_exception("Too big expiry: " + value);
    }
    return gc_clock::time_point(gc_clock::duration(value));
}

inline gc_clock::time_point parse_expiry(const serialization_header& header,
                                   uint32_t delta) {
    return parse_expiry(header.min_local_deletion_time.value + delta);
}

};   // namespace sstables
<|endoftext|>


<commit_before>#ifndef STAN_MATH_REV_FUN_LDLT_FACTOR_HPP
#define STAN_MATH_REV_FUN_LDLT_FACTOR_HPP

#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/LDLT_factor.hpp>

namespace stan {
namespace math {

/**
 * An LDLT_factor of an `Eigen::Matrix<var, Eigen::Dynamic, Eigen::Dynamic>`
 * with `alloc_in_arena = True` holds a copy of the input matrix and the LDLT
 * of its values, with all member variable allocations are done in the arena.
 */
template <typename T>
class LDLT_factor<T, require_eigen_matrix_dynamic_vt<is_var, T>> {
 private:
  arena_t<plain_type_t<T>> matrix_;
  Eigen::LDLT<Eigen::MatrixXd> ldlt_;

 public:
  template <typename S,
            require_same_t<plain_type_t<T>, plain_type_t<S>>* = nullptr>
  explicit LDLT_factor(const S& matrix)
      : matrix_(matrix), ldlt_(matrix.val().ldlt()) {}

  /**
   * Return a const reference to the underlying matrix
   */
  const auto& matrix() const noexcept { return matrix_; }

  /**
   * Return a const reference to the LDLT factor of the matrix values
   */
  const auto& ldlt() const noexcept { return ldlt_; }
};

/**
 * An LDLT_factor of a `var_value<Eigen::MatrixXd>`
 * holds a copy of the input `var_value` and the LDLT of its values.
 */
template <typename T>
class LDLT_factor<T, require_var_matrix_t<T>> {
 private:
  std::decay_t<T> matrix_;
  Eigen::LDLT<Eigen::MatrixXd> ldlt_;

 public:
  template <typename S,
            require_same_t<plain_type_t<T>, plain_type_t<S>>* = nullptr>
  explicit LDLT_factor(const S& matrix)
      : matrix_(matrix), ldlt_(matrix.val().ldlt()) {}

  /**
   * Return a const reference the underlying `var_value`
   */
  const auto& matrix() const noexcept { return matrix_; }

  /**
   * Return a const reference to the LDLT factor of the matrix values
   */
  const auto& ldlt() const noexcept { return ldlt_; }
};

}  // namespace math
}  // namespace stan
#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags/RELEASE_600/final)<commit_after>#ifndef STAN_MATH_REV_FUN_LDLT_FACTOR_HPP
#define STAN_MATH_REV_FUN_LDLT_FACTOR_HPP

#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/LDLT_factor.hpp>

namespace stan {
namespace math {

/**
 * An LDLT_factor of an `Eigen::Matrix<var, Eigen::Dynamic, Eigen::Dynamic>`
 * with `alloc_in_arena = True` holds a copy of the input matrix and the LDLT
 * of its values, with all member variable allocations are done in the arena.
 */
template <typename T>
class LDLT_factor<T, require_eigen_matrix_dynamic_vt<is_var, T>> {
 private:
  arena_t<plain_type_t<T>> matrix_;
  Eigen::LDLT<Eigen::MatrixXd> ldlt_;

 public:
  template <typename S,
            require_same_t<plain_type_t<T>, plain_type_t<S>>* = nullptr>
  explicit LDLT_factor(const S& matrix)
      : matrix_(matrix), ldlt_(matrix.val().ldlt()) {}

  /**
   * Return a const reference to the underlying matrix
   */
  const auto& matrix() const noexcept { return matrix_; }

  /**
   * Return a const reference to the LDLT factor of the matrix values
   */
  const auto& ldlt() const noexcept { return ldlt_; }
};

/**
 * An LDLT_factor of a `var_value<Eigen::MatrixXd>`
 * holds a copy of the input `var_value` and the LDLT of its values.
 */
template <typename T>
class LDLT_factor<T, require_var_matrix_t<T>> {
 private:
  std::decay_t<T> matrix_;
  Eigen::LDLT<Eigen::MatrixXd> ldlt_;

 public:
  template <typename S,
            require_same_t<plain_type_t<T>, plain_type_t<S>>* = nullptr>
  explicit LDLT_factor(const S& matrix)
      : matrix_(matrix), ldlt_(matrix.val().ldlt()) {}

  /**
   * Return a const reference the underlying `var_value`
   */
  const auto& matrix() const noexcept { return matrix_; }

  /**
   * Return a const reference to the LDLT factor of the matrix values
   */
  const auto& ldlt() const noexcept { return ldlt_; }
};

}  // namespace math
}  // namespace stan
#endif
<|endoftext|>


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

#include "cyber/io/poller.h"
#include <fcntl.h>
#include <gtest/gtest.h>
#include <unistd.h>
#include <thread>

namespace apollo {
namespace cyber {
namespace io {

TEST(PollerTest, operation) {
  auto poller = Poller::Instance();
  ASSERT_NE(poller, nullptr);

  // invalid input
  PollRequest request;
  EXPECT_FALSE(poller->Register(request));

  int pipe_fd[2] = {-1, -1};
  ASSERT_EQ(pipe(pipe_fd), 0);
  ASSERT_EQ(fcntl(pipe_fd[0], F_SETFL, O_NONBLOCK), 0);
  ASSERT_EQ(fcntl(pipe_fd[1], F_SETFL, O_NONBLOCK), 0);

  // invalid input, callback is nullptr
  request.fd = pipe_fd[0];
  request.events = EPOLLIN | EPOLLET;
  request.timeout_ms = 0;
  EXPECT_FALSE(poller->Register(request));

  // timeout_ms is 0
  PollResponse response(123);
  request.callback = [&response](const PollResponse& rsp) { response = rsp; };
  EXPECT_TRUE(poller->Register(request));
  std::this_thread::sleep_for(std::chrono::milliseconds(5));
  EXPECT_EQ(response.events, 0);

  // timeout_ms is 50
  response.events = 123;
  request.timeout_ms = 50;
  EXPECT_TRUE(poller->Register(request));
  std::this_thread::sleep_for(std::chrono::milliseconds(20));
  EXPECT_EQ(response.events, 123);
  std::this_thread::sleep_for(std::chrono::milliseconds(35));
  EXPECT_EQ(response.events, 0);

  // timeout_ms is 200
  response.events = 123;
  request.timeout_ms = 200;
  EXPECT_TRUE(poller->Register(request));
  std::this_thread::sleep_for(std::chrono::milliseconds(20));
  EXPECT_EQ(response.events, 123);
  char msg = 'C';
  ssize_t res = 0;
  int try_num = 3;
  do {
    --try_num;
    res = write(pipe_fd[1], &msg, 1);
  } while (res <= 0 && try_num >= 0);
  std::this_thread::sleep_for(std::chrono::milliseconds(5));
  EXPECT_NE(response.events & EPOLLIN, 0);

  EXPECT_TRUE(poller->Unregister(request));
  EXPECT_FALSE(poller->Unregister(request));
  request.callback = nullptr;
  EXPECT_FALSE(poller->Unregister(request));
  request.fd = -1;
  EXPECT_FALSE(poller->Unregister(request));

  poller->Shutdown();
  request.fd = pipe_fd[0];
  request.events = EPOLLIN | EPOLLET;
  request.timeout_ms = 0;
  request.callback = [](const PollResponse&) {};
  // poller has been shutdown
  EXPECT_FALSE(poller->Register(request));
  EXPECT_FALSE(poller->Unregister(request));

  close(pipe_fd[0]);
  close(pipe_fd[1]);
}

}  // namespace io
}  // namespace cyber
}  // namespace apollo

int main(int argc, char** argv) {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<commit_msg>framework: sleep for a while to wait start of thread in poller<commit_after>/******************************************************************************
 * Copyright 2018 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "cyber/io/poller.h"
#include <fcntl.h>
#include <gtest/gtest.h>
#include <unistd.h>
#include <thread>

namespace apollo {
namespace cyber {
namespace io {

TEST(PollerTest, operation) {
  auto poller = Poller::Instance();
  ASSERT_NE(poller, nullptr);
  std::this_thread::sleep_for(std::chrono::milliseconds(10));

  // invalid input
  PollRequest request;
  EXPECT_FALSE(poller->Register(request));

  int pipe_fd[2] = {-1, -1};
  ASSERT_EQ(pipe(pipe_fd), 0);
  ASSERT_EQ(fcntl(pipe_fd[0], F_SETFL, O_NONBLOCK), 0);
  ASSERT_EQ(fcntl(pipe_fd[1], F_SETFL, O_NONBLOCK), 0);

  // invalid input, callback is nullptr
  request.fd = pipe_fd[0];
  request.events = EPOLLIN | EPOLLET;
  request.timeout_ms = 0;
  EXPECT_FALSE(poller->Register(request));

  // timeout_ms is 0
  PollResponse response(123);
  request.callback = [&response](const PollResponse& rsp) { response = rsp; };
  EXPECT_TRUE(poller->Register(request));
  std::this_thread::sleep_for(std::chrono::milliseconds(5));
  EXPECT_EQ(response.events, 0);

  // timeout_ms is 50
  response.events = 123;
  request.timeout_ms = 50;
  EXPECT_TRUE(poller->Register(request));
  std::this_thread::sleep_for(std::chrono::milliseconds(20));
  EXPECT_EQ(response.events, 123);
  std::this_thread::sleep_for(std::chrono::milliseconds(35));
  EXPECT_EQ(response.events, 0);

  // timeout_ms is 200
  response.events = 123;
  request.timeout_ms = 200;
  EXPECT_TRUE(poller->Register(request));
  std::this_thread::sleep_for(std::chrono::milliseconds(20));
  EXPECT_EQ(response.events, 123);
  char msg = 'C';
  ssize_t res = 0;
  int try_num = 3;
  do {
    --try_num;
    res = write(pipe_fd[1], &msg, 1);
  } while (res <= 0 && try_num >= 0);
  std::this_thread::sleep_for(std::chrono::milliseconds(5));
  EXPECT_NE(response.events & EPOLLIN, 0);

  EXPECT_TRUE(poller->Unregister(request));
  EXPECT_FALSE(poller->Unregister(request));
  request.callback = nullptr;
  EXPECT_FALSE(poller->Unregister(request));
  request.fd = -1;
  EXPECT_FALSE(poller->Unregister(request));

  poller->Shutdown();
  request.fd = pipe_fd[0];
  request.events = EPOLLIN | EPOLLET;
  request.timeout_ms = 0;
  request.callback = [](const PollResponse&) {};
  // poller has been shutdown
  EXPECT_FALSE(poller->Register(request));
  EXPECT_FALSE(poller->Unregister(request));

  close(pipe_fd[0]);
  close(pipe_fd[1]);
}

}  // namespace io
}  // namespace cyber
}  // namespace apollo

int main(int argc, char** argv) {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>/// YANG Development Kit
// Copyright 2016 Cisco Systems. All rights reserved
//
////////////////////////////////////////////////////////////////
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
//
//////////////////////////////////////////////////////////////////

#include <iostream>
#include <sstream>
#include <memory>
#include <libyang/libyang.h>

#include "entity_data_node_walker.hpp"
#include "errors.hpp"
#include "ietf_parser.hpp"
#include "netconf_ssh_client.hpp"
#include "netconf_tcp_client.hpp"
#include "netconf_provider.hpp"
#include "netconf_service.hpp"
#include "types.hpp"
#include "ydk_yang.hpp"
#include "logger.hpp"
#include "common_utilities.hpp"

using namespace std;
using namespace ydk;

namespace ydk
{

NetconfServiceProvider::NetconfServiceProvider(const string& address,
                                               const string& username,
                                               const string& password,
                                               int port,
                                               const string& protocol,
                                               bool on_demand,
                                               bool common_cache,
                                               int timeout)
    : session{address, username, password, port, protocol, on_demand, common_cache, timeout}
{
}

NetconfServiceProvider::NetconfServiceProvider(path::Repository & repo,
                                               const string& address,
                                               const string& username,
                                               const string& password,
                                               int port,
                                               const string& protocol,
                                               bool on_demand,
                                               int timeout)
    : session{repo, address, username, password, port, protocol, on_demand, timeout}
{
}

NetconfServiceProvider::NetconfServiceProvider(path::Repository & repo,
                                               const string& address,
                                               const string& username,
                                               const string& private_key_path,
                                               const string& public_key_path,
                                               int port,
                                               bool on_demand,
                                               int timeout)
    : session{
        repo, address, username, private_key_path, public_key_path,
        port, on_demand, timeout }
{
}

NetconfServiceProvider::NetconfServiceProvider(const string& address,
                                               const string& username,
                                               const string& private_key_path,
                                               const string& public_key_path,
                                               int port,
                                               bool on_demand,
                                               bool common_cache,
                                               int timeout)
    : session{
        address, username, private_key_path, public_key_path,
        port, on_demand, common_cache, timeout }
{
}

NetconfServiceProvider::~NetconfServiceProvider()
{
}

EncodingFormat NetconfServiceProvider::get_encoding() const
{
    return EncodingFormat::XML;
}

const path::Session& NetconfServiceProvider::get_session() const
{
    return session;
}

std::vector<std::string> NetconfServiceProvider::get_capabilities() const
{
    return session.get_capabilities();
}

static bool is_candidate_supported(vector<string> capabilities)
{
	const char* CANDIDATE = "urn:ietf:params:netconf:capability:candidate:1.0";
	if(find(capabilities.begin(), capabilities.end(), CANDIDATE) != capabilities.end())
    {
        //candidate is supported
        return true;
    }
    return false;
}

shared_ptr<Entity>
NetconfServiceProvider::execute_operation(const string & operation, Entity & entity, map<string,string> params)
{
    NetconfService ns;
    if (operation == "create" || operation == "update" || operation == "delete") {
        YFilter original_yfilter = entity.yfilter;
        if (original_yfilter == YFilter::not_set) {
            entity.yfilter = (operation == "delete") ? YFilter::delete_ : YFilter::merge;
        }
        DataStore target = (is_candidate_supported(session.get_capabilities())) ?
                           DataStore::candidate : DataStore::running;
        if (ns.edit_config(*this, target, entity)) {
            ns.commit(*this);
        }
        else {
            ns.discard_changes(*this);
            YLOG_ERROR("NetconfServiceProvider::execute_operation: Operation '{}' failed; discarding changes.", operation);
            throw(YServiceProviderError("NetconfServiceProvider: Operation failed"));
        }
        entity.yfilter = original_yfilter;
    }
    else if (operation == "read") {
        if (params["mode"] == "config")
            return ns.get_config(*this, DataStore::running, entity);
        else
            return ns.get(*this, entity);
    }
    else {
        YLOG_ERROR("NetconfServiceProvider::execute_operation: Operation '{}' is not supported", operation);
        throw(YServiceProviderError("NetconfServiceProvider: Requested operation is not supported"));
    }
    return nullptr;
}

vector<shared_ptr<Entity>>
NetconfServiceProvider::execute_operation(const string & operation, vector<Entity*> entity_list, map<string,string> params)
{
    vector<shared_ptr<Entity>> result;
    NetconfService ns;
    if (operation == "create" || operation == "update" || operation == "delete") {
        YFilter original_yfilters[entity_list.size()];
        size_t item = 0;
        for (auto entity : entity_list) {
            original_yfilters[item++] = entity->yfilter;
            if (entity->yfilter == YFilter::not_set) {
                entity->yfilter = (operation == "delete") ? YFilter::delete_ : YFilter::merge;
            }
        }
        DataStore target = (is_candidate_supported(session.get_capabilities())) ?
                           DataStore::candidate : DataStore::running;
        if (ns.edit_config(*this, target, entity_list)) {
            ns.commit(*this);
        }
        else {
            ns.discard_changes(*this);
        }
        // Restore original yfilter setting
        item = 0;
        for (auto entity : entity_list) {
            entity->yfilter = original_yfilters[item++];
        }
    }
    else if (operation == "read") {
        if (params["mode"] == "config")
            return ns.get_config(*this, DataStore::running, entity_list);
        else
            return ns.get(*this, entity_list);
    }
    else {
        YLOG_ERROR("NetconfServiceProvider::execute_operation: Operation '{}' is not supported", operation);
        throw(YServiceProviderError("NetconfServiceProvider: Requested operation is not supported"));
    }
    return result;
}

}
<commit_msg>Fixed issue #915<commit_after>/// YANG Development Kit
// Copyright 2016 Cisco Systems. All rights reserved
//
////////////////////////////////////////////////////////////////
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
//
//////////////////////////////////////////////////////////////////

#include <iostream>
#include <sstream>
#include <memory>
#include <libyang/libyang.h>

#include "entity_data_node_walker.hpp"
#include "errors.hpp"
#include "ietf_parser.hpp"
#include "netconf_ssh_client.hpp"
#include "netconf_tcp_client.hpp"
#include "netconf_provider.hpp"
#include "netconf_service.hpp"
#include "types.hpp"
#include "ydk_yang.hpp"
#include "logger.hpp"
#include "common_utilities.hpp"

using namespace std;
using namespace ydk;

namespace ydk
{

NetconfServiceProvider::NetconfServiceProvider(const string& address,
                                               const string& username,
                                               const string& password,
                                               int port,
                                               const string& protocol,
                                               bool on_demand,
                                               bool common_cache,
                                               int timeout)
    : session{address, username, password, port, protocol, on_demand, common_cache, timeout}
{
}

NetconfServiceProvider::NetconfServiceProvider(path::Repository & repo,
                                               const string& address,
                                               const string& username,
                                               const string& password,
                                               int port,
                                               const string& protocol,
                                               bool on_demand,
                                               int timeout)
    : session{repo, address, username, password, port, protocol, on_demand, timeout}
{
}

NetconfServiceProvider::NetconfServiceProvider(path::Repository & repo,
                                               const string& address,
                                               const string& username,
                                               const string& private_key_path,
                                               const string& public_key_path,
                                               int port,
                                               bool on_demand,
                                               int timeout)
    : session{
        repo, address, username, private_key_path, public_key_path,
        port, on_demand, timeout }
{
}

NetconfServiceProvider::NetconfServiceProvider(const string& address,
                                               const string& username,
                                               const string& private_key_path,
                                               const string& public_key_path,
                                               int port,
                                               bool on_demand,
                                               bool common_cache,
                                               int timeout)
    : session{
        address, username, private_key_path, public_key_path,
        port, on_demand, common_cache, timeout }
{
}

NetconfServiceProvider::~NetconfServiceProvider()
{
}

EncodingFormat NetconfServiceProvider::get_encoding() const
{
    return EncodingFormat::XML;
}

const path::Session& NetconfServiceProvider::get_session() const
{
    return session;
}

std::vector<std::string> NetconfServiceProvider::get_capabilities() const
{
    return session.get_capabilities();
}

static bool is_candidate_supported(vector<string> capabilities)
{
	const char* CANDIDATE = "urn:ietf:params:netconf:capability:candidate:1.0";
	if(find(capabilities.begin(), capabilities.end(), CANDIDATE) != capabilities.end())
    {
        //candidate is supported
        return true;
    }
    return false;
}

shared_ptr<Entity>
NetconfServiceProvider::execute_operation(const string & operation, Entity & entity, map<string,string> params)
{
    NetconfService ns;
    if (operation == "create" || operation == "update" || operation == "delete") {
        YFilter original_yfilter = entity.yfilter;
        if (original_yfilter == YFilter::not_set) {
            entity.yfilter = (operation == "delete") ? YFilter::delete_ : YFilter::merge;
        }
        DataStore target = (is_candidate_supported(session.get_capabilities())) ?
                           DataStore::candidate : DataStore::running;
        if (ns.edit_config(*this, target, entity)) {
            if (target == DataStore::candidate)
                ns.commit(*this);
        }
        else {
            ns.discard_changes(*this);
            YLOG_ERROR("NetconfServiceProvider::execute_operation: Operation '{}' failed; discarding changes.", operation);
            throw(YServiceProviderError("NetconfServiceProvider: Operation failed"));
        }
        entity.yfilter = original_yfilter;
    }
    else if (operation == "read") {
        if (params["mode"] == "config")
            return ns.get_config(*this, DataStore::running, entity);
        else
            return ns.get(*this, entity);
    }
    else {
        YLOG_ERROR("NetconfServiceProvider::execute_operation: Operation '{}' is not supported", operation);
        throw(YServiceProviderError("NetconfServiceProvider: Requested operation is not supported"));
    }
    return nullptr;
}

vector<shared_ptr<Entity>>
NetconfServiceProvider::execute_operation(const string & operation, vector<Entity*> entity_list, map<string,string> params)
{
    vector<shared_ptr<Entity>> result;
    NetconfService ns;
    if (operation == "create" || operation == "update" || operation == "delete") {
        YFilter original_yfilters[entity_list.size()];
        size_t item = 0;
        for (auto entity : entity_list) {
            original_yfilters[item++] = entity->yfilter;
            if (entity->yfilter == YFilter::not_set) {
                entity->yfilter = (operation == "delete") ? YFilter::delete_ : YFilter::merge;
            }
        }
        DataStore target = (is_candidate_supported(session.get_capabilities())) ?
                           DataStore::candidate : DataStore::running;
        if (ns.edit_config(*this, target, entity_list)) {
            if (target == DataStore::candidate)
                ns.commit(*this);
        }
        else {
            ns.discard_changes(*this);
        }
        // Restore original yfilter setting
        item = 0;
        for (auto entity : entity_list) {
            entity->yfilter = original_yfilters[item++];
        }
    }
    else if (operation == "read") {
        if (params["mode"] == "config")
            return ns.get_config(*this, DataStore::running, entity_list);
        else
            return ns.get(*this, entity_list);
    }
    else {
        YLOG_ERROR("NetconfServiceProvider::execute_operation: Operation '{}' is not supported", operation);
        throw(YServiceProviderError("NetconfServiceProvider: Requested operation is not supported"));
    }
    return result;
}

}
<|endoftext|>


<commit_before>#include "filterablelistwidget.h"
#include "ui_filterablelistwidget.h"
#include "PlotJuggler/alphanum.hpp"
#include <QDebug>
#include <QLayoutItem>
#include <QMenu>
#include <QSettings>
#include <QDrag>
#include <QMimeData>
#include <QHeaderView>
#include <QFontDatabase>
#include <QMessageBox>
#include <QApplication>
#include <QPainter>
#include <QCompleter>

class TreeModelCompleter : public QCompleter
{

public:
    TreeModelCompleter(QAbstractItemModel *model, QObject *parent = 0): QCompleter(model, parent)
    {  }

    QStringList splitPath(const QString &path) const override {
        return path.split('/');
    }

    QString pathFromIndex(const QModelIndex &index) const override
    {
        QStringList dataList;
        for (QModelIndex i = index; i.isValid(); i = i.parent())
        {
            QString name = model()->data(i, completionRole()).toString();
            dataList.prepend(name);
        }
        return dataList.join('/');
    }
};

FilterableListWidget::FilterableListWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FilterableListWidget),
    _tree_model( new QStandardItemModel(this)),
    _completer( new TreeModelCompleter(_tree_model, this) )
{
    ui->setupUi(this);
    ui->tableWidget->viewport()->installEventFilter( this );

    ui->tableWidget->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
    ui->tableWidget->horizontalHeader()->resizeSection(1, 120);

    ui->widgetOptions->setVisible(false);

    ui->radioRegExp->setAutoExclusive(true);
    ui->radioContains->setAutoExclusive(true);
    ui->radioPrefix->setAutoExclusive(true);

    _completer->setCompletionMode( QCompleter::PopupCompletion );

    QSettings settings( "IcarusTechnology", "PlotJuggler");

    QString active_filter = settings.value("FilterableListWidget.searchFilter", "radioContains").toString();
    if( active_filter == "radioRegExp")        ui->radioRegExp->setChecked(true);
    else if( active_filter == "radioPrefix")   ui->radioPrefix->setChecked(true);
    else if( active_filter == "radioContains") ui->radioContains->setChecked(true);

}

FilterableListWidget::~FilterableListWidget()
{
    QSettings settings( "IcarusTechnology", "PlotJuggler");

    if(ui->radioRegExp->isChecked())
        settings.setValue("FilterableListWidget.searchFilter", "radioRegExp");
    else if(ui->radioPrefix->isChecked())
        settings.setValue("FilterableListWidget.searchFilter", "radioPrefix");
    else if(ui->radioContains->isChecked())
        settings.setValue("FilterableListWidget.searchFilter", "radioContains");

    delete ui;
}

int FilterableListWidget::rowCount() const
{
    return ui->tableWidget->rowCount();
}

void FilterableListWidget::clear()
{
    ui->tableWidget->setRowCount(0);
    _tree_model->clear();
    ui->labelNumberDisplayed->setText( "0 of 0");
}

class CustomSortedTableItem: public QTableWidgetItem
{

 public:
     CustomSortedTableItem(const QString& name): QTableWidgetItem(name) {}

     bool operator< (const QTableWidgetItem &other) const
     {
         return doj::alphanum_impl(this->text().toLocal8Bit().constData(),
                                   other.text().toLocal8Bit().constData()) < 0;
     }
 };

void FilterableListWidget::addItem(const QString &item_name, bool sort_columns)
{
    auto item = new CustomSortedTableItem(item_name);
    const int row = rowCount();
    ui->tableWidget->setRowCount(row+1);
    ui->tableWidget->setItem(row, 0, item);

    auto val_cell = new QTableWidgetItem("-");
    val_cell->setTextAlignment(Qt::AlignRight);
    val_cell->setFlags( Qt::NoItemFlags | Qt::ItemIsEnabled );
    val_cell->setFont(  QFontDatabase::systemFont(QFontDatabase::FixedFont) );

    ui->tableWidget->setItem(row, 1, val_cell );
    if( sort_columns )
    {
      ui->tableWidget->sortByColumn(0,Qt::AscendingOrder);
    }

    addToCompletionTree(item);
}

void FilterableListWidget::sortColumns()
{
  ui->tableWidget->sortByColumn(0,Qt::AscendingOrder);
}

QList<int>
FilterableListWidget::findRowsByName(const QString &text) const
{
    QList<int> output;
    QList<QTableWidgetItem*> item_list = ui->tableWidget->findItems( text, Qt::MatchExactly);
    for(QTableWidgetItem* item : item_list)
    {
        if(item->column() == 0) {
            output.push_back( item->row() );
        }
    }
    return output;
}

const QTableWidget *FilterableListWidget::getTable() const
{
    return ui->tableWidget;
}

void FilterableListWidget::updateFilter()
{
    on_lineEdit_textChanged( ui->lineEdit->text() );
}

void FilterableListWidget::keyPressEvent(QKeyEvent *event)
{
    if( event->key() == Qt::Key_Delete){
        removeSelectedCurves();
    }
}

bool FilterableListWidget::eventFilter(QObject *object, QEvent *event)
{
    QObject *obj = object;
    while ( obj != NULL )
    {
        if( obj == ui->tableWidget || obj == ui->lineEdit ) break;
        obj = obj->parent();
    }

    //Ignore obj different than tableWidget
    if(obj != ui->tableWidget)
    {
      return QWidget::eventFilter(object,event);
    }

    if(event->type() == QEvent::MouseButtonPress)
    {
      QMouseEvent *mouse_event = static_cast<QMouseEvent*>(event);

      _dragging = false;
      _drag_start_pos = mouse_event->pos();

      if(mouse_event->button() == Qt::LeftButton )
      {
        _newX_modifier = false;
      }
      else if(mouse_event->button() == Qt::RightButton )
      {
        _newX_modifier = true;
      }
      else {
        return false;
      }
      return QWidget::eventFilter(object,event);
    }
    else if(event->type() == QEvent::MouseMove)
    {
      QMouseEvent *mouse_event = static_cast<QMouseEvent*>(event);
      double distance_from_click = (mouse_event->pos() - _drag_start_pos).manhattanLength();

      if ((mouse_event->buttons() == Qt::LeftButton ||
           mouse_event->buttons() == Qt::RightButton) &&
          distance_from_click >= QApplication::startDragDistance() &&
          _dragging == false)
      {
        _dragging = true;
        QDrag *drag = new QDrag(this);
        QMimeData *mimeData = new QMimeData;

        QByteArray mdata;
        QDataStream stream(&mdata, QIODevice::WriteOnly);

        for(QTableWidgetItem* item: ui->tableWidget->selectedItems()) {
          stream << item->text();
        }

        if( !_newX_modifier )
        {
          mimeData->setData("curveslist/add_curve", mdata);
        }
        else
        {
          if( ui->tableWidget->selectedItems().size() != 1)
          {
            return false;
          }
          mimeData->setData("curveslist/new_X_axis", mdata);

          QPixmap cursor( QSize(160,30) );
          cursor.fill();

          QPainter painter;
          painter.begin( &cursor);
          painter.setPen(QColor(22, 22, 22));

          QString text("set as new X axis");
          painter.setFont( QFont("Arial", 14 ) );

          painter.drawText( QRect(0, 0, 160, 30), Qt::AlignHCenter | Qt::AlignVCenter, text );
          painter.end();

          drag->setDragCursor(cursor, Qt::MoveAction);
        }

        drag->setMimeData(mimeData);
        drag->start(Qt::CopyAction | Qt::MoveAction);
      }
      return true;
    }

    return QWidget::eventFilter(object,event);
}

void FilterableListWidget::on_radioContains_toggled(bool checked)
{
    if(checked) {
        updateFilter();
        ui->lineEdit->setCompleter( nullptr );
    }
}

void FilterableListWidget::on_radioRegExp_toggled(bool checked)
{
    if(checked) {
        updateFilter();
        ui->lineEdit->setCompleter( nullptr );
    }
}

void FilterableListWidget::addToCompletionTree(QTableWidgetItem* item)
{
    QString name = item->data(Qt::DisplayRole).toString();
    QStringList parts = name.split('/');

    QStandardItem *parent_item = _tree_model->invisibleRootItem();

    for (int col=0; col < parts.count(); col++)
    {
        bool already_stored = false;
        for (int row = 0; row < parent_item->rowCount() && !already_stored; row++)
        {
            if( parent_item->child(row)->text() == parts[col])
            {
                already_stored = true;
                parent_item = parent_item->child(row);
            }
        }
        if( !already_stored )
        {
            QStandardItem *item = new QStandardItem(parts[col]);
            parent_item->appendRow(item);
            parent_item = item;
        }
    }
}

void FilterableListWidget::on_radioPrefix_toggled(bool checked)
{
    if(checked) {
        updateFilter();
        ui->lineEdit->setCompleter( _completer );
    }
}

void FilterableListWidget::on_checkBoxCaseSensitive_toggled(bool checked)
{
    updateFilter();
}

void FilterableListWidget::on_lineEdit_textChanged(const QString &search_string)
{
    int item_count = rowCount();
    int visible_count = 0;
    bool updated = false;

    Qt::CaseSensitivity cs = Qt::CaseInsensitive;
    if( ui->checkBoxCaseSensitive->isChecked())
    {
        cs = Qt::CaseSensitive;
    }
    QRegExp regexp( search_string,  cs, QRegExp::Wildcard );
    QRegExpValidator v(regexp, 0);

    for (int row=0; row< rowCount(); row++)
    {
        QTableWidgetItem* item = ui->tableWidget->item(row,0);
        QString name = item->text();
        int pos = 0;
        bool toHide = false;

        if( ui->radioRegExp->isChecked())
        {
            toHide = v.validate( name, pos ) != QValidator::Acceptable;
        }
        else if( ui->radioPrefix->isChecked())
        {
            toHide = !name.startsWith( search_string, cs ) ;
        }
        else if( ui->radioContains->isChecked())
        {
            QStringList items = search_string.split(' ');
            for (int i=0; i< items.size(); i++)
            {
                if( name.contains(items[i], cs) == false )
                {
                    toHide = true;
                }
            }
        }
        if( !toHide ) visible_count++;

        if( toHide != ui->tableWidget->isRowHidden(row) ) updated = true;

        ui->tableWidget->setRowHidden(row, toHide );
    }
    ui->labelNumberDisplayed->setText( QString::number( visible_count ) + QString(" of ") + QString::number( item_count ) );

    if(updated){
        emit hiddenItemsChanged();
    }
}

void FilterableListWidget::on_pushButtonSettings_toggled(bool checked)
{
    ui->widgetOptions->setVisible(checked);
}

void FilterableListWidget::on_checkBoxHideSecondColumn_toggled(bool checked)
{
    if(checked){
        ui->tableWidget->hideColumn(1);
        emit hiddenItemsChanged();
    }
    else{
        ui->tableWidget->showColumn(1);
        emit hiddenItemsChanged();
    }
}

void FilterableListWidget::removeSelectedCurves()
{
    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(0, tr("Warning"),
                                  tr("Do you really want to remove these data?\n"),
                                  QMessageBox::Yes | QMessageBox::No,
                                  QMessageBox::No );

    if( reply == QMessageBox::Yes ) {

        while( ui->tableWidget->selectedItems().size() > 0 )
        {
            QTableWidgetItem* item = ui->tableWidget->selectedItems().first();
            emit deleteCurve( item->text() );
        }
    }

    // rebuild the tree model
    _tree_model->clear();
    for (int row=0; row< rowCount(); row++)
    {
        QTableWidgetItem* item = ui->tableWidget->item(row,0);
        addToCompletionTree(item);
    }

    updateFilter();
}

void FilterableListWidget::removeRow(int row)
{
    ui->tableWidget->removeRow(row);
}

<commit_msg>fixing right mouse drag&drop<commit_after>#include "filterablelistwidget.h"
#include "ui_filterablelistwidget.h"
#include "PlotJuggler/alphanum.hpp"
#include <QDebug>
#include <QLayoutItem>
#include <QMenu>
#include <QSettings>
#include <QDrag>
#include <QMimeData>
#include <QHeaderView>
#include <QFontDatabase>
#include <QMessageBox>
#include <QApplication>
#include <QPainter>
#include <QCompleter>

class TreeModelCompleter : public QCompleter
{

public:
    TreeModelCompleter(QAbstractItemModel *model, QObject *parent = 0): QCompleter(model, parent)
    {  }

    QStringList splitPath(const QString &path) const override {
        return path.split('/');
    }

    QString pathFromIndex(const QModelIndex &index) const override
    {
        QStringList dataList;
        for (QModelIndex i = index; i.isValid(); i = i.parent())
        {
            QString name = model()->data(i, completionRole()).toString();
            dataList.prepend(name);
        }
        return dataList.join('/');
    }
};

FilterableListWidget::FilterableListWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FilterableListWidget),
    _tree_model( new QStandardItemModel(this)),
    _completer( new TreeModelCompleter(_tree_model, this) )
{
    ui->setupUi(this);
    ui->tableWidget->viewport()->installEventFilter( this );

    ui->tableWidget->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
    ui->tableWidget->horizontalHeader()->resizeSection(1, 120);

    ui->widgetOptions->setVisible(false);

    ui->radioRegExp->setAutoExclusive(true);
    ui->radioContains->setAutoExclusive(true);
    ui->radioPrefix->setAutoExclusive(true);

    _completer->setCompletionMode( QCompleter::PopupCompletion );

    QSettings settings( "IcarusTechnology", "PlotJuggler");

    QString active_filter = settings.value("FilterableListWidget.searchFilter", "radioContains").toString();
    if( active_filter == "radioRegExp")        ui->radioRegExp->setChecked(true);
    else if( active_filter == "radioPrefix")   ui->radioPrefix->setChecked(true);
    else if( active_filter == "radioContains") ui->radioContains->setChecked(true);

}

FilterableListWidget::~FilterableListWidget()
{
    QSettings settings( "IcarusTechnology", "PlotJuggler");

    if(ui->radioRegExp->isChecked())
        settings.setValue("FilterableListWidget.searchFilter", "radioRegExp");
    else if(ui->radioPrefix->isChecked())
        settings.setValue("FilterableListWidget.searchFilter", "radioPrefix");
    else if(ui->radioContains->isChecked())
        settings.setValue("FilterableListWidget.searchFilter", "radioContains");

    delete ui;
}

int FilterableListWidget::rowCount() const
{
    return ui->tableWidget->rowCount();
}

void FilterableListWidget::clear()
{
    ui->tableWidget->setRowCount(0);
    _tree_model->clear();
    ui->labelNumberDisplayed->setText( "0 of 0");
}

class CustomSortedTableItem: public QTableWidgetItem
{

 public:
     CustomSortedTableItem(const QString& name): QTableWidgetItem(name) {}

     bool operator< (const QTableWidgetItem &other) const
     {
         return doj::alphanum_impl(this->text().toLocal8Bit().constData(),
                                   other.text().toLocal8Bit().constData()) < 0;
     }
 };

void FilterableListWidget::addItem(const QString &item_name, bool sort_columns)
{
    auto item = new CustomSortedTableItem(item_name);
    const int row = rowCount();
    ui->tableWidget->setRowCount(row+1);
    ui->tableWidget->setItem(row, 0, item);

    auto val_cell = new QTableWidgetItem("-");
    val_cell->setTextAlignment(Qt::AlignRight);
    val_cell->setFlags( Qt::NoItemFlags | Qt::ItemIsEnabled );
    val_cell->setFont(  QFontDatabase::systemFont(QFontDatabase::FixedFont) );

    ui->tableWidget->setItem(row, 1, val_cell );
    if( sort_columns )
    {
      ui->tableWidget->sortByColumn(0,Qt::AscendingOrder);
    }

    addToCompletionTree(item);
}

void FilterableListWidget::sortColumns()
{
  ui->tableWidget->sortByColumn(0,Qt::AscendingOrder);
}

QList<int>
FilterableListWidget::findRowsByName(const QString &text) const
{
    QList<int> output;
    QList<QTableWidgetItem*> item_list = ui->tableWidget->findItems( text, Qt::MatchExactly);
    for(QTableWidgetItem* item : item_list)
    {
        if(item->column() == 0) {
            output.push_back( item->row() );
        }
    }
    return output;
}

const QTableWidget *FilterableListWidget::getTable() const
{
    return ui->tableWidget;
}

void FilterableListWidget::updateFilter()
{
    on_lineEdit_textChanged( ui->lineEdit->text() );
}

void FilterableListWidget::keyPressEvent(QKeyEvent *event)
{
    if( event->key() == Qt::Key_Delete){
        removeSelectedCurves();
    }
}

bool FilterableListWidget::eventFilter(QObject *object, QEvent *event)
{
    QObject *obj = object;
    while ( obj != NULL )
    {
        if( obj == ui->tableWidget || obj == ui->lineEdit ) break;
        obj = obj->parent();
    }

    //Ignore obj different than tableWidget
    if(obj != ui->tableWidget)
    {
      return QWidget::eventFilter(object,event);
    }

    if(event->type() == QEvent::MouseButtonPress)
    {
      QMouseEvent *mouse_event = static_cast<QMouseEvent*>(event);

      _dragging = false;
      _drag_start_pos = mouse_event->pos();

      if(mouse_event->button() == Qt::LeftButton )
      {
        _newX_modifier = false;
      }
      else if(mouse_event->button() == Qt::RightButton )
      {
        _newX_modifier = true;
      }
      else {
        return false;
      }
      return QWidget::eventFilter(object,event);
    }
    else if(event->type() == QEvent::MouseMove)
    {
      QMouseEvent *mouse_event = static_cast<QMouseEvent*>(event);
      double distance_from_click = (mouse_event->pos() - _drag_start_pos).manhattanLength();

      if ((mouse_event->buttons() == Qt::LeftButton ||
           mouse_event->buttons() == Qt::RightButton) &&
          distance_from_click >= QApplication::startDragDistance() &&
          _dragging == false)
      {
        _dragging = true;
        QDrag *drag = new QDrag(this);
        QMimeData *mimeData = new QMimeData;

        QByteArray mdata;
        QDataStream stream(&mdata, QIODevice::WriteOnly);

        for(QTableWidgetItem* item: ui->tableWidget->selectedItems()) {
          stream << item->text();
        }

        if( !_newX_modifier )
        {
          mimeData->setData("curveslist/add_curve", mdata);
        }
        else
        {
          if( ui->tableWidget->selectedItems().size() != 1)
          {
            return false;
          }
          mimeData->setData("curveslist/new_X_axis", mdata);

          QPixmap cursor( QSize(160,30) );
          cursor.fill(Qt::transparent);

          QPainter painter;
          painter.begin( &cursor);
          painter.setPen(QColor(22, 22, 22));

          QString text("set as new X axis");
          painter.setFont( QFont("Arial", 14 ) );

          painter.setBackground(Qt::transparent);
          painter.drawText( QRect(0, 0, 160, 30), Qt::AlignHCenter | Qt::AlignVCenter, text );
          painter.end();

          drag->setDragCursor(cursor, Qt::MoveAction);
        }

        drag->setMimeData(mimeData);
        drag->exec(Qt::CopyAction | Qt::MoveAction);
      }
      return true;
    }

    return QWidget::eventFilter(object,event);
}

void FilterableListWidget::on_radioContains_toggled(bool checked)
{
    if(checked) {
        updateFilter();
        ui->lineEdit->setCompleter( nullptr );
    }
}

void FilterableListWidget::on_radioRegExp_toggled(bool checked)
{
    if(checked) {
        updateFilter();
        ui->lineEdit->setCompleter( nullptr );
    }
}

void FilterableListWidget::addToCompletionTree(QTableWidgetItem* item)
{
    QString name = item->data(Qt::DisplayRole).toString();
    QStringList parts = name.split('/');

    QStandardItem *parent_item = _tree_model->invisibleRootItem();

    for (int col=0; col < parts.count(); col++)
    {
        bool already_stored = false;
        for (int row = 0; row < parent_item->rowCount() && !already_stored; row++)
        {
            if( parent_item->child(row)->text() == parts[col])
            {
                already_stored = true;
                parent_item = parent_item->child(row);
            }
        }
        if( !already_stored )
        {
            QStandardItem *item = new QStandardItem(parts[col]);
            parent_item->appendRow(item);
            parent_item = item;
        }
    }
}

void FilterableListWidget::on_radioPrefix_toggled(bool checked)
{
    if(checked) {
        updateFilter();
        ui->lineEdit->setCompleter( _completer );
    }
}

void FilterableListWidget::on_checkBoxCaseSensitive_toggled(bool checked)
{
    updateFilter();
}

void FilterableListWidget::on_lineEdit_textChanged(const QString &search_string)
{
    int item_count = rowCount();
    int visible_count = 0;
    bool updated = false;

    Qt::CaseSensitivity cs = Qt::CaseInsensitive;
    if( ui->checkBoxCaseSensitive->isChecked())
    {
        cs = Qt::CaseSensitive;
    }
    QRegExp regexp( search_string,  cs, QRegExp::Wildcard );
    QRegExpValidator v(regexp, 0);

    for (int row=0; row< rowCount(); row++)
    {
        QTableWidgetItem* item = ui->tableWidget->item(row,0);
        QString name = item->text();
        int pos = 0;
        bool toHide = false;

        if( ui->radioRegExp->isChecked())
        {
            toHide = v.validate( name, pos ) != QValidator::Acceptable;
        }
        else if( ui->radioPrefix->isChecked())
        {
            toHide = !name.startsWith( search_string, cs ) ;
        }
        else if( ui->radioContains->isChecked())
        {
            QStringList items = search_string.split(' ');
            for (int i=0; i< items.size(); i++)
            {
                if( name.contains(items[i], cs) == false )
                {
                    toHide = true;
                }
            }
        }
        if( !toHide ) visible_count++;

        if( toHide != ui->tableWidget->isRowHidden(row) ) updated = true;

        ui->tableWidget->setRowHidden(row, toHide );
    }
    ui->labelNumberDisplayed->setText( QString::number( visible_count ) + QString(" of ") + QString::number( item_count ) );

    if(updated){
        emit hiddenItemsChanged();
    }
}

void FilterableListWidget::on_pushButtonSettings_toggled(bool checked)
{
    ui->widgetOptions->setVisible(checked);
}

void FilterableListWidget::on_checkBoxHideSecondColumn_toggled(bool checked)
{
    if(checked){
        ui->tableWidget->hideColumn(1);
        emit hiddenItemsChanged();
    }
    else{
        ui->tableWidget->showColumn(1);
        emit hiddenItemsChanged();
    }
}

void FilterableListWidget::removeSelectedCurves()
{
    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(0, tr("Warning"),
                                  tr("Do you really want to remove these data?\n"),
                                  QMessageBox::Yes | QMessageBox::No,
                                  QMessageBox::No );

    if( reply == QMessageBox::Yes ) {

        while( ui->tableWidget->selectedItems().size() > 0 )
        {
            QTableWidgetItem* item = ui->tableWidget->selectedItems().first();
            emit deleteCurve( item->text() );
        }
    }

    // rebuild the tree model
    _tree_model->clear();
    for (int row=0; row< rowCount(); row++)
    {
        QTableWidgetItem* item = ui->tableWidget->item(row,0);
        addToCompletionTree(item);
    }

    updateFilter();
}

void FilterableListWidget::removeRow(int row)
{
    ui->tableWidget->removeRow(row);
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: misccfg.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-11-11 08:51:58 $
 *
 *  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
 *
 ************************************************************************/

#ifdef  SVL_DLLIMPLEMENTATION
#undef  SVL_DLLIMPLEMENTATION
#endif
#define SVT_DLLIMPLEMENTATION

#include "misccfg.hxx"

#ifndef _ZFORLIST_HXX //autogen
#include "zforlist.hxx"
#endif

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

#include <rtl/logfile.hxx>

#define DEFAULT_TAB 2000

#define DEF_INCH    2540L
#define DEF_RELTWIP 1440L

using namespace rtl;
using namespace com::sun::star::uno;

#define C2U(cChar) OUString::createFromAscii(cChar)
/*--------------------------------------------------------------------
     Beschreibung:
 --------------------------------------------------------------------*/
SfxMiscCfg::SfxMiscCfg() :
    ConfigItem(C2U("Office.Common") ),
    nYear2000( SvNumberFormatter::GetYear2000Default() ),
    bNotFound (FALSE),
    bPaperSize(FALSE),
    bPaperOrientation (FALSE)
{
    RTL_LOGFILE_CONTEXT(aLog, "svtools (???) SfxMiscCfg::SfxMiscCfg()");

    Load();
}
/* -----------------------------02.03.01 15:31--------------------------------

 ---------------------------------------------------------------------------*/
SfxMiscCfg::~SfxMiscCfg()
{
}
/*--------------------------------------------------------------------
     Beschreibung:
 --------------------------------------------------------------------*/

void SfxMiscCfg::SetNotFoundWarning( BOOL bSet)
{
    if(bNotFound != bSet)
        SetModified();
    bNotFound = bSet;
}

/*--------------------------------------------------------------------
     Beschreibung:
 --------------------------------------------------------------------*/

void SfxMiscCfg::SetPaperSizeWarning( BOOL bSet)
{
    if(bPaperSize != bSet)
        SetModified();
    bPaperSize = bSet;
}

/*--------------------------------------------------------------------
     Beschreibung:
 --------------------------------------------------------------------*/
void SfxMiscCfg::SetPaperOrientationWarning( BOOL bSet)
{
    if(bPaperOrientation != bSet)
        SetModified();
    bPaperOrientation = bSet;
}
/*--------------------------------------------------------------------
     Beschreibung:
 --------------------------------------------------------------------*/

void SfxMiscCfg::SetYear2000( sal_Int32 nSet )
{
    if(nYear2000 != nSet)
        SetModified();
    nYear2000 = nSet;
}
/* -----------------------------02.03.01 15:31--------------------------------

 ---------------------------------------------------------------------------*/
const Sequence<OUString>& SfxMiscCfg::GetPropertyNames()
{
    static Sequence<OUString> aNames;
    if(!aNames.getLength())
    {
        static const char* aPropNames[] =
        {
               "Print/Warning/PaperSize",               //  0
               "Print/Warning/PaperOrientation",        //  1
               "Print/Warning/NotFound",                //  2
            "DateFormat/TwoDigitYear",              //  3
        };
        const int nCount = 4;
        aNames.realloc(nCount);
        OUString* pNames = aNames.getArray();
        for(int i = 0; i < nCount; i++)
            pNames[i] = OUString::createFromAscii(aPropNames[i]);
    }
    return aNames;
}
/* -----------------------------02.03.01 15:31--------------------------------

 ---------------------------------------------------------------------------*/
void SfxMiscCfg::Load()
{
    const Sequence<OUString>& aNames = GetPropertyNames();
    Sequence<Any> aValues = GetProperties(aNames);
    EnableNotification(aNames);
    const Any* pValues = aValues.getConstArray();
    DBG_ASSERT(aValues.getLength() == aNames.getLength(), "GetProperties failed")
    if(aValues.getLength() == aNames.getLength())
    {
        for(int nProp = 0; nProp < aNames.getLength(); nProp++)
        {
            if(pValues[nProp].hasValue())
            {
                switch(nProp)
                {
                    case  0: bPaperSize        = *(sal_Bool*)pValues[nProp].getValue(); break;      //"Print/Warning/PaperSize",
                    case  1: bPaperOrientation = *(sal_Bool*)pValues[nProp].getValue();  break;     //"Print/Warning/PaperOrientation",
                    case  2: bNotFound         = *(sal_Bool*)pValues[nProp].getValue()  ;  break;   //"Print/Warning/NotFound",
                    case  3: pValues[nProp] >>= nYear2000;break;                                    //"DateFormat/TwoDigitYear",
                }
            }
        }
    }
}
/* -----------------------------02.03.01 15:31--------------------------------

 ---------------------------------------------------------------------------*/
void SfxMiscCfg::Notify( const com::sun::star::uno::Sequence<rtl::OUString>& aPropertyNames)
{
    Load();
}
/* -----------------------------02.03.01 15:31--------------------------------

 ---------------------------------------------------------------------------*/
void SfxMiscCfg::Commit()
{
    const Sequence<OUString>& aNames = GetPropertyNames();
    const OUString* pNames = aNames.getConstArray();
    Sequence<Any> aValues(aNames.getLength());
    Any* pValues = aValues.getArray();

    const Type& rType = ::getBooleanCppuType();
    for(int nProp = 0; nProp < aNames.getLength(); nProp++)
    {
        switch(nProp)
        {
            case  0: pValues[nProp].setValue(&bPaperSize, rType);break;  //"Print/Warning/PaperSize",
            case  1: pValues[nProp].setValue(&bPaperOrientation, rType);break;     //"Print/Warning/PaperOrientation",
            case  2: pValues[nProp].setValue(&bNotFound, rType);break;   //"Print/Warning/NotFound",
            case  3: pValues[nProp] <<= nYear2000;break;                 //"DateFormat/TwoDigitYear",
        }
    }
    PutProperties(aNames, aValues);
}

<commit_msg>INTEGRATION: CWS warnings01 (1.4.62); FILE MERGED 2006/01/27 16:43:23 sb 1.4.62.4: #i53898# Made code warning-free. 2006/01/25 19:41:51 sb 1.4.62.3: RESYNC: (1.4-1.5); FILE MERGED 2005/11/14 14:23:36 pl 1.4.62.2: #i55991# removed warnings 2005/10/25 12:44:22 pl 1.4.62.1: #i55991# removed warnings for linux platform<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: misccfg.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 20:46:55 $
 *
 *  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
 *
 ************************************************************************/

#ifdef  SVL_DLLIMPLEMENTATION
#undef  SVL_DLLIMPLEMENTATION
#endif
#define SVT_DLLIMPLEMENTATION

#include "misccfg.hxx"

#ifndef _ZFORLIST_HXX //autogen
#include "zforlist.hxx"
#endif

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

#include <rtl/logfile.hxx>

#define DEFAULT_TAB 2000

#define DEF_INCH    2540L
#define DEF_RELTWIP 1440L

using namespace rtl;
using namespace com::sun::star::uno;

#define C2U(cChar) OUString::createFromAscii(cChar)
/*--------------------------------------------------------------------
     Beschreibung:
 --------------------------------------------------------------------*/
SfxMiscCfg::SfxMiscCfg() :
    ConfigItem(C2U("Office.Common") ),
    bPaperSize(FALSE),
    bPaperOrientation (FALSE),
    bNotFound (FALSE),
    nYear2000( SvNumberFormatter::GetYear2000Default() )
{
    RTL_LOGFILE_CONTEXT(aLog, "svtools SfxMiscCfg::SfxMiscCfg()");

    Load();
}
/* -----------------------------02.03.01 15:31--------------------------------

 ---------------------------------------------------------------------------*/
SfxMiscCfg::~SfxMiscCfg()
{
}
/*--------------------------------------------------------------------
     Beschreibung:
 --------------------------------------------------------------------*/

void SfxMiscCfg::SetNotFoundWarning( BOOL bSet)
{
    if(bNotFound != bSet)
        SetModified();
    bNotFound = bSet;
}

/*--------------------------------------------------------------------
     Beschreibung:
 --------------------------------------------------------------------*/

void SfxMiscCfg::SetPaperSizeWarning( BOOL bSet)
{
    if(bPaperSize != bSet)
        SetModified();
    bPaperSize = bSet;
}

/*--------------------------------------------------------------------
     Beschreibung:
 --------------------------------------------------------------------*/
void SfxMiscCfg::SetPaperOrientationWarning( BOOL bSet)
{
    if(bPaperOrientation != bSet)
        SetModified();
    bPaperOrientation = bSet;
}
/*--------------------------------------------------------------------
     Beschreibung:
 --------------------------------------------------------------------*/

void SfxMiscCfg::SetYear2000( sal_Int32 nSet )
{
    if(nYear2000 != nSet)
        SetModified();
    nYear2000 = nSet;
}
/* -----------------------------02.03.01 15:31--------------------------------

 ---------------------------------------------------------------------------*/
const Sequence<OUString>& SfxMiscCfg::GetPropertyNames()
{
    static Sequence<OUString> aNames;
    if(!aNames.getLength())
    {
        static const char* aPropNames[] =
        {
               "Print/Warning/PaperSize",               //  0
               "Print/Warning/PaperOrientation",        //  1
               "Print/Warning/NotFound",                //  2
            "DateFormat/TwoDigitYear",              //  3
        };
        const int nCount = 4;
        aNames.realloc(nCount);
        OUString* pNames = aNames.getArray();
        for(int i = 0; i < nCount; i++)
            pNames[i] = OUString::createFromAscii(aPropNames[i]);
    }
    return aNames;
}
/* -----------------------------02.03.01 15:31--------------------------------

 ---------------------------------------------------------------------------*/
void SfxMiscCfg::Load()
{
    const Sequence<OUString>& aNames = GetPropertyNames();
    Sequence<Any> aValues = GetProperties(aNames);
    EnableNotification(aNames);
    const Any* pValues = aValues.getConstArray();
    DBG_ASSERT(aValues.getLength() == aNames.getLength(), "GetProperties failed")
    if(aValues.getLength() == aNames.getLength())
    {
        for(int nProp = 0; nProp < aNames.getLength(); nProp++)
        {
            if(pValues[nProp].hasValue())
            {
                switch(nProp)
                {
                    case  0: bPaperSize        = *(sal_Bool*)pValues[nProp].getValue(); break;      //"Print/Warning/PaperSize",
                    case  1: bPaperOrientation = *(sal_Bool*)pValues[nProp].getValue();  break;     //"Print/Warning/PaperOrientation",
                    case  2: bNotFound         = *(sal_Bool*)pValues[nProp].getValue()  ;  break;   //"Print/Warning/NotFound",
                    case  3: pValues[nProp] >>= nYear2000;break;                                    //"DateFormat/TwoDigitYear",
                }
            }
        }
    }
}
/* -----------------------------02.03.01 15:31--------------------------------

 ---------------------------------------------------------------------------*/
void SfxMiscCfg::Notify( const com::sun::star::uno::Sequence<rtl::OUString>& )
{
    Load();
}
/* -----------------------------02.03.01 15:31--------------------------------

 ---------------------------------------------------------------------------*/
void SfxMiscCfg::Commit()
{
    const Sequence<OUString>& aNames = GetPropertyNames();
    Sequence<Any> aValues(aNames.getLength());
    Any* pValues = aValues.getArray();

    const Type& rType = ::getBooleanCppuType();
    for(int nProp = 0; nProp < aNames.getLength(); nProp++)
    {
        switch(nProp)
        {
            case  0: pValues[nProp].setValue(&bPaperSize, rType);break;  //"Print/Warning/PaperSize",
            case  1: pValues[nProp].setValue(&bPaperOrientation, rType);break;     //"Print/Warning/PaperOrientation",
            case  2: pValues[nProp].setValue(&bNotFound, rType);break;   //"Print/Warning/NotFound",
            case  3: pValues[nProp] <<= nYear2000;break;                 //"DateFormat/TwoDigitYear",
        }
    }
    PutProperties(aNames, aValues);
}

<|endoftext|>