<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetSinogramTest
#include <boost/test/unit_test.hpp>
#include <boost/numeric/ublas/matrix.hpp>
using namespace boost::numeric::ublas;

#include "./JPetSinogram.h"

BOOST_AUTO_TEST_SUITE(FirstSuite)

BOOST_AUTO_TEST_CASE( emissionMatrix_sinogram_0_degree )
{
  matrix<int> m (2, 2);
  m(0, 0) = 2;
  m(0, 1) = 3;
  m(1, 0) = 4;
  m(1, 1) = 1;

  JPetSinogram sin;
  BOOST_REQUIRE_EQUAL(sin.forwardProjection(0, 0, m), 5ll);
  BOOST_REQUIRE_EQUAL(sin.forwardProjection(1, 0, m), 5ll);
  BOOST_REQUIRE_EQUAL(sin.forwardProjection(0, 90, m), 6ll);
  BOOST_REQUIRE_EQUAL(sin.forwardProjection(1, 90, m), 4ll);
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Add 45theta tests with matrix 3x3<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetSinogramTest
#include <boost/test/unit_test.hpp>
#include <boost/numeric/ublas/matrix.hpp>
using namespace boost::numeric::ublas;

#include "./JPetSinogram.h"

BOOST_AUTO_TEST_SUITE(FirstSuite)

BOOST_AUTO_TEST_CASE( emissionMatrix_projection )
{
  matrix<int> m (2, 2);
  m(0, 0) = 2;
  m(0, 1) = 3;
  m(1, 0) = 4;
  m(1, 1) = 1;

  JPetSinogram sin;
  BOOST_REQUIRE_EQUAL(sin.forwardProjection(0, 0, m), 5ll);
  BOOST_REQUIRE_EQUAL(sin.forwardProjection(1, 0, m), 5ll);
  BOOST_REQUIRE_EQUAL(sin.forwardProjection(0, 90, m), 6ll);
  BOOST_REQUIRE_EQUAL(sin.forwardProjection(1, 90, m), 4ll);
  BOOST_REQUIRE_EQUAL(sin.forwardProjection(0, 45, m), 3ll);
  BOOST_REQUIRE_EQUAL(sin.forwardProjection(1, 45, m), 3ll);
  BOOST_REQUIRE_EQUAL(sin.forwardProjection(2, 45, m), 4ll);
}

BOOST_AUTO_TEST_CASE( emissionMatrix_45theta )
{
  matrix<int> m (3, 3);
  /*
    3 4 5
    1 2 7
    9 3 2
    s = 0 - 5
    s = 1 - 11
    s = 2 - 7
    s = 3 - 4
    s = 4 - 9
  */
  m(0, 0) = 3;
  m(0, 1) = 4;
  m(0, 2) = 5;

  m(1, 0) = 1;
  m(1, 1) = 2;
  m(1, 2) = 7;

  m(2, 0) = 9;
  m(2, 1) = 3;
  m(2, 2) = 2;

  JPetSinogram sin;
  BOOST_REQUIRE_EQUAL(sin.forwardProjection(0, 45, m), 5ll);
  BOOST_REQUIRE_EQUAL(sin.forwardProjection(1, 45, m), 11ll);
  BOOST_REQUIRE_EQUAL(sin.forwardProjection(2, 45, m), 7ll);
  BOOST_REQUIRE_EQUAL(sin.forwardProjection(3, 45, m), 4ll);
  BOOST_REQUIRE_EQUAL(sin.forwardProjection(4, 45, m), 9ll);
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>// Copyright (c) 2009-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <coins.h>
#include <consensus/tx_verify.h>
#include <policy/policy.h>
#include <psbt.h>
#include <util/strencodings.h>

#include <numeric>

PartiallySignedTransaction::PartiallySignedTransaction(const CMutableTransaction& tx) : tx(tx)
{
    inputs.resize(tx.vin.size());
    outputs.resize(tx.vout.size());
}

bool PartiallySignedTransaction::IsNull() const
{
    return !tx && inputs.empty() && outputs.empty() && unknown.empty();
}

bool PartiallySignedTransaction::Merge(const PartiallySignedTransaction& psbt)
{
    // Prohibited to merge two PSBTs over different transactions
    if (tx->GetHash() != psbt.tx->GetHash()) {
        return false;
    }

    for (unsigned int i = 0; i < inputs.size(); ++i) {
        inputs[i].Merge(psbt.inputs[i]);
    }
    for (unsigned int i = 0; i < outputs.size(); ++i) {
        outputs[i].Merge(psbt.outputs[i]);
    }
    unknown.insert(psbt.unknown.begin(), psbt.unknown.end());

    return true;
}

bool PartiallySignedTransaction::IsSane() const
{
    for (PSBTInput input : inputs) {
        if (!input.IsSane()) return false;
    }
    return true;
}

bool PartiallySignedTransaction::AddInput(const CTxIn& txin, PSBTInput& psbtin)
{
    if (std::find(tx->vin.begin(), tx->vin.end(), txin) != tx->vin.end()) {
        return false;
    }
    tx->vin.push_back(txin);
    psbtin.partial_sigs.clear();
    psbtin.final_script_sig.clear();
    psbtin.final_script_witness.SetNull();
    inputs.push_back(psbtin);
    return true;
}

bool PartiallySignedTransaction::AddOutput(const CTxOut& txout, const PSBTOutput& psbtout)
{
    tx->vout.push_back(txout);
    outputs.push_back(psbtout);
    return true;
}

bool PartiallySignedTransaction::GetInputUTXO(CTxOut& utxo, int input_index) const
{
    PSBTInput input = inputs[input_index];
    int prevout_index = tx->vin[input_index].prevout.n;
    if (input.non_witness_utxo) {
        utxo = input.non_witness_utxo->vout[prevout_index];
    } else if (!input.witness_utxo.IsNull()) {
        utxo = input.witness_utxo;
    } else {
        return false;
    }
    return true;
}

bool PSBTInput::IsNull() const
{
    return !non_witness_utxo && witness_utxo.IsNull() && partial_sigs.empty() && unknown.empty() && hd_keypaths.empty() && redeem_script.empty() && witness_script.empty();
}

void PSBTInput::FillSignatureData(SignatureData& sigdata) const
{
    if (!final_script_sig.empty()) {
        sigdata.scriptSig = final_script_sig;
        sigdata.complete = true;
    }
    if (!final_script_witness.IsNull()) {
        sigdata.scriptWitness = final_script_witness;
        sigdata.complete = true;
    }
    if (sigdata.complete) {
        return;
    }

    sigdata.signatures.insert(partial_sigs.begin(), partial_sigs.end());
    if (!redeem_script.empty()) {
        sigdata.redeem_script = redeem_script;
    }
    if (!witness_script.empty()) {
        sigdata.witness_script = witness_script;
    }
    for (const auto& key_pair : hd_keypaths) {
        sigdata.misc_pubkeys.emplace(key_pair.first.GetID(), key_pair);
    }
}

void PSBTInput::FromSignatureData(const SignatureData& sigdata)
{
    if (sigdata.complete) {
        partial_sigs.clear();
        hd_keypaths.clear();
        redeem_script.clear();
        witness_script.clear();

        if (!sigdata.scriptSig.empty()) {
            final_script_sig = sigdata.scriptSig;
        }
        if (!sigdata.scriptWitness.IsNull()) {
            final_script_witness = sigdata.scriptWitness;
        }
        return;
    }

    partial_sigs.insert(sigdata.signatures.begin(), sigdata.signatures.end());
    if (redeem_script.empty() && !sigdata.redeem_script.empty()) {
        redeem_script = sigdata.redeem_script;
    }
    if (witness_script.empty() && !sigdata.witness_script.empty()) {
        witness_script = sigdata.witness_script;
    }
    for (const auto& entry : sigdata.misc_pubkeys) {
        hd_keypaths.emplace(entry.second);
    }
}

void PSBTInput::Merge(const PSBTInput& input)
{
    if (!non_witness_utxo && input.non_witness_utxo) non_witness_utxo = input.non_witness_utxo;
    if (witness_utxo.IsNull() && !input.witness_utxo.IsNull()) {
        witness_utxo = input.witness_utxo;
        non_witness_utxo = nullptr; // Clear out any non-witness utxo when we set a witness one.
    }

    partial_sigs.insert(input.partial_sigs.begin(), input.partial_sigs.end());
    hd_keypaths.insert(input.hd_keypaths.begin(), input.hd_keypaths.end());
    unknown.insert(input.unknown.begin(), input.unknown.end());

    if (redeem_script.empty() && !input.redeem_script.empty()) redeem_script = input.redeem_script;
    if (witness_script.empty() && !input.witness_script.empty()) witness_script = input.witness_script;
    if (final_script_sig.empty() && !input.final_script_sig.empty()) final_script_sig = input.final_script_sig;
    if (final_script_witness.IsNull() && !input.final_script_witness.IsNull()) final_script_witness = input.final_script_witness;
}

bool PSBTInput::IsSane() const
{
    // Cannot have both witness and non-witness utxos
    if (!witness_utxo.IsNull() && non_witness_utxo) return false;

    // If we have a witness_script or a scriptWitness, we must also have a witness utxo
    if (!witness_script.empty() && witness_utxo.IsNull()) return false;
    if (!final_script_witness.IsNull() && witness_utxo.IsNull()) return false;

    return true;
}

void PSBTOutput::FillSignatureData(SignatureData& sigdata) const
{
    if (!redeem_script.empty()) {
        sigdata.redeem_script = redeem_script;
    }
    if (!witness_script.empty()) {
        sigdata.witness_script = witness_script;
    }
    for (const auto& key_pair : hd_keypaths) {
        sigdata.misc_pubkeys.emplace(key_pair.first.GetID(), key_pair);
    }
}

void PSBTOutput::FromSignatureData(const SignatureData& sigdata)
{
    if (redeem_script.empty() && !sigdata.redeem_script.empty()) {
        redeem_script = sigdata.redeem_script;
    }
    if (witness_script.empty() && !sigdata.witness_script.empty()) {
        witness_script = sigdata.witness_script;
    }
    for (const auto& entry : sigdata.misc_pubkeys) {
        hd_keypaths.emplace(entry.second);
    }
}

bool PSBTOutput::IsNull() const
{
    return redeem_script.empty() && witness_script.empty() && hd_keypaths.empty() && unknown.empty();
}

void PSBTOutput::Merge(const PSBTOutput& output)
{
    hd_keypaths.insert(output.hd_keypaths.begin(), output.hd_keypaths.end());
    unknown.insert(output.unknown.begin(), output.unknown.end());

    if (redeem_script.empty() && !output.redeem_script.empty()) redeem_script = output.redeem_script;
    if (witness_script.empty() && !output.witness_script.empty()) witness_script = output.witness_script;
}

bool PSBTInputSigned(const PSBTInput& input)
{
    return !input.final_script_sig.empty() || !input.final_script_witness.IsNull();
}

bool SignPSBTInput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index, int sighash, SignatureData* out_sigdata, bool use_dummy)
{
    PSBTInput& input = psbt.inputs.at(index);
    const CMutableTransaction& tx = *psbt.tx;

    if (PSBTInputSigned(input)) {
        return true;
    }

    // Fill SignatureData with input info
    SignatureData sigdata;
    input.FillSignatureData(sigdata);

    // Get UTXO
    bool require_witness_sig = false;
    CTxOut utxo;

    // Verify input sanity, which checks that at most one of witness or non-witness utxos is provided.
    if (!input.IsSane()) {
        return false;
    }

    if (input.non_witness_utxo) {
        // If we're taking our information from a non-witness UTXO, verify that it matches the prevout.
        COutPoint prevout = tx.vin[index].prevout;
        if (input.non_witness_utxo->GetHash() != prevout.hash) {
            return false;
        }
        utxo = input.non_witness_utxo->vout[prevout.n];
    } else if (!input.witness_utxo.IsNull()) {
        utxo = input.witness_utxo;
        // When we're taking our information from a witness UTXO, we can't verify it is actually data from
        // the output being spent. This is safe in case a witness signature is produced (which includes this
        // information directly in the hash), but not for non-witness signatures. Remember that we require
        // a witness signature in this situation.
        require_witness_sig = true;
    } else {
        return false;
    }

    sigdata.witness = false;
    bool sig_complete;
    if (use_dummy) {
        sig_complete = ProduceSignature(provider, DUMMY_SIGNATURE_CREATOR, utxo.scriptPubKey, sigdata);
    } else {
        MutableTransactionSignatureCreator creator(&tx, index, utxo.nValue, sighash);
        sig_complete = ProduceSignature(provider, creator, utxo.scriptPubKey, sigdata);
    }
    // Verify that a witness signature was produced in case one was required.
    if (require_witness_sig && !sigdata.witness) return false;
    input.FromSignatureData(sigdata);

    // If we have a witness signature, use the smaller witness UTXO.
    if (sigdata.witness) {
        input.witness_utxo = utxo;
        input.non_witness_utxo = nullptr;
    }

    // Fill in the missing info
    if (out_sigdata) {
        out_sigdata->missing_pubkeys = sigdata.missing_pubkeys;
        out_sigdata->missing_sigs = sigdata.missing_sigs;
        out_sigdata->missing_redeem_script = sigdata.missing_redeem_script;
        out_sigdata->missing_witness_script = sigdata.missing_witness_script;
    }

    return sig_complete;
}

bool FinalizePSBT(PartiallySignedTransaction& psbtx)
{
    // Finalize input signatures -- in case we have partial signatures that add up to a complete
    //   signature, but have not combined them yet (e.g. because the combiner that created this
    //   PartiallySignedTransaction did not understand them), this will combine them into a final
    //   script.
    bool complete = true;
    for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
        complete &= SignPSBTInput(DUMMY_SIGNING_PROVIDER, psbtx, i, SIGHASH_ALL);
    }

    return complete;
}

bool FinalizeAndExtractPSBT(PartiallySignedTransaction& psbtx, CMutableTransaction& result)
{
    // It's not safe to extract a PSBT that isn't finalized, and there's no easy way to check
    //   whether a PSBT is finalized without finalizing it, so we just do this.
    if (!FinalizePSBT(psbtx)) {
        return false;
    }

    result = *psbtx.tx;
    for (unsigned int i = 0; i < result.vin.size(); ++i) {
        result.vin[i].scriptSig = psbtx.inputs[i].final_script_sig;
        result.vin[i].scriptWitness = psbtx.inputs[i].final_script_witness;
    }
    return true;
}

TransactionError CombinePSBTs(PartiallySignedTransaction& out, const std::vector<PartiallySignedTransaction>& psbtxs)
{
    out = psbtxs[0]; // Copy the first one

    // Merge
    for (auto it = std::next(psbtxs.begin()); it != psbtxs.end(); ++it) {
        if (!out.Merge(*it)) {
            return TransactionError::PSBT_MISMATCH;
        }
    }
    if (!out.IsSane()) {
        return TransactionError::INVALID_PSBT;
    }

    return TransactionError::OK;
}

std::string PSBTRoleName(PSBTRole role) {
    switch (role) {
    case PSBTRole::UPDATER: return "updater";
    case PSBTRole::SIGNER: return "signer";
    case PSBTRole::FINALIZER: return "finalizer";
    case PSBTRole::EXTRACTOR: return "extractor";
    }
}

bool DecodeBase64PSBT(PartiallySignedTransaction& psbt, const std::string& base64_tx, std::string& error)
{
    bool invalid;
    std::string tx_data = DecodeBase64(base64_tx, &invalid);
    if (invalid) {
        error = "invalid base64";
        return false;
    }
    return DecodeRawPSBT(psbt, tx_data, error);
}

bool DecodeRawPSBT(PartiallySignedTransaction& psbt, const std::string& tx_data, std::string& error)
{
    CDataStream ss_data(tx_data.data(), tx_data.data() + tx_data.size(), SER_NETWORK, PROTOCOL_VERSION);
    try {
        ss_data >> psbt;
        if (!ss_data.empty()) {
            error = "extra data after PSBT";
            return false;
        }
    } catch (const std::exception& e) {
        error = e.what();
        return false;
    }
    return true;
}<commit_msg>Bitcoin: beb42d71a0fd8ac75f3c889cb650b7d21fa9a740 (Silence GCC 7 warning 'control reaches end of non-void function' (-Wreturn-type) in psbt.cpp).<commit_after>// Copyright (c) 2009-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <coins.h>
#include <consensus/tx_verify.h>
#include <policy/policy.h>
#include <psbt.h>
#include <util/strencodings.h>

#include <numeric>

PartiallySignedTransaction::PartiallySignedTransaction(const CMutableTransaction& tx) : tx(tx)
{
    inputs.resize(tx.vin.size());
    outputs.resize(tx.vout.size());
}

bool PartiallySignedTransaction::IsNull() const
{
    return !tx && inputs.empty() && outputs.empty() && unknown.empty();
}

bool PartiallySignedTransaction::Merge(const PartiallySignedTransaction& psbt)
{
    // Prohibited to merge two PSBTs over different transactions
    if (tx->GetHash() != psbt.tx->GetHash()) {
        return false;
    }

    for (unsigned int i = 0; i < inputs.size(); ++i) {
        inputs[i].Merge(psbt.inputs[i]);
    }
    for (unsigned int i = 0; i < outputs.size(); ++i) {
        outputs[i].Merge(psbt.outputs[i]);
    }
    unknown.insert(psbt.unknown.begin(), psbt.unknown.end());

    return true;
}

bool PartiallySignedTransaction::IsSane() const
{
    for (PSBTInput input : inputs) {
        if (!input.IsSane()) return false;
    }
    return true;
}

bool PartiallySignedTransaction::AddInput(const CTxIn& txin, PSBTInput& psbtin)
{
    if (std::find(tx->vin.begin(), tx->vin.end(), txin) != tx->vin.end()) {
        return false;
    }
    tx->vin.push_back(txin);
    psbtin.partial_sigs.clear();
    psbtin.final_script_sig.clear();
    psbtin.final_script_witness.SetNull();
    inputs.push_back(psbtin);
    return true;
}

bool PartiallySignedTransaction::AddOutput(const CTxOut& txout, const PSBTOutput& psbtout)
{
    tx->vout.push_back(txout);
    outputs.push_back(psbtout);
    return true;
}

bool PartiallySignedTransaction::GetInputUTXO(CTxOut& utxo, int input_index) const
{
    PSBTInput input = inputs[input_index];
    int prevout_index = tx->vin[input_index].prevout.n;
    if (input.non_witness_utxo) {
        utxo = input.non_witness_utxo->vout[prevout_index];
    } else if (!input.witness_utxo.IsNull()) {
        utxo = input.witness_utxo;
    } else {
        return false;
    }
    return true;
}

bool PSBTInput::IsNull() const
{
    return !non_witness_utxo && witness_utxo.IsNull() && partial_sigs.empty() && unknown.empty() && hd_keypaths.empty() && redeem_script.empty() && witness_script.empty();
}

void PSBTInput::FillSignatureData(SignatureData& sigdata) const
{
    if (!final_script_sig.empty()) {
        sigdata.scriptSig = final_script_sig;
        sigdata.complete = true;
    }
    if (!final_script_witness.IsNull()) {
        sigdata.scriptWitness = final_script_witness;
        sigdata.complete = true;
    }
    if (sigdata.complete) {
        return;
    }

    sigdata.signatures.insert(partial_sigs.begin(), partial_sigs.end());
    if (!redeem_script.empty()) {
        sigdata.redeem_script = redeem_script;
    }
    if (!witness_script.empty()) {
        sigdata.witness_script = witness_script;
    }
    for (const auto& key_pair : hd_keypaths) {
        sigdata.misc_pubkeys.emplace(key_pair.first.GetID(), key_pair);
    }
}

void PSBTInput::FromSignatureData(const SignatureData& sigdata)
{
    if (sigdata.complete) {
        partial_sigs.clear();
        hd_keypaths.clear();
        redeem_script.clear();
        witness_script.clear();

        if (!sigdata.scriptSig.empty()) {
            final_script_sig = sigdata.scriptSig;
        }
        if (!sigdata.scriptWitness.IsNull()) {
            final_script_witness = sigdata.scriptWitness;
        }
        return;
    }

    partial_sigs.insert(sigdata.signatures.begin(), sigdata.signatures.end());
    if (redeem_script.empty() && !sigdata.redeem_script.empty()) {
        redeem_script = sigdata.redeem_script;
    }
    if (witness_script.empty() && !sigdata.witness_script.empty()) {
        witness_script = sigdata.witness_script;
    }
    for (const auto& entry : sigdata.misc_pubkeys) {
        hd_keypaths.emplace(entry.second);
    }
}

void PSBTInput::Merge(const PSBTInput& input)
{
    if (!non_witness_utxo && input.non_witness_utxo) non_witness_utxo = input.non_witness_utxo;
    if (witness_utxo.IsNull() && !input.witness_utxo.IsNull()) {
        witness_utxo = input.witness_utxo;
        non_witness_utxo = nullptr; // Clear out any non-witness utxo when we set a witness one.
    }

    partial_sigs.insert(input.partial_sigs.begin(), input.partial_sigs.end());
    hd_keypaths.insert(input.hd_keypaths.begin(), input.hd_keypaths.end());
    unknown.insert(input.unknown.begin(), input.unknown.end());

    if (redeem_script.empty() && !input.redeem_script.empty()) redeem_script = input.redeem_script;
    if (witness_script.empty() && !input.witness_script.empty()) witness_script = input.witness_script;
    if (final_script_sig.empty() && !input.final_script_sig.empty()) final_script_sig = input.final_script_sig;
    if (final_script_witness.IsNull() && !input.final_script_witness.IsNull()) final_script_witness = input.final_script_witness;
}

bool PSBTInput::IsSane() const
{
    // Cannot have both witness and non-witness utxos
    if (!witness_utxo.IsNull() && non_witness_utxo) return false;

    // If we have a witness_script or a scriptWitness, we must also have a witness utxo
    if (!witness_script.empty() && witness_utxo.IsNull()) return false;
    if (!final_script_witness.IsNull() && witness_utxo.IsNull()) return false;

    return true;
}

void PSBTOutput::FillSignatureData(SignatureData& sigdata) const
{
    if (!redeem_script.empty()) {
        sigdata.redeem_script = redeem_script;
    }
    if (!witness_script.empty()) {
        sigdata.witness_script = witness_script;
    }
    for (const auto& key_pair : hd_keypaths) {
        sigdata.misc_pubkeys.emplace(key_pair.first.GetID(), key_pair);
    }
}

void PSBTOutput::FromSignatureData(const SignatureData& sigdata)
{
    if (redeem_script.empty() && !sigdata.redeem_script.empty()) {
        redeem_script = sigdata.redeem_script;
    }
    if (witness_script.empty() && !sigdata.witness_script.empty()) {
        witness_script = sigdata.witness_script;
    }
    for (const auto& entry : sigdata.misc_pubkeys) {
        hd_keypaths.emplace(entry.second);
    }
}

bool PSBTOutput::IsNull() const
{
    return redeem_script.empty() && witness_script.empty() && hd_keypaths.empty() && unknown.empty();
}

void PSBTOutput::Merge(const PSBTOutput& output)
{
    hd_keypaths.insert(output.hd_keypaths.begin(), output.hd_keypaths.end());
    unknown.insert(output.unknown.begin(), output.unknown.end());

    if (redeem_script.empty() && !output.redeem_script.empty()) redeem_script = output.redeem_script;
    if (witness_script.empty() && !output.witness_script.empty()) witness_script = output.witness_script;
}

bool PSBTInputSigned(const PSBTInput& input)
{
    return !input.final_script_sig.empty() || !input.final_script_witness.IsNull();
}

bool SignPSBTInput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index, int sighash, SignatureData* out_sigdata, bool use_dummy)
{
    PSBTInput& input = psbt.inputs.at(index);
    const CMutableTransaction& tx = *psbt.tx;

    if (PSBTInputSigned(input)) {
        return true;
    }

    // Fill SignatureData with input info
    SignatureData sigdata;
    input.FillSignatureData(sigdata);

    // Get UTXO
    bool require_witness_sig = false;
    CTxOut utxo;

    // Verify input sanity, which checks that at most one of witness or non-witness utxos is provided.
    if (!input.IsSane()) {
        return false;
    }

    if (input.non_witness_utxo) {
        // If we're taking our information from a non-witness UTXO, verify that it matches the prevout.
        COutPoint prevout = tx.vin[index].prevout;
        if (input.non_witness_utxo->GetHash() != prevout.hash) {
            return false;
        }
        utxo = input.non_witness_utxo->vout[prevout.n];
    } else if (!input.witness_utxo.IsNull()) {
        utxo = input.witness_utxo;
        // When we're taking our information from a witness UTXO, we can't verify it is actually data from
        // the output being spent. This is safe in case a witness signature is produced (which includes this
        // information directly in the hash), but not for non-witness signatures. Remember that we require
        // a witness signature in this situation.
        require_witness_sig = true;
    } else {
        return false;
    }

    sigdata.witness = false;
    bool sig_complete;
    if (use_dummy) {
        sig_complete = ProduceSignature(provider, DUMMY_SIGNATURE_CREATOR, utxo.scriptPubKey, sigdata);
    } else {
        MutableTransactionSignatureCreator creator(&tx, index, utxo.nValue, sighash);
        sig_complete = ProduceSignature(provider, creator, utxo.scriptPubKey, sigdata);
    }
    // Verify that a witness signature was produced in case one was required.
    if (require_witness_sig && !sigdata.witness) return false;
    input.FromSignatureData(sigdata);

    // If we have a witness signature, use the smaller witness UTXO.
    if (sigdata.witness) {
        input.witness_utxo = utxo;
        input.non_witness_utxo = nullptr;
    }

    // Fill in the missing info
    if (out_sigdata) {
        out_sigdata->missing_pubkeys = sigdata.missing_pubkeys;
        out_sigdata->missing_sigs = sigdata.missing_sigs;
        out_sigdata->missing_redeem_script = sigdata.missing_redeem_script;
        out_sigdata->missing_witness_script = sigdata.missing_witness_script;
    }

    return sig_complete;
}

bool FinalizePSBT(PartiallySignedTransaction& psbtx)
{
    // Finalize input signatures -- in case we have partial signatures that add up to a complete
    //   signature, but have not combined them yet (e.g. because the combiner that created this
    //   PartiallySignedTransaction did not understand them), this will combine them into a final
    //   script.
    bool complete = true;
    for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
        complete &= SignPSBTInput(DUMMY_SIGNING_PROVIDER, psbtx, i, SIGHASH_ALL);
    }

    return complete;
}

bool FinalizeAndExtractPSBT(PartiallySignedTransaction& psbtx, CMutableTransaction& result)
{
    // It's not safe to extract a PSBT that isn't finalized, and there's no easy way to check
    //   whether a PSBT is finalized without finalizing it, so we just do this.
    if (!FinalizePSBT(psbtx)) {
        return false;
    }

    result = *psbtx.tx;
    for (unsigned int i = 0; i < result.vin.size(); ++i) {
        result.vin[i].scriptSig = psbtx.inputs[i].final_script_sig;
        result.vin[i].scriptWitness = psbtx.inputs[i].final_script_witness;
    }
    return true;
}

TransactionError CombinePSBTs(PartiallySignedTransaction& out, const std::vector<PartiallySignedTransaction>& psbtxs)
{
    out = psbtxs[0]; // Copy the first one

    // Merge
    for (auto it = std::next(psbtxs.begin()); it != psbtxs.end(); ++it) {
        if (!out.Merge(*it)) {
            return TransactionError::PSBT_MISMATCH;
        }
    }
    if (!out.IsSane()) {
        return TransactionError::INVALID_PSBT;
    }

    return TransactionError::OK;
}

std::string PSBTRoleName(PSBTRole role) {
    switch (role) {
    case PSBTRole::UPDATER: return "updater";
    case PSBTRole::SIGNER: return "signer";
    case PSBTRole::FINALIZER: return "finalizer";
    case PSBTRole::EXTRACTOR: return "extractor";
        // no default case, so the compiler can warn about missing cases
    }
    assert(false);
}

bool DecodeBase64PSBT(PartiallySignedTransaction& psbt, const std::string& base64_tx, std::string& error)
{
    bool invalid;
    std::string tx_data = DecodeBase64(base64_tx, &invalid);
    if (invalid) {
        error = "invalid base64";
        return false;
    }
    return DecodeRawPSBT(psbt, tx_data, error);
}

bool DecodeRawPSBT(PartiallySignedTransaction& psbt, const std::string& tx_data, std::string& error)
{
    CDataStream ss_data(tx_data.data(), tx_data.data() + tx_data.size(), SER_NETWORK, PROTOCOL_VERSION);
    try {
        ss_data >> psbt;
        if (!ss_data.empty()) {
            error = "extra data after PSBT";
            return false;
        }
    } catch (const std::exception& e) {
        error = e.what();
        return false;
    }
    return true;
}<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (c) 2009 Werner Mayer <wmayer[at]users.sourceforge.net>     *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 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 Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"

#ifndef _PreComp_
# include <QCheckBox>
#endif

#include <Standard_math.hxx>
#include "TaskDialog.h"
#include <Gui/Application.h>
#include <Gui/Command.h>
#include <Gui/Selection.h>
#include <Gui/Document.h>
#include <Gui/View3DInventor.h>
#include <Gui/View3DInventorViewer.h>
#include <Mod/Part/App/PartFeature.h>

using namespace DrawingGui;

/* TRANSLATOR DrawingGui::TaskProjection */

TaskProjection::TaskProjection()
{
    QString texts[10] =
    {
        tr("Visible sharp edges"),
        tr("Visible smooth edges"),
        tr("Visible sewn edges"),
        tr("Visible outline edges"),
        tr("Visible isoparameters"),
        tr("Hidden sharp edges"),
        tr("Hidden smooth edges"),
        tr("Hidden sewn edges"),
        tr("Hidden outline edges"),
        tr("Hidden isoparameters")
    };
    widget = new QWidget();
    QVBoxLayout *mainLayout = new QVBoxLayout;

    for (int i=0; i<10; i++) {
        QCheckBox* cb = new QCheckBox();
        if (i < 5)
            cb->setChecked(true);
        cb->setText(texts[i]);
        mainLayout->addWidget(cb);
        boxes.push_back(cb);
    }

    widget->setLayout(mainLayout);

    taskbox = new Gui::TaskView::TaskBox(
        QPixmap(), tr("Project shapes"), false, 0);
    taskbox->groupLayout()->addWidget(widget);
    Content.push_back(taskbox);
}

TaskProjection::~TaskProjection()
{
    // automatically deleted in the sub-class
}

bool TaskProjection::accept()
{
    Gui::Document* document = Gui::Application::Instance->activeDocument();
    if (!document)
        return false;
    Gui::MDIView* mdi = document->getActiveView();
    if (!mdi || !mdi->isDerivedFrom(Gui::View3DInventor::getClassTypeId()))
        return false;

    Gui::View3DInventorViewer* viewer = static_cast<Gui::View3DInventor*>(mdi)->getViewer();
    SbVec3f pnt, dir;
    viewer->getNearPlane(pnt, dir);
    float x=0, y=1,z=1;
    dir.getValue(x,y,z);

    std::vector<Part::Feature*> shapes = Gui::Selection().getObjectsOfType<Part::Feature>();
    Gui::Command::openCommand("Project shape");
    Gui::Command::doCommand(Gui::Command::Doc,"import Drawing");
    for (std::vector<Part::Feature*>::iterator it = shapes.begin(); it != shapes.end(); ++it) {
        const char* object = (*it)->getNameInDocument();
        Gui::Command::doCommand(Gui::Command::Doc,
            "FreeCAD.ActiveDocument.addObject('Drawing::FeatureProjection','%s_proj')", object);
        Gui::Command::doCommand(Gui::Command::Doc,
            "FreeCAD.ActiveDocument.ActiveObject.Direction=FreeCAD.Vector(%f,%f,%f)", x,y,z);
        Gui::Command::doCommand(Gui::Command::Doc,
            "FreeCAD.ActiveDocument.ActiveObject.Source=FreeCAD.ActiveDocument.%s", object);
        Gui::Command::doCommand(Gui::Command::Doc,
            "FreeCAD.ActiveDocument.ActiveObject.VCompound=%s", (boxes[0]->isChecked() ? "True" : "False"));
        Gui::Command::doCommand(Gui::Command::Doc,
            "FreeCAD.ActiveDocument.ActiveObject.Rg1LineVCompound=%s", (boxes[1]->isChecked() ? "True" : "False"));
        Gui::Command::doCommand(Gui::Command::Doc,
            "FreeCAD.ActiveDocument.ActiveObject.RgNLineVCompound=%s", (boxes[2]->isChecked() ? "True" : "False"));
        Gui::Command::doCommand(Gui::Command::Doc,
            "FreeCAD.ActiveDocument.ActiveObject.OutLineVCompound=%s", (boxes[3]->isChecked() ? "True" : "False"));
        Gui::Command::doCommand(Gui::Command::Doc,
            "FreeCAD.ActiveDocument.ActiveObject.IsoLineVCompound=%s", (boxes[4]->isChecked() ? "True" : "False"));
        Gui::Command::doCommand(Gui::Command::Doc,
            "FreeCAD.ActiveDocument.ActiveObject.HCompound=%s", (boxes[5]->isChecked() ? "True" : "False"));
        Gui::Command::doCommand(Gui::Command::Doc,
            "FreeCAD.ActiveDocument.ActiveObject.Rg1LineHCompound=%s", (boxes[6]->isChecked() ? "True" : "False"));
        Gui::Command::doCommand(Gui::Command::Doc,
            "FreeCAD.ActiveDocument.ActiveObject.RgNLineHCompound=%s", (boxes[7]->isChecked() ? "True" : "False"));
        Gui::Command::doCommand(Gui::Command::Doc,
            "FreeCAD.ActiveDocument.ActiveObject.OutLineHCompound=%s", (boxes[8]->isChecked() ? "True" : "False"));
        Gui::Command::doCommand(Gui::Command::Doc,
            "FreeCAD.ActiveDocument.ActiveObject.IsoLineHCompound=%s", (boxes[9]->isChecked() ? "True" : "False"));
    }
    Gui::Command::updateActive();
    Gui::Command::commitCommand();
    return true;
}

#include "moc_TaskDialog.cpp"
<commit_msg>+ improve error handling in projection panel in Drawing workbench<commit_after>/***************************************************************************
 *   Copyright (c) 2009 Werner Mayer <wmayer[at]users.sourceforge.net>     *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 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 Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"

#ifndef _PreComp_
# include <QCheckBox>
# include <QMessageBox>
#endif

#include <Standard_math.hxx>
#include "TaskDialog.h"
#include <Gui/Application.h>
#include <Gui/Command.h>
#include <Gui/Selection.h>
#include <Gui/Document.h>
#include <Gui/View3DInventor.h>
#include <Gui/View3DInventorViewer.h>
#include <Mod/Part/App/PartFeature.h>

using namespace DrawingGui;

/* TRANSLATOR DrawingGui::TaskProjection */

TaskProjection::TaskProjection()
{
    QString texts[10] =
    {
        tr("Visible sharp edges"),
        tr("Visible smooth edges"),
        tr("Visible sewn edges"),
        tr("Visible outline edges"),
        tr("Visible isoparameters"),
        tr("Hidden sharp edges"),
        tr("Hidden smooth edges"),
        tr("Hidden sewn edges"),
        tr("Hidden outline edges"),
        tr("Hidden isoparameters")
    };
    widget = new QWidget();
    QVBoxLayout *mainLayout = new QVBoxLayout;

    for (int i=0; i<10; i++) {
        QCheckBox* cb = new QCheckBox();
        if (i < 5)
            cb->setChecked(true);
        cb->setText(texts[i]);
        mainLayout->addWidget(cb);
        boxes.push_back(cb);
    }

    widget->setLayout(mainLayout);

    taskbox = new Gui::TaskView::TaskBox(
        QPixmap(), tr("Project shapes"), false, 0);
    taskbox->groupLayout()->addWidget(widget);
    Content.push_back(taskbox);
}

TaskProjection::~TaskProjection()
{
    // automatically deleted in the sub-class
}

bool TaskProjection::accept()
{
    Gui::Document* document = Gui::Application::Instance->activeDocument();
    if (!document) {
        QMessageBox::warning(widget, tr("No active document"),
            tr("There is currently no active document to complete the operation"));
        return true;
    }
    std::list<Gui::MDIView*> mdis = document->getMDIViewsOfType(Gui::View3DInventor::getClassTypeId());
    if (mdis.empty()) {
        QMessageBox::warning(widget, tr("No active view"),
            tr("There is currently no active view to complete the operation"));
        return false;
    }

    Gui::View3DInventorViewer* viewer = static_cast<Gui::View3DInventor*>(mdis.front())->getViewer();
    SbVec3f pnt, dir;
    viewer->getNearPlane(pnt, dir);
    float x=0, y=1,z=1;
    dir.getValue(x,y,z);

    std::vector<Part::Feature*> shapes = Gui::Selection().getObjectsOfType<Part::Feature>();
    Gui::Command::openCommand("Project shape");
    Gui::Command::addModule(Gui::Command::Doc,"Drawing");
    for (std::vector<Part::Feature*>::iterator it = shapes.begin(); it != shapes.end(); ++it) {
        const char* object = (*it)->getNameInDocument();
        Gui::Command::doCommand(Gui::Command::Doc,
            "FreeCAD.ActiveDocument.addObject('Drawing::FeatureProjection','%s_proj')", object);
        Gui::Command::doCommand(Gui::Command::Doc,
            "FreeCAD.ActiveDocument.ActiveObject.Direction=FreeCAD.Vector(%f,%f,%f)", x,y,z);
        Gui::Command::doCommand(Gui::Command::Doc,
            "FreeCAD.ActiveDocument.ActiveObject.Source=FreeCAD.ActiveDocument.%s", object);
        Gui::Command::doCommand(Gui::Command::Doc,
            "FreeCAD.ActiveDocument.ActiveObject.VCompound=%s", (boxes[0]->isChecked() ? "True" : "False"));
        Gui::Command::doCommand(Gui::Command::Doc,
            "FreeCAD.ActiveDocument.ActiveObject.Rg1LineVCompound=%s", (boxes[1]->isChecked() ? "True" : "False"));
        Gui::Command::doCommand(Gui::Command::Doc,
            "FreeCAD.ActiveDocument.ActiveObject.RgNLineVCompound=%s", (boxes[2]->isChecked() ? "True" : "False"));
        Gui::Command::doCommand(Gui::Command::Doc,
            "FreeCAD.ActiveDocument.ActiveObject.OutLineVCompound=%s", (boxes[3]->isChecked() ? "True" : "False"));
        Gui::Command::doCommand(Gui::Command::Doc,
            "FreeCAD.ActiveDocument.ActiveObject.IsoLineVCompound=%s", (boxes[4]->isChecked() ? "True" : "False"));
        Gui::Command::doCommand(Gui::Command::Doc,
            "FreeCAD.ActiveDocument.ActiveObject.HCompound=%s", (boxes[5]->isChecked() ? "True" : "False"));
        Gui::Command::doCommand(Gui::Command::Doc,
            "FreeCAD.ActiveDocument.ActiveObject.Rg1LineHCompound=%s", (boxes[6]->isChecked() ? "True" : "False"));
        Gui::Command::doCommand(Gui::Command::Doc,
            "FreeCAD.ActiveDocument.ActiveObject.RgNLineHCompound=%s", (boxes[7]->isChecked() ? "True" : "False"));
        Gui::Command::doCommand(Gui::Command::Doc,
            "FreeCAD.ActiveDocument.ActiveObject.OutLineHCompound=%s", (boxes[8]->isChecked() ? "True" : "False"));
        Gui::Command::doCommand(Gui::Command::Doc,
            "FreeCAD.ActiveDocument.ActiveObject.IsoLineHCompound=%s", (boxes[9]->isChecked() ? "True" : "False"));
    }
    Gui::Command::updateActive();
    Gui::Command::commitCommand();
    return true;
}

#include "moc_TaskDialog.cpp"
<|endoftext|>


<commit_before>#include <vector>
#include <algorithm>
#include <iterator>

#include <catch.hpp>
#include <sliding_window_buffer.hpp>

typedef helene::sliding_window_buffer<int, 4> swb_type;

TEST_CASE("default construct a sliding_window_buffer",
          "[sliding_window_buffer]")
{
    swb_type swb;

    CHECK(swb.size() == 4);

    SECTION("push back four values")
    {
        swb.push_back(1);
        swb.push_back(2);
        swb.push_back(3);
        swb.push_back(4);

        CHECK(swb[0] == 1);
        CHECK(swb[1] == 2);
        CHECK(swb[2] == 3);
        CHECK(swb[3] == 4);

        CHECK(swb.front() == 1);
        CHECK(swb.back() == 4);

        SECTION("push back another value")
        {
            swb.push_back(5);

            CHECK(swb[0] == 2);
            CHECK(swb[1] == 3);
            CHECK(swb[2] == 4);
            CHECK(swb[3] == 5);

            CHECK(swb.front() == 2);
            CHECK(swb.back() == 5);
        }

        SECTION("push front a value")
        {
            swb.push_front(10);

            CHECK(swb[0] == 10);
            CHECK(swb[1] == 1);
            CHECK(swb[2] == 2);
            CHECK(swb[3] == 3);

            CHECK(swb.front() == 10);
            CHECK(swb.back() == 3);

            SECTION("copy full range into vector")
            {
                std::vector<int> res;

                std::copy(swb.begin(), swb.end(), std::back_inserter(res));

                CHECK(res.size() == 4);
                CHECK(res[0] == 10);
                CHECK(res[1] == 1);
                CHECK(res[2] == 2);
                CHECK(res[3] == 3);
            }
        }

        SECTION("copy full range into vector")
        {
            std::vector<int> res;

            std::copy(swb.begin(), swb.end(), std::back_inserter(res));

            CHECK(res.size() == 4);
            CHECK(res[0] == 1);
            CHECK(res[1] == 2);
            CHECK(res[2] == 3);
            CHECK(res[3] == 4);
        }

        SECTION("access values through const_iterators")
        {
            auto cb = swb.cbegin();
            auto ce = swb.cend();
        }
    }
}

TEST_CASE("construct sliding_window_buffer with range",
          "[sliding_window_buffer]")
{
    std::vector<int> vals{1, 2, 3, 4};

    swb_type swb(vals.begin(), vals.end());

    CHECK(swb[0] == 1);
    CHECK(swb[1] == 2);
    CHECK(swb[2] == 3);
    CHECK(swb[3] == 4);

    SECTION("push back another value")
    {
        swb.push_back(5);

        CHECK(swb[0] == 2);
        CHECK(swb[1] == 3);
        CHECK(swb[2] == 4);
        CHECK(swb[3] == 5);

        CHECK(swb.front() == 2);
        CHECK(swb.back() == 5);
    }

    SECTION("push front a value")
    {
        swb.push_front(10);

        CHECK(swb[0] == 10);
        CHECK(swb[1] == 1);
        CHECK(swb[2] == 2);
        CHECK(swb[3] == 3);

        CHECK(swb.front() == 10);
        CHECK(swb.back() == 3);

        SECTION("copy full range into vector")
        {
            std::vector<int> res;

            std::copy(swb.begin(), swb.end(), std::back_inserter(res));

            CHECK(res.size() == 4);
            CHECK(res[0] == 10);
            CHECK(res[1] == 1);
            CHECK(res[2] == 2);
            CHECK(res[3] == 3);
        }
    }

    SECTION("copy full range into vector")
    {
        std::vector<int> res;

        std::copy(swb.begin(), swb.end(), std::back_inserter(res));

        CHECK(res.size() == 4);
        CHECK(res[0] == 1);
        CHECK(res[1] == 2);
        CHECK(res[2] == 3);
        CHECK(res[3] == 4);
    }
}
<commit_msg>Add unit tests. 	modified:   tests/test_sliding_window_buffer.cpp<commit_after>#include <vector>
#include <algorithm>
#include <iterator>

#include <catch.hpp>
#include <sliding_window_buffer.hpp>

typedef helene::sliding_window_buffer<int, 4> swb_type;

TEST_CASE("default construct a sliding_window_buffer",
          "[sliding_window_buffer]")
{
    swb_type swb;

    CHECK(swb.size() == 4);

    SECTION("push back four values")
    {
        swb.push_back(1);
        swb.push_back(2);
        swb.push_back(3);
        swb.push_back(4);

        CHECK(swb[0] == 1);
        CHECK(swb[1] == 2);
        CHECK(swb[2] == 3);
        CHECK(swb[3] == 4);

        CHECK(swb.front() == 1);
        CHECK(swb.back() == 4);

        SECTION("push back another value")
        {
            swb.push_back(5);

            CHECK(swb[0] == 2);
            CHECK(swb[1] == 3);
            CHECK(swb[2] == 4);
            CHECK(swb[3] == 5);

            CHECK(swb.front() == 2);
            CHECK(swb.back() == 5);
        }

        SECTION("push front a value")
        {
            swb.push_front(10);

            CHECK(swb[0] == 10);
            CHECK(swb[1] == 1);
            CHECK(swb[2] == 2);
            CHECK(swb[3] == 3);

            CHECK(swb.front() == 10);
            CHECK(swb.back() == 3);

            SECTION("copy full range into vector")
            {
                std::vector<int> res;

                std::copy(swb.begin(), swb.end(), std::back_inserter(res));

                CHECK(res.size() == 4);
                CHECK(res[0] == 10);
                CHECK(res[1] == 1);
                CHECK(res[2] == 2);
                CHECK(res[3] == 3);
            }
        }

        SECTION("copy full range into vector")
        {
            std::vector<int> res;

            std::copy(swb.begin(), swb.end(), std::back_inserter(res));

            CHECK(res.size() == 4);
            CHECK(res[0] == 1);
            CHECK(res[1] == 2);
            CHECK(res[2] == 3);
            CHECK(res[3] == 4);
        }

        SECTION("access values through const_iterators")
        {
            auto cb = swb.cbegin();
            auto ce = swb.cend();

            CHECK(*cb == 1);
            CHECK(cb[1] == 2);
            CHECK(cb[2] == 3);
            CHECK(cb[3] == 4);
            CHECK(cb + 4 == ce);
        }
    }
}

TEST_CASE("construct sliding_window_buffer with range",
          "[sliding_window_buffer]")
{
    std::vector<int> vals{1, 2, 3, 4};

    swb_type swb(vals.begin(), vals.end());

    CHECK(swb[0] == 1);
    CHECK(swb[1] == 2);
    CHECK(swb[2] == 3);
    CHECK(swb[3] == 4);

    SECTION("push back another value")
    {
        swb.push_back(5);

        CHECK(swb[0] == 2);
        CHECK(swb[1] == 3);
        CHECK(swb[2] == 4);
        CHECK(swb[3] == 5);

        CHECK(swb.front() == 2);
        CHECK(swb.back() == 5);
    }

    SECTION("push front a value")
    {
        swb.push_front(10);

        CHECK(swb[0] == 10);
        CHECK(swb[1] == 1);
        CHECK(swb[2] == 2);
        CHECK(swb[3] == 3);

        CHECK(swb.front() == 10);
        CHECK(swb.back() == 3);

        SECTION("copy full range into vector")
        {
            std::vector<int> res;

            std::copy(swb.begin(), swb.end(), std::back_inserter(res));

            CHECK(res.size() == 4);
            CHECK(res[0] == 10);
            CHECK(res[1] == 1);
            CHECK(res[2] == 2);
            CHECK(res[3] == 3);
        }
    }

    SECTION("copy full range into vector")
    {
        std::vector<int> res;

        std::copy(swb.begin(), swb.end(), std::back_inserter(res));

        CHECK(res.size() == 4);
        CHECK(res[0] == 1);
        CHECK(res[1] == 2);
        CHECK(res[2] == 3);
        CHECK(res[3] == 4);
    }
}
<|endoftext|>


<commit_before>// mail-qman - deliver mail messages from the queue

// The spool directory has the following structure:
// * pid/<pid> - message files under construction
// * mess/<inumber> - message files
// * todo/<message inumber> - envelope files
// * notify - a UNIX socket that receives an <inumber> when a message
//   is added to the spool

#include "libutil.h"
#include "shutil.h"

#include <fcntl.h>
#include <spawn.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <sys/wait.h>

#include <string>
#include <thread>

using std::string;
using std::thread;

class spool_reader
{
  string spooldir_;
  int notifyfd_;

public:
  spool_reader(const string &spooldir) : spooldir_(spooldir)
  {
    // Create notification socket
    // XXX Commutativity: Unordered
    notifyfd_ = socket(AF_UNIX, SOCK_DGRAM, 0);
    if (notifyfd_ < 0)
      edie("socket failed");
    struct sockaddr_un sun{};
    sun.sun_family = AF_UNIX;
    snprintf(sun.sun_path, sizeof sun.sun_path, "%s/notify", spooldir.c_str());
    unlink(sun.sun_path);
    if (bind(notifyfd_, (struct sockaddr*)&sun, SUN_LEN(&sun)) < 0)
      edie("bind failed");
  }

  string dequeue()
  {
    char buf[256];
    ssize_t r = recv(notifyfd_, buf, sizeof buf, 0);
    if (r < 0)
      edie("recv failed");
    return {buf, (size_t)r};
  }

  string get_recipient(const string &id)
  {
    char path[256];
    snprintf(path, sizeof path, "%s/todo/%s", spooldir_.c_str(), id.c_str());
    // XXX Commutativity: O_ANYFD
    int fd = open(path, O_RDONLY|O_CLOEXEC);
    if (fd < 0)
      edie("open %s failed", path);
    struct stat st;
    // XXX Commutativity: STAT_OMIT_NLINK
    if (fstat(fd, &st) < 0)
      edie("fstat %s failed", path);
    string res(st.st_size, 0);
    if (readall(fd, &res.front(), res.size()) != res.size())
      edie("readall %s failed", path);
    close(fd);
    return res;
  }

  int open_message(const string &id)
  {
    char path[256];
    snprintf(path, sizeof path, "%s/mess/%s", spooldir_.c_str(), id.c_str());
    // XXX Commutativity: O_ANYFD
    int fd = open(path, O_RDONLY|O_CLOEXEC);
    if (fd < 0)
      edie("open %s failed", path);
    return fd;
  }

  void remove(const string &id)
  {
    string x;
    x.append(spooldir_).append("/todo/").append(id);
    unlink(x.c_str());
    x.clear();
    x.append(spooldir_).append("/mess/").append(id);
    unlink(x.c_str());
  }
};

static void
deliver(const char *mailroot, int msgfd, const string &recipient)
{
  const char *argv[] = {"./mail-deliver", mailroot, recipient.c_str(), nullptr};

  // XXX Commutativity: fork/exec vs posix_spawn
  pid_t pid;
  posix_spawn_file_actions_t actions;
  if ((errno = posix_spawn_file_actions_init(&actions)))
    edie("posix_spawn_file_actions_init failed");
  if ((errno = posix_spawn_file_actions_adddup2(&actions, msgfd, 0)))
    edie("posix_spawn_file_actions_adddup2 failed");
  if ((errno = posix_spawn(&pid, argv[0], &actions, nullptr,
                           const_cast<char *const*>(argv), environ)))
    edie("posix_spawn failed");
  if ((errno = posix_spawn_file_actions_destroy(&actions)))
    edie("posix_spawn_file_actions_destroy failed");

  int status;
  if (waitpid(pid, &status, 0) < 0)
    edie("waitpid failed");
  if (!WIFEXITED(status) || WEXITSTATUS(status))
    die("deliver failed: status %d", status);
}

static void
do_process(spool_reader *spool, const char *mailroot)
{
  while (true) {
    string id = spool->dequeue();
    string recip = spool->get_recipient(id);
    int msgfd = spool->open_message(id);
    deliver(mailroot, msgfd, recip);
    spool->remove(id);
  }
}

static void
usage(const char *argv0)
{
  fprintf(stderr, "Usage: %s spooldir mailroot nthread\n", argv0);
  exit(2);
}

int
main(int argc, char **argv)
{
  if (argc != 4)
    usage(argv[0]);

  const char *spooldir = argv[1];
  const char *mailroot = argv[2];
  int nthread = atoi(argv[3]);
  if (nthread <= 0)
    usage(argv[0]);

  spool_reader reader{spooldir};

  thread *threads = new thread[nthread];

  for (int i = 0; i < nthread; ++i) {
    setaffinity(i);
    threads[i] = std::move(thread(do_process, &reader, mailroot));
  }

  for (int i = 0; i < nthread; ++i)
    threads[i].join();
}
<commit_msg>mail-qman: Support fork/exec as alternate to posix_spawn<commit_after>// mail-qman - deliver mail messages from the queue

// The spool directory has the following structure:
// * pid/<pid> - message files under construction
// * mess/<inumber> - message files
// * todo/<message inumber> - envelope files
// * notify - a UNIX socket that receives an <inumber> when a message
//   is added to the spool

#define HAVE_POSIX_SPAWN 0

#include "libutil.h"
#include "shutil.h"
#include "xsys.h"

#include <fcntl.h>
#if HAVE_POSIX_SPAWN
#include <spawn.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <sys/wait.h>

#include <string>
#include <thread>

using std::string;
using std::thread;

class spool_reader
{
  string spooldir_;
  int notifyfd_;

public:
  spool_reader(const string &spooldir) : spooldir_(spooldir)
  {
    // Create notification socket
    // XXX Commutativity: Unordered
    notifyfd_ = socket(AF_UNIX, SOCK_DGRAM, 0);
    if (notifyfd_ < 0)
      edie("socket failed");
    struct sockaddr_un sun{};
    sun.sun_family = AF_UNIX;
    snprintf(sun.sun_path, sizeof sun.sun_path, "%s/notify", spooldir.c_str());
    unlink(sun.sun_path);
    if (bind(notifyfd_, (struct sockaddr*)&sun, SUN_LEN(&sun)) < 0)
      edie("bind failed");
  }

  string dequeue()
  {
    char buf[256];
    ssize_t r = recv(notifyfd_, buf, sizeof buf, 0);
    if (r < 0)
      edie("recv failed");
    return {buf, (size_t)r};
  }

  string get_recipient(const string &id)
  {
    char path[256];
    snprintf(path, sizeof path, "%s/todo/%s", spooldir_.c_str(), id.c_str());
    // XXX Commutativity: O_ANYFD
    int fd = open(path, O_RDONLY|O_CLOEXEC);
    if (fd < 0)
      edie("open %s failed", path);
    struct stat st;
    // XXX Commutativity: STAT_OMIT_NLINK
    if (fstat(fd, &st) < 0)
      edie("fstat %s failed", path);
    string res(st.st_size, 0);
    if (readall(fd, &res.front(), res.size()) != res.size())
      edie("readall %s failed", path);
    close(fd);
    return res;
  }

  int open_message(const string &id)
  {
    char path[256];
    snprintf(path, sizeof path, "%s/mess/%s", spooldir_.c_str(), id.c_str());
    // XXX Commutativity: O_ANYFD
    int fd = open(path, O_RDONLY|O_CLOEXEC);
    if (fd < 0)
      edie("open %s failed", path);
    return fd;
  }

  void remove(const string &id)
  {
    string x;
    x.append(spooldir_).append("/todo/").append(id);
    unlink(x.c_str());
    x.clear();
    x.append(spooldir_).append("/mess/").append(id);
    unlink(x.c_str());
  }
};

static void
deliver(const char *mailroot, int msgfd, const string &recipient)
{
  const char *argv[] = {"./mail-deliver", mailroot, recipient.c_str(), nullptr};

  // XXX Commutativity: fork/exec vs posix_spawn
  pid_t pid;
#if HAVE_POSIX_SPAWN
  posix_spawn_file_actions_t actions;
  if ((errno = posix_spawn_file_actions_init(&actions)))
    edie("posix_spawn_file_actions_init failed");
  if ((errno = posix_spawn_file_actions_adddup2(&actions, msgfd, 0)))
    edie("posix_spawn_file_actions_adddup2 failed");
  if ((errno = posix_spawn(&pid, argv[0], &actions, nullptr,
                           const_cast<char *const*>(argv), environ)))
    edie("posix_spawn failed");
  if ((errno = posix_spawn_file_actions_destroy(&actions)))
    edie("posix_spawn_file_actions_destroy failed");
#else
  pid = xfork();
  if (pid < 0)
    edie("fork failed");
  if (pid == 0) {
    dup2(msgfd, 0);
    execv(argv[0], const_cast<char *const*>(argv));
    edie("execv %s failed", argv[0]);
  }
#endif

  int status;
  if (waitpid(pid, &status, 0) < 0)
    edie("waitpid failed");
  if (!WIFEXITED(status) || WEXITSTATUS(status))
    die("deliver failed: status %d", status);
}

static void
do_process(spool_reader *spool, const char *mailroot)
{
  while (true) {
    string id = spool->dequeue();
    string recip = spool->get_recipient(id);
    int msgfd = spool->open_message(id);
    deliver(mailroot, msgfd, recip);
    spool->remove(id);
  }
}

static void
usage(const char *argv0)
{
  fprintf(stderr, "Usage: %s spooldir mailroot nthread\n", argv0);
  exit(2);
}

int
main(int argc, char **argv)
{
  if (argc != 4)
    usage(argv[0]);

  const char *spooldir = argv[1];
  const char *mailroot = argv[2];
  int nthread = atoi(argv[3]);
  if (nthread <= 0)
    usage(argv[0]);

  spool_reader reader{spooldir};

  thread *threads = new thread[nthread];

  for (int i = 0; i < nthread; ++i) {
    setaffinity(i);
    threads[i] = std::move(thread(do_process, &reader, mailroot));
  }

  for (int i = 0; i < nthread; ++i)
    threads[i].join();
}
<|endoftext|>


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

#include "chrome/browser/policy/configuration_policy_store_interface.h"

namespace {

using namespace policy;

bool IsProxyPolicy(ConfigurationPolicyType policy) {
  return policy == kPolicyProxyMode ||
         policy == kPolicyProxyServerMode ||
         policy == kPolicyProxyServer ||
         policy == kPolicyProxyPacUrl ||
         policy == kPolicyProxyBypassList;
}

} // namespace

namespace policy {

void ObservingPolicyStoreInterface::Apply(ConfigurationPolicyType policy,
                                          Value* value) {
  next_->Apply(policy, value);

  if (IsProxyPolicy(policy))
      proxy_policy_applied_ = true;
}

void FilteringPolicyStoreInterface::Apply(ConfigurationPolicyType policy,
                                          Value* value) {
  if (IsProxyPolicy(policy) && apply_proxy_policies_)
    next_->Apply(policy, value);
}

} // namespace policy
<commit_msg>Plugged memory leak in FilteringPolicyStoreInterface::Apply.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/policy/configuration_policy_store_interface.h"

namespace {

using namespace policy;

bool IsProxyPolicy(ConfigurationPolicyType policy) {
  return policy == kPolicyProxyMode ||
         policy == kPolicyProxyServerMode ||
         policy == kPolicyProxyServer ||
         policy == kPolicyProxyPacUrl ||
         policy == kPolicyProxyBypassList;
}

} // namespace

namespace policy {

void ObservingPolicyStoreInterface::Apply(ConfigurationPolicyType policy,
                                          Value* value) {
  next_->Apply(policy, value);

  if (IsProxyPolicy(policy))
      proxy_policy_applied_ = true;
}

void FilteringPolicyStoreInterface::Apply(ConfigurationPolicyType policy,
                                          Value* value) {
  // Apply() takes ownership of |value|.
  if (IsProxyPolicy(policy) && apply_proxy_policies_)
    next_->Apply(policy, value);
  else
    delete value;
}

} // namespace policy
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: FillProperties.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-22 18:58:47 $
 *
 *  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_chart2.hxx"
#include "FillProperties.hxx"
#include "macros.hxx"

#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_BITMAPMODE_HPP_
#include <com/sun/star/drawing/BitmapMode.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_FILLSTYLE_HPP_
#include <com/sun/star/drawing/FillStyle.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_RECTANGLEPOINT_HPP_
#include <com/sun/star/drawing/RectanglePoint.hpp>
#endif

using namespace ::com::sun::star;

using ::com::sun::star::beans::Property;

namespace chart
{

namespace
{

void lcl_AddPropertiesToVector_without_BitmapProperties( ::std::vector< ::com::sun::star::beans::Property > & rOutProperties )
{
    rOutProperties.push_back(
        Property( C2U( "FillStyle" ),
                  FillProperties::PROP_FILL_STYLE,
                  ::getCppuType( reinterpret_cast< const drawing::FillStyle * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "FillColor" ),
                  FillProperties::PROP_FILL_COLOR,
                  ::getCppuType( reinterpret_cast< const sal_Int32 * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEVOID         // "maybe auto"
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "FillTransparence" ),
                  FillProperties::PROP_FILL_TRANSPARENCE,
                  ::getCppuType( reinterpret_cast< const sal_Int16 * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "FillTransparenceGradientName" ),
                  FillProperties::PROP_FILL_TRANSPARENCE_GRADIENT_NAME,
                  ::getCppuType( reinterpret_cast< const ::rtl::OUString * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    //optional
//    rOutProperties.push_back(
//        Property( C2U( "FillTransparenceGradient" ),
//                  FillProperties::PROP_FILL_TRANSPARENCE_GRADIENT,
//                  ::getCppuType( reinterpret_cast< const awt::Gradient * >(0)),
//                  beans::PropertyAttribute::BOUND
//                  | beans::PropertyAttribute::MAYBEDEFAULT
//                  | beans::PropertyAttribute::MAYBEVOID ));

    rOutProperties.push_back(
        Property( C2U( "FillGradientName" ),
                  FillProperties::PROP_FILL_GRADIENT_NAME,
                  ::getCppuType( reinterpret_cast< const ::rtl::OUString * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        beans::Property( C2U( "FillGradientStepCount" ),
                  FillProperties::PROP_FILL_GRADIENT_STEPCOUNT,
                  ::getCppuType( reinterpret_cast< const sal_Int16 * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    //optional
//    rOutProperties.push_back(
//        Property( C2U( "FillGradient" ),
//                  FillProperties::PROP_FILL_GRADIENT,
//                  ::getCppuType( reinterpret_cast< const awt::Gradient * >(0)),
//                  beans::PropertyAttribute::BOUND
//                  | beans::PropertyAttribute::MAYBEDEFAULT
//                  | beans::PropertyAttribute::MAYBEVOID ));

    rOutProperties.push_back(
        Property( C2U( "FillHatchName" ),
                  FillProperties::PROP_FILL_HATCH_NAME,
                  ::getCppuType( reinterpret_cast< const ::rtl::OUString * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    //optional
//    rOutProperties.push_back(
//        Property( C2U( "FillHatch" ),
//                  FillProperties::PROP_FILL_HATCH,
//                  ::getCppuType( reinterpret_cast< const drawing::Hatch * >(0)),
//                  beans::PropertyAttribute::BOUND
//                  | beans::PropertyAttribute::MAYBEDEFAULT
//                  | beans::PropertyAttribute::MAYBEVOID ));

    //bitmap properties see lcl_AddPropertiesToVector_only_BitmapProperties()

    rOutProperties.push_back(
        Property( C2U( "FillBackground" ),
                  FillProperties::PROP_FILL_BACKGROUND,
                  ::getCppuType( reinterpret_cast< const sal_Bool * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));
}

//static
void lcl_AddPropertiesToVector_only_BitmapProperties( ::std::vector< ::com::sun::star::beans::Property > & rOutProperties )
{
    rOutProperties.push_back(
        Property( C2U( "FillBitmapName" ),
                  FillProperties::PROP_FILL_BITMAP_NAME,
                  ::getCppuType( reinterpret_cast< const ::rtl::OUString * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    //optional
//    rOutProperties.push_back(
//        Property( C2U( "FillBitmap" ),
//                  FillProperties::PROP_FILL_BITMAP,
//                  ::getCppuType( reinterpret_cast< const uno::Reference< awt::XBitmap > * >(0)),
//                  beans::PropertyAttribute::BOUND
//                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    //optional
//    rOutProperties.push_back(
//        Property( C2U( "FillBitmapURL" ),
//                  FillProperties::PROP_FILL_BITMAP_URL,
//                  ::getCppuType( reinterpret_cast< const ::rtl::OUString * >(0)),
//                  beans::PropertyAttribute::BOUND
//                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "FillBitmapOffsetX" ),
                  FillProperties::PROP_FILL_BITMAP_OFFSETX,
                  ::getCppuType( reinterpret_cast< const sal_Int16 * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "FillBitmapOffsetY" ),
                  FillProperties::PROP_FILL_BITMAP_OFFSETY,
                  ::getCppuType( reinterpret_cast< const sal_Int16 * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "FillBitmapPositionOffsetX" ),
                  FillProperties::PROP_FILL_BITMAP_POSITION_OFFSETX,
                  ::getCppuType( reinterpret_cast< const sal_Int16 * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "FillBitmapPositionOffsetY" ),
                  FillProperties::PROP_FILL_BITMAP_POSITION_OFFSETY,
                  ::getCppuType( reinterpret_cast< const sal_Int16 * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "FillBitmapRectanglePoint" ),
                  FillProperties::PROP_FILL_BITMAP_RECTANGLEPOINT,
                  ::getCppuType( reinterpret_cast< const drawing::RectanglePoint * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "FillBitmapLogicalSize" ),
                  FillProperties::PROP_FILL_BITMAP_LOGICALSIZE,
                  ::getCppuType( reinterpret_cast< const sal_Bool * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "FillBitmapSizeX" ),
                  FillProperties::PROP_FILL_BITMAP_SIZEX,
                  ::getCppuType( reinterpret_cast< const sal_Int32 * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "FillBitmapSizeY" ),
                  FillProperties::PROP_FILL_BITMAP_SIZEY,
                  ::getCppuType( reinterpret_cast< const sal_Int32 * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "FillBitmapMode" ),
                  FillProperties::PROP_FILL_BITMAP_MODE,
                  ::getCppuType( reinterpret_cast< const drawing::BitmapMode * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));
}

void lcl_AddDefaultsToMap_without_BitmapProperties(
    ::chart::tPropertyValueMap & rOutMap )
{
    OSL_ASSERT( rOutMap.end() == rOutMap.find( FillProperties::PROP_FILL_STYLE ));
    rOutMap[ FillProperties::PROP_FILL_STYLE ] =
        uno::makeAny( drawing::FillStyle_SOLID );
    OSL_ASSERT( rOutMap.end() == rOutMap.find( FillProperties::PROP_FILL_COLOR ));
    rOutMap[ FillProperties::PROP_FILL_COLOR ] =
        uno::makeAny( sal_Int32( 0xd9d9d9 ) ); // gray85
    OSL_ASSERT( rOutMap.end() == rOutMap.find( FillProperties::PROP_FILL_TRANSPARENCE ));
    rOutMap[ FillProperties::PROP_FILL_TRANSPARENCE ] =
        uno::makeAny( sal_Int16( 0 ) );
    OSL_ASSERT( rOutMap.end() == rOutMap.find( FillProperties::PROP_FILL_GRADIENT_STEPCOUNT ));
    rOutMap[ FillProperties::PROP_FILL_GRADIENT_STEPCOUNT ] =
        uno::makeAny( sal_Int16( 0 ) );
    OSL_ASSERT( rOutMap.end() == rOutMap.find( FillProperties::PROP_FILL_BACKGROUND ));
    rOutMap[ FillProperties::PROP_FILL_BACKGROUND ] =
        uno::makeAny( sal_Bool( sal_False ) );
}

void lcl_AddDefaultsToMap_only_BitmapProperties(
    ::chart::tPropertyValueMap & rOutMap )
{
    uno::Any aSalInt16Zero = uno::makeAny( sal_Int16( 0 ));
    uno::Any aSalInt32SizeDefault = uno::makeAny( sal_Int32( 0 ));

    OSL_ASSERT( rOutMap.end() == rOutMap.find( FillProperties::PROP_FILL_BITMAP_OFFSETX ));
    rOutMap[ FillProperties::PROP_FILL_BITMAP_OFFSETX ] = aSalInt16Zero;
    OSL_ASSERT( rOutMap.end() == rOutMap.find( FillProperties::PROP_FILL_BITMAP_OFFSETY ));
    rOutMap[ FillProperties::PROP_FILL_BITMAP_OFFSETY ] = aSalInt16Zero;
    OSL_ASSERT( rOutMap.end() == rOutMap.find( FillProperties::PROP_FILL_BITMAP_POSITION_OFFSETX ));
    rOutMap[ FillProperties::PROP_FILL_BITMAP_POSITION_OFFSETX ] = aSalInt16Zero;
    OSL_ASSERT( rOutMap.end() == rOutMap.find( FillProperties::PROP_FILL_BITMAP_POSITION_OFFSETY ));
    rOutMap[ FillProperties::PROP_FILL_BITMAP_POSITION_OFFSETY ] = aSalInt16Zero;
    OSL_ASSERT( rOutMap.end() == rOutMap.find( FillProperties::PROP_FILL_BITMAP_RECTANGLEPOINT ));
    rOutMap[ FillProperties::PROP_FILL_BITMAP_RECTANGLEPOINT ] =
        uno::makeAny( drawing::RectanglePoint_MIDDLE_MIDDLE );
    OSL_ASSERT( rOutMap.end() == rOutMap.find( FillProperties::PROP_FILL_BITMAP_LOGICALSIZE ));
    rOutMap[ FillProperties::PROP_FILL_BITMAP_LOGICALSIZE ] =
        uno::makeAny( true );
    OSL_ASSERT( rOutMap.end() == rOutMap.find( FillProperties::PROP_FILL_BITMAP_SIZEX ));
    rOutMap[ FillProperties::PROP_FILL_BITMAP_SIZEX ] = aSalInt32SizeDefault;
    OSL_ASSERT( rOutMap.end() == rOutMap.find( FillProperties::PROP_FILL_BITMAP_SIZEY ));
    rOutMap[ FillProperties::PROP_FILL_BITMAP_SIZEY ] = aSalInt32SizeDefault;
    OSL_ASSERT( rOutMap.end() == rOutMap.find( FillProperties::PROP_FILL_BITMAP_MODE ));
    rOutMap[ FillProperties::PROP_FILL_BITMAP_MODE ] =
        uno::makeAny( drawing::BitmapMode_REPEAT );
}

}//end anonymous namespace

void FillProperties::AddPropertiesToVector(
    ::std::vector< Property > & rOutProperties )
{
    // Fill Properties see service drawing::FillProperties
    // ---------------
    lcl_AddPropertiesToVector_without_BitmapProperties( rOutProperties );
    lcl_AddPropertiesToVector_only_BitmapProperties( rOutProperties );
}

void FillProperties::AddDefaultsToMap(
    ::chart::tPropertyValueMap & rOutMap )
{
    lcl_AddDefaultsToMap_without_BitmapProperties( rOutMap );
    lcl_AddDefaultsToMap_only_BitmapProperties( rOutMap );
}

} //  namespace chart
<commit_msg>INTEGRATION: CWS chart07 (1.5.12); FILE MERGED 2007/07/09 07:27:22 bm 1.5.12.1: #i79087# FillxxxName is void per default so add MAYBEVOID<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: FillProperties.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2007-07-25 08:57:12 $
 *
 *  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_chart2.hxx"
#include "FillProperties.hxx"
#include "macros.hxx"

#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_BITMAPMODE_HPP_
#include <com/sun/star/drawing/BitmapMode.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_FILLSTYLE_HPP_
#include <com/sun/star/drawing/FillStyle.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_RECTANGLEPOINT_HPP_
#include <com/sun/star/drawing/RectanglePoint.hpp>
#endif

using namespace ::com::sun::star;

using ::com::sun::star::beans::Property;

namespace chart
{

namespace
{

void lcl_AddPropertiesToVector_without_BitmapProperties( ::std::vector< ::com::sun::star::beans::Property > & rOutProperties )
{
    rOutProperties.push_back(
        Property( C2U( "FillStyle" ),
                  FillProperties::PROP_FILL_STYLE,
                  ::getCppuType( reinterpret_cast< const drawing::FillStyle * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "FillColor" ),
                  FillProperties::PROP_FILL_COLOR,
                  ::getCppuType( reinterpret_cast< const sal_Int32 * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEVOID         // "maybe auto"
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "FillTransparence" ),
                  FillProperties::PROP_FILL_TRANSPARENCE,
                  ::getCppuType( reinterpret_cast< const sal_Int16 * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "FillTransparenceGradientName" ),
                  FillProperties::PROP_FILL_TRANSPARENCE_GRADIENT_NAME,
                  ::getCppuType( reinterpret_cast< const ::rtl::OUString * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEVOID
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    //optional
//    rOutProperties.push_back(
//        Property( C2U( "FillTransparenceGradient" ),
//                  FillProperties::PROP_FILL_TRANSPARENCE_GRADIENT,
//                  ::getCppuType( reinterpret_cast< const awt::Gradient * >(0)),
//                  beans::PropertyAttribute::BOUND
//                  | beans::PropertyAttribute::MAYBEDEFAULT
//                  | beans::PropertyAttribute::MAYBEVOID ));

    rOutProperties.push_back(
        Property( C2U( "FillGradientName" ),
                  FillProperties::PROP_FILL_GRADIENT_NAME,
                  ::getCppuType( reinterpret_cast< const ::rtl::OUString * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEVOID
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        beans::Property( C2U( "FillGradientStepCount" ),
                  FillProperties::PROP_FILL_GRADIENT_STEPCOUNT,
                  ::getCppuType( reinterpret_cast< const sal_Int16 * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    //optional
//    rOutProperties.push_back(
//        Property( C2U( "FillGradient" ),
//                  FillProperties::PROP_FILL_GRADIENT,
//                  ::getCppuType( reinterpret_cast< const awt::Gradient * >(0)),
//                  beans::PropertyAttribute::BOUND
//                  | beans::PropertyAttribute::MAYBEDEFAULT
//                  | beans::PropertyAttribute::MAYBEVOID ));

    rOutProperties.push_back(
        Property( C2U( "FillHatchName" ),
                  FillProperties::PROP_FILL_HATCH_NAME,
                  ::getCppuType( reinterpret_cast< const ::rtl::OUString * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEVOID
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    //optional
//    rOutProperties.push_back(
//        Property( C2U( "FillHatch" ),
//                  FillProperties::PROP_FILL_HATCH,
//                  ::getCppuType( reinterpret_cast< const drawing::Hatch * >(0)),
//                  beans::PropertyAttribute::BOUND
//                  | beans::PropertyAttribute::MAYBEDEFAULT
//                  | beans::PropertyAttribute::MAYBEVOID ));

    //bitmap properties see lcl_AddPropertiesToVector_only_BitmapProperties()

    rOutProperties.push_back(
        Property( C2U( "FillBackground" ),
                  FillProperties::PROP_FILL_BACKGROUND,
                  ::getCppuType( reinterpret_cast< const sal_Bool * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));
}

//static
void lcl_AddPropertiesToVector_only_BitmapProperties( ::std::vector< ::com::sun::star::beans::Property > & rOutProperties )
{
    rOutProperties.push_back(
        Property( C2U( "FillBitmapName" ),
                  FillProperties::PROP_FILL_BITMAP_NAME,
                  ::getCppuType( reinterpret_cast< const ::rtl::OUString * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEVOID
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    //optional
//    rOutProperties.push_back(
//        Property( C2U( "FillBitmap" ),
//                  FillProperties::PROP_FILL_BITMAP,
//                  ::getCppuType( reinterpret_cast< const uno::Reference< awt::XBitmap > * >(0)),
//                  beans::PropertyAttribute::BOUND
//                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    //optional
//    rOutProperties.push_back(
//        Property( C2U( "FillBitmapURL" ),
//                  FillProperties::PROP_FILL_BITMAP_URL,
//                  ::getCppuType( reinterpret_cast< const ::rtl::OUString * >(0)),
//                  beans::PropertyAttribute::BOUND
//                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "FillBitmapOffsetX" ),
                  FillProperties::PROP_FILL_BITMAP_OFFSETX,
                  ::getCppuType( reinterpret_cast< const sal_Int16 * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "FillBitmapOffsetY" ),
                  FillProperties::PROP_FILL_BITMAP_OFFSETY,
                  ::getCppuType( reinterpret_cast< const sal_Int16 * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "FillBitmapPositionOffsetX" ),
                  FillProperties::PROP_FILL_BITMAP_POSITION_OFFSETX,
                  ::getCppuType( reinterpret_cast< const sal_Int16 * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "FillBitmapPositionOffsetY" ),
                  FillProperties::PROP_FILL_BITMAP_POSITION_OFFSETY,
                  ::getCppuType( reinterpret_cast< const sal_Int16 * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "FillBitmapRectanglePoint" ),
                  FillProperties::PROP_FILL_BITMAP_RECTANGLEPOINT,
                  ::getCppuType( reinterpret_cast< const drawing::RectanglePoint * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "FillBitmapLogicalSize" ),
                  FillProperties::PROP_FILL_BITMAP_LOGICALSIZE,
                  ::getCppuType( reinterpret_cast< const sal_Bool * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "FillBitmapSizeX" ),
                  FillProperties::PROP_FILL_BITMAP_SIZEX,
                  ::getCppuType( reinterpret_cast< const sal_Int32 * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "FillBitmapSizeY" ),
                  FillProperties::PROP_FILL_BITMAP_SIZEY,
                  ::getCppuType( reinterpret_cast< const sal_Int32 * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));

    rOutProperties.push_back(
        Property( C2U( "FillBitmapMode" ),
                  FillProperties::PROP_FILL_BITMAP_MODE,
                  ::getCppuType( reinterpret_cast< const drawing::BitmapMode * >(0)),
                  beans::PropertyAttribute::BOUND
                  | beans::PropertyAttribute::MAYBEDEFAULT ));
}

void lcl_AddDefaultsToMap_without_BitmapProperties(
    ::chart::tPropertyValueMap & rOutMap )
{
    OSL_ASSERT( rOutMap.end() == rOutMap.find( FillProperties::PROP_FILL_STYLE ));
    rOutMap[ FillProperties::PROP_FILL_STYLE ] =
        uno::makeAny( drawing::FillStyle_SOLID );
    OSL_ASSERT( rOutMap.end() == rOutMap.find( FillProperties::PROP_FILL_COLOR ));
    rOutMap[ FillProperties::PROP_FILL_COLOR ] =
        uno::makeAny( sal_Int32( 0xd9d9d9 ) ); // gray85
    OSL_ASSERT( rOutMap.end() == rOutMap.find( FillProperties::PROP_FILL_TRANSPARENCE ));
    rOutMap[ FillProperties::PROP_FILL_TRANSPARENCE ] =
        uno::makeAny( sal_Int16( 0 ) );
    OSL_ASSERT( rOutMap.end() == rOutMap.find( FillProperties::PROP_FILL_GRADIENT_STEPCOUNT ));
    rOutMap[ FillProperties::PROP_FILL_GRADIENT_STEPCOUNT ] =
        uno::makeAny( sal_Int16( 0 ) );
    OSL_ASSERT( rOutMap.end() == rOutMap.find( FillProperties::PROP_FILL_BACKGROUND ));
    rOutMap[ FillProperties::PROP_FILL_BACKGROUND ] =
        uno::makeAny( sal_Bool( sal_False ) );
}

void lcl_AddDefaultsToMap_only_BitmapProperties(
    ::chart::tPropertyValueMap & rOutMap )
{
    uno::Any aSalInt16Zero = uno::makeAny( sal_Int16( 0 ));
    uno::Any aSalInt32SizeDefault = uno::makeAny( sal_Int32( 0 ));

    OSL_ASSERT( rOutMap.end() == rOutMap.find( FillProperties::PROP_FILL_BITMAP_OFFSETX ));
    rOutMap[ FillProperties::PROP_FILL_BITMAP_OFFSETX ] = aSalInt16Zero;
    OSL_ASSERT( rOutMap.end() == rOutMap.find( FillProperties::PROP_FILL_BITMAP_OFFSETY ));
    rOutMap[ FillProperties::PROP_FILL_BITMAP_OFFSETY ] = aSalInt16Zero;
    OSL_ASSERT( rOutMap.end() == rOutMap.find( FillProperties::PROP_FILL_BITMAP_POSITION_OFFSETX ));
    rOutMap[ FillProperties::PROP_FILL_BITMAP_POSITION_OFFSETX ] = aSalInt16Zero;
    OSL_ASSERT( rOutMap.end() == rOutMap.find( FillProperties::PROP_FILL_BITMAP_POSITION_OFFSETY ));
    rOutMap[ FillProperties::PROP_FILL_BITMAP_POSITION_OFFSETY ] = aSalInt16Zero;
    OSL_ASSERT( rOutMap.end() == rOutMap.find( FillProperties::PROP_FILL_BITMAP_RECTANGLEPOINT ));
    rOutMap[ FillProperties::PROP_FILL_BITMAP_RECTANGLEPOINT ] =
        uno::makeAny( drawing::RectanglePoint_MIDDLE_MIDDLE );
    OSL_ASSERT( rOutMap.end() == rOutMap.find( FillProperties::PROP_FILL_BITMAP_LOGICALSIZE ));
    rOutMap[ FillProperties::PROP_FILL_BITMAP_LOGICALSIZE ] =
        uno::makeAny( true );
    OSL_ASSERT( rOutMap.end() == rOutMap.find( FillProperties::PROP_FILL_BITMAP_SIZEX ));
    rOutMap[ FillProperties::PROP_FILL_BITMAP_SIZEX ] = aSalInt32SizeDefault;
    OSL_ASSERT( rOutMap.end() == rOutMap.find( FillProperties::PROP_FILL_BITMAP_SIZEY ));
    rOutMap[ FillProperties::PROP_FILL_BITMAP_SIZEY ] = aSalInt32SizeDefault;
    OSL_ASSERT( rOutMap.end() == rOutMap.find( FillProperties::PROP_FILL_BITMAP_MODE ));
    rOutMap[ FillProperties::PROP_FILL_BITMAP_MODE ] =
        uno::makeAny( drawing::BitmapMode_REPEAT );
}

}//end anonymous namespace

void FillProperties::AddPropertiesToVector(
    ::std::vector< Property > & rOutProperties )
{
    // Fill Properties see service drawing::FillProperties
    // ---------------
    lcl_AddPropertiesToVector_without_BitmapProperties( rOutProperties );
    lcl_AddPropertiesToVector_only_BitmapProperties( rOutProperties );
}

void FillProperties::AddDefaultsToMap(
    ::chart::tPropertyValueMap & rOutMap )
{
    lcl_AddDefaultsToMap_without_BitmapProperties( rOutMap );
    lcl_AddDefaultsToMap_only_BitmapProperties( rOutMap );
}

} //  namespace chart
<|endoftext|>


<commit_before>#include "map/crown.hpp"

#include "map/purchase.hpp"

#include "metrics/eye.hpp"

#include "platform/preferred_languages.hpp"
#include "platform/platform.hpp"

#include <algorithm>
#include <array>
#include <string>

#include "private.h"

namespace
{
std::array<std::string, 10> const kSupportedLanguages = {"ru", "en", "fr", "de", "es", "it", "pl",
                                                         "zh", "ar", "nl"};
}  // namespace

namespace crown
{
bool NeedToShow(std::unique_ptr<Purchase> const & purchase)
{
  if (!purchase || purchase->IsSubscriptionActive(SubscriptionType::BookmarkCatalog) ||
      !GetPlatform().IsConnected())
  {
    return false;
  }

  auto const lang = languages::GetCurrentNorm();
  auto const supportedLanguageIt = std::find(kSupportedLanguages.cbegin(),
                                             kSupportedLanguages.cend(), lang);
  if (supportedLanguageIt == kSupportedLanguages.cend())
    return false;

  auto const eyeInfo = eye::Eye::Instance().GetInfo();
  // No need to show crown when it is clicked already.
  if (eyeInfo->m_crown.m_clickedTime.time_since_epoch().count() != 0)
    return false;

  // Show crown in some percent of devices.
  std::hash<std::string> h;
  auto const deviceHash = h(GetPlatform().UniqueClientId());
  LOG(LINFO, ("Crown device hash:", deviceHash));
  return deviceHash % 100 < CROWN_PERCENT_OF_DEVICES;
}
}  // namespace crown
<commit_msg>[core] Changed supported launguages list for crown showing<commit_after>#include "map/crown.hpp"

#include "map/purchase.hpp"

#include "metrics/eye.hpp"

#include "platform/preferred_languages.hpp"
#include "platform/platform.hpp"

#include <algorithm>
#include <array>
#include <string>

#include "private.h"

namespace
{
std::array<std::string, 5> const kSupportedLanguages = {"ru", "en", "fr", "de", "es"};
}  // namespace

namespace crown
{
bool NeedToShow(std::unique_ptr<Purchase> const & purchase)
{
  if (!purchase || purchase->IsSubscriptionActive(SubscriptionType::BookmarkCatalog) ||
      !GetPlatform().IsConnected())
  {
    return false;
  }

  auto const lang = languages::GetCurrentNorm();
  auto const supportedLanguageIt = std::find(kSupportedLanguages.cbegin(),
                                             kSupportedLanguages.cend(), lang);
  if (supportedLanguageIt == kSupportedLanguages.cend())
    return false;

  auto const eyeInfo = eye::Eye::Instance().GetInfo();
  // No need to show crown when it is clicked already.
  if (eyeInfo->m_crown.m_clickedTime.time_since_epoch().count() != 0)
    return false;

  // Show crown in some percent of devices.
  std::hash<std::string> h;
  auto const deviceHash = h(GetPlatform().UniqueClientId());
  LOG(LINFO, ("Crown device hash:", deviceHash));
  return deviceHash % 100 < CROWN_PERCENT_OF_DEVICES;
}
}  // namespace crown
<|endoftext|>


<commit_before>#include <QtPlugin>
\
#include "animatedtilesplugin.h"
#include "animatedtilesitem.h"

AnimatedTilesPlugin::AnimatedTilesPlugin()
{
    this->mName = "AnimatedTiles";
    this->mRole = "animatedTiles";
}

Q_EXPORT_PLUGIN2(animatedTiles, AnimatedTilesPlugin)

void AnimatedTilesPlugin::registerPlugin(QDeclarativeContext *context)
{
    qmlRegisterType<AnimatedTilesItem>("AnimatedTiles", 1, 0, "AnimatedTiles");
}
<commit_msg>Prevent the unimplemented animated tiles from being advertized on menu<commit_after>#include <QtPlugin>
\
#include "animatedtilesplugin.h"
#include "animatedtilesitem.h"

AnimatedTilesPlugin::AnimatedTilesPlugin()
{
    this->mName = "AnimatedTiles";
    //This should not be an advertized plugin until it is implemented
    //this->mRole = "animatedTiles";
}

Q_EXPORT_PLUGIN2(animatedTiles, AnimatedTilesPlugin)

void AnimatedTilesPlugin::registerPlugin(QDeclarativeContext *context)
{
    qmlRegisterType<AnimatedTilesItem>("AnimatedTiles", 1, 0, "AnimatedTiles");
}
<|endoftext|>


<commit_before>#include <sys/ioctl.h>
#include <netpacket/packet.h>
#include <syslog.h>
#include <cstdio>
#include <boost/bind.hpp>

#include "defs.h"
#include "PortMapper.hh"

#define BUFFER_SIZE 23 /* Mapping packet size. */
#define SLEEP_TIME boost::posix_time::seconds(10)

PortMapper::PortMapper(uint64_t vm_id, map<int, Interface*> *ifaces, boost::mutex *ifMutex) {
    this->id = vm_id;
    this->ifaces = ifaces;
    this->ifMutex = ifMutex;
}

/**
 * Loops through interfaces, sending mapping packets out each, then sleeps.
 * Rinse and repeat ad infinitum.
 */
void PortMapper::operator()() {
    while(true) {
        boost::system_time timeout = boost::get_system_time() + SLEEP_TIME;

        /* Grab list of interfaces from RFClient, iterate, send map packet */
        {
            boost::lock_guard<boost::mutex> lock(*(this->ifMutex));
            map<int, Interface*>::iterator it;
            for (it = this->ifaces->begin(); it != this->ifaces->end(); it++) {
                this->send_port_map(*(it->second));
            }
        }

        boost::this_thread::sleep(timeout);
    }
}

/**
 * Sends a portmap packet out the given interface, logging the success or
 * failure of the endeavour.
 */
void PortMapper::send_port_map(Interface &iface) {
    if (send_packet(iface.name.c_str(), iface.port) == -1)
        syslog(LOG_NOTICE, "Error sending mapping packet (vm_port=%d)",
               iface.port);
    else
        syslog(LOG_DEBUG, "Mapping packet was sent to RFVS (vm_port=%d)",
               iface.port);
}

/**
 * Sends the magic RouteFlow portmap packet out an interface with the given
 * name, encoding the given port number inside the message.
 *
 * Returns the number of characters sent, or -1 on failure.
 */
int PortMapper::send_packet(const char ethName[], uint8_t port) {
    char msg[BUFFER_SIZE];
    char buffer[BUFSIZ];
    uint16_t ethType;
    struct ifreq req;
    struct sockaddr_ll sll;
    uint8_t srcAddress[IFHWADDRLEN];
    uint8_t dstAddress[IFHWADDRLEN] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
    int ifindex, addrLen, SockFd;
    int error = -1;

    SockFd = socket(PF_PACKET, SOCK_RAW, htons(RF_ETH_PROTO));

    memset(&req, 0, sizeof(req));
    strcpy(req.ifr_name, ethName);
    if (ioctl(SockFd, SIOCGIFFLAGS, &req) < 0) {
        goto exit;
    }

    /* If the interface is down we can't send the packet. */
    syslog(LOG_INFO, "FLAG %d\n", req.ifr_flags & IFF_UP);
    if (!(req.ifr_flags & IFF_UP)) {
        goto exit;
    }

    /* Get the interface index. */
    if (ioctl(SockFd, SIOCGIFINDEX, &req) < 0) {
        goto exit;
    }

    /* Get the MAC address. */
    ifindex = req.ifr_ifindex;
    if (ioctl(SockFd, SIOCGIFHWADDR, &req) < 0) {
        goto exit;
    }
    memcpy(srcAddress, req.ifr_hwaddr.sa_data, IFHWADDRLEN);

    /* Bind to the socket. */
    memset(&sll, 0, sizeof(struct sockaddr_ll));
    sll.sll_family = PF_PACKET;
    sll.sll_ifindex = ifindex;
    addrLen = sizeof(sll);
    if (bind(SockFd, (struct sockaddr *) &sll, addrLen) < 0) {
        goto exit;
    }

    /* Construct the packet and send it. */
    memset(msg, 0, BUFFER_SIZE);
    memcpy((void *) msg, (void *) dstAddress, IFHWADDRLEN);
    memcpy((void *) (msg + IFHWADDRLEN), (void *) srcAddress, IFHWADDRLEN);
    ethType = htons(RF_ETH_PROTO);
    memcpy((void *) (msg + 2 * IFHWADDRLEN), (void *) &ethType,
            sizeof(uint16_t));
    memcpy((void *) (msg + 14), (void *) &this->id, sizeof(uint64_t));
    memcpy((void *) (msg + 22), (void *) &port, sizeof(uint8_t));
    error = (sendto(SockFd, msg, BUFFER_SIZE, 0, (struct sockaddr *) &sll,
             (socklen_t) addrLen));

exit:
    if (error) {
        strerror_r(errno, buffer, BUFSIZ);
        syslog(LOG_ERR, "send_packet(): %s", buffer);
    }
    close(SockFd);
    return error;
}
<commit_msg>Improve PortMapper logging<commit_after>#include <sys/ioctl.h>
#include <netpacket/packet.h>
#include <syslog.h>
#include <cstdio>
#include <boost/bind.hpp>

#include "defs.h"
#include "PortMapper.hh"

#define BUFFER_SIZE 23 /* Mapping packet size. */
#define SLEEP_TIME boost::posix_time::seconds(10)

PortMapper::PortMapper(uint64_t vm_id, map<int, Interface*> *ifaces, boost::mutex *ifMutex) {
    this->id = vm_id;
    this->ifaces = ifaces;
    this->ifMutex = ifMutex;
}

/**
 * Loops through interfaces, sending mapping packets out each, then sleeps.
 * Rinse and repeat ad infinitum.
 */
void PortMapper::operator()() {
    while(true) {
        boost::system_time timeout = boost::get_system_time() + SLEEP_TIME;

        /* Grab list of interfaces from RFClient, iterate, send map packet */
        {
            boost::lock_guard<boost::mutex> lock(*(this->ifMutex));
            map<int, Interface*>::iterator it;
            for (it = this->ifaces->begin(); it != this->ifaces->end(); it++) {
                this->send_port_map(*(it->second));
            }
        }

        boost::this_thread::sleep(timeout);
    }
}

/**
 * Sends a portmap packet out the given interface, logging the success or
 * failure of the endeavour.
 */
void PortMapper::send_port_map(Interface &iface) {
    if (send_packet(iface.name.c_str(), iface.port) == -1)
        syslog(LOG_NOTICE, "Error sending mapping packet (vm_port=%d)",
               iface.port);
    else
        syslog(LOG_DEBUG, "Mapping packet was sent to RFVS (vm_port=%d)",
               iface.port);
}

/**
 * Sends the magic RouteFlow portmap packet out an interface with the given
 * name, encoding the given port number inside the message.
 *
 * Returns the number of characters sent, or -1 on failure.
 */
int PortMapper::send_packet(const char ethName[], uint8_t port) {
    char msg[BUFFER_SIZE];
    char buffer[BUFSIZ];
    uint16_t ethType;
    struct ifreq req;
    struct sockaddr_ll sll;
    uint8_t srcAddress[IFHWADDRLEN];
    uint8_t dstAddress[IFHWADDRLEN] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
    int ifindex, addrLen, SockFd;
    int error = -1;

    SockFd = socket(PF_PACKET, SOCK_RAW, htons(RF_ETH_PROTO));

    memset(&req, 0, sizeof(req));
    strcpy(req.ifr_name, ethName);
    if (ioctl(SockFd, SIOCGIFFLAGS, &req) < 0) {
        goto exit;
    }

    /* If the interface is down we can't send the packet. */
    if (!(req.ifr_flags & IFF_UP)) {
        goto exit;
    }

    /* Get the interface index. */
    if (ioctl(SockFd, SIOCGIFINDEX, &req) < 0) {
        goto exit;
    }

    /* Get the MAC address. */
    ifindex = req.ifr_ifindex;
    if (ioctl(SockFd, SIOCGIFHWADDR, &req) < 0) {
        goto exit;
    }
    memcpy(srcAddress, req.ifr_hwaddr.sa_data, IFHWADDRLEN);

    /* Bind to the socket. */
    memset(&sll, 0, sizeof(struct sockaddr_ll));
    sll.sll_family = PF_PACKET;
    sll.sll_ifindex = ifindex;
    addrLen = sizeof(sll);
    if (bind(SockFd, (struct sockaddr *) &sll, addrLen) < 0) {
        goto exit;
    }

    /* Construct the packet and send it. */
    memset(msg, 0, BUFFER_SIZE);
    memcpy((void *) msg, (void *) dstAddress, IFHWADDRLEN);
    memcpy((void *) (msg + IFHWADDRLEN), (void *) srcAddress, IFHWADDRLEN);
    ethType = htons(RF_ETH_PROTO);
    memcpy((void *) (msg + 2 * IFHWADDRLEN), (void *) &ethType,
            sizeof(uint16_t));
    memcpy((void *) (msg + 14), (void *) &this->id, sizeof(uint64_t));
    memcpy((void *) (msg + 22), (void *) &port, sizeof(uint8_t));
    error = (sendto(SockFd, msg, BUFFER_SIZE, 0, (struct sockaddr *) &sll,
             (socklen_t) addrLen));

exit:
    if (error <= 0) {
        strerror_r(errno, buffer, BUFSIZ);
        syslog(LOG_ERR, "send_packet(): %s", buffer);
    }
    close(SockFd);
    return error;
}
<|endoftext|>