<commit_before>// Copyright (c) 2021 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or https://www.opensource.org/licenses/mit-license.php.

#include "qt/pivx/governancemodel.h"

#include "budget/budgetmanager.h"
#include "budget/budgetutil.h"
#include "destination_io.h"
#include "guiconstants.h"
#include "masternode-sync.h"
#include "script/standard.h"
#include "qt/transactiontablemodel.h"
#include "qt/transactionrecord.h"
#include "qt/pivx/mnmodel.h"
#include "utilmoneystr.h"
#include "utilstrencodings.h"
#include "walletmodel.h"

#include <algorithm>
#include <QTimer>

GovernanceModel::GovernanceModel(ClientModel* _clientModel, MNModel* _mnModel) : clientModel(_clientModel), mnModel(_mnModel) {}
GovernanceModel::~GovernanceModel() {}

void GovernanceModel::setWalletModel(WalletModel* _walletModel)
{
    walletModel = _walletModel;
    connect(walletModel->getTransactionTableModel(), &TransactionTableModel::txLoaded, this, &GovernanceModel::txLoaded);
}

ProposalInfo GovernanceModel::buidProposalInfo(const CBudgetProposal* prop, bool isPassing, bool isPending)
{
    CTxDestination recipient;
    ExtractDestination(prop->GetPayee(), recipient);

    // Calculate status
    int votesYes = prop->GetYeas();
    int votesNo = prop->GetNays();
    ProposalInfo::Status status;

    if (isPending) {
        // Proposal waiting for confirmation to be broadcasted.
        status = ProposalInfo::WAITING_FOR_APPROVAL;
    } else {
        if (isPassing) {
            status = ProposalInfo::PASSING;
        } else if (votesYes > votesNo) {
            status = ProposalInfo::PASSING_NOT_FUNDED;
        } else {
            status = ProposalInfo::NOT_PASSING;
        }
    }

    return ProposalInfo(prop->GetHash(),
            prop->GetName(),
            prop->GetURL(),
            votesYes,
            votesNo,
            Standard::EncodeDestination(recipient),
            prop->GetAmount(),
            prop->GetTotalPaymentCount(),
            prop->GetRemainingPaymentCount(clientModel->getLastBlockProcessedHeight()),
            status);
}

std::list<ProposalInfo> GovernanceModel::getProposals(const ProposalInfo::Status* filterByStatus)
{
    if (!clientModel) return {};
    std::list<ProposalInfo> ret;
    std::vector<CBudgetProposal> budget = g_budgetman.GetBudget();
    for (const auto& prop : g_budgetman.GetAllProposalsOrdered()) {
        bool isPassing = std::find(budget.begin(), budget.end(), *prop) != budget.end();
        ProposalInfo propInfo = buidProposalInfo(prop, isPassing, false);
        if (!filterByStatus || propInfo.status == *filterByStatus) {
            ret.emplace_back(propInfo);
        }
        if (isPassing) allocatedAmount += prop->GetAmount();
    }

    // Add pending proposals
    for (const auto& prop : waitingPropsForConfirmations) {
        ProposalInfo propInfo = buidProposalInfo(&prop, false, true);
        if (!filterByStatus || propInfo.status == *filterByStatus) {
            ret.emplace_back(propInfo);
        }
    }
    return ret;
}

bool GovernanceModel::hasProposals()
{
    return g_budgetman.HasAnyProposal();
}

CAmount GovernanceModel::getMaxAvailableBudgetAmount() const
{
    return g_budgetman.GetTotalBudget(clientModel->getNumBlocks());
}

int GovernanceModel::getNumBlocksPerBudgetCycle() const
{
    return Params().GetConsensus().nBudgetCycleBlocks;
}

int GovernanceModel::getPropMaxPaymentsCount() const
{
    return Params().GetConsensus().nMaxProposalPayments;
}

int GovernanceModel::getNextSuperblockHeight() const
{
    const int nBlocksPerCycle = getNumBlocksPerBudgetCycle();
    const int chainHeight = clientModel->getNumBlocks();
    return chainHeight - chainHeight % nBlocksPerCycle + nBlocksPerCycle;
}

std::vector<VoteInfo> GovernanceModel::getLocalMNsVotesForProposal(const ProposalInfo& propInfo)
{
    // First, get the local masternodes
    std::vector<std::pair<COutPoint, std::string>> vecLocalMn;
    for (int i = 0; i < mnModel->rowCount(); ++i) {
        vecLocalMn.emplace_back(std::make_pair(
                COutPoint(uint256S(mnModel->index(i, MNModel::COLLATERAL_ID, QModelIndex()).data().toString().toStdString()),
                mnModel->index(i, MNModel::COLLATERAL_OUT_INDEX, QModelIndex()).data().toInt()),
                mnModel->index(i, MNModel::ALIAS, QModelIndex()).data().toString().toStdString())
        );
    }

    std::vector<VoteInfo> localVotes;
    // Get the budget proposal, get the votes, then loop over it and return the ones that correspond to the local masternodes here.
    CBudgetProposal* prop = g_budgetman.FindProposal(propInfo.id);
    const auto& mapVotes = prop->GetVotes();
    for (const auto& it : mapVotes) {
        for (const auto& mn : vecLocalMn) {
            if (it.first == mn.first && it.second.IsValid()) {
                localVotes.emplace_back(mn.first, (VoteInfo::VoteDirection) it.second.GetDirection(), mn.second);
                break;
            }
        }
    }
    return localVotes;
}

OperationResult GovernanceModel::validatePropURL(const QString& url) const
{
    std::string strError;
    return {validateURL(url.toStdString(), strError, PROP_URL_MAX_SIZE), strError};
}

OperationResult GovernanceModel::validatePropAmount(CAmount amount) const
{
    if (amount > getMaxAvailableBudgetAmount()) {
        return {false, strprintf("Amount exceeding the maximum available budget amount of %s PIV", FormatMoney(amount))};
    }
    return {true};
}

OperationResult GovernanceModel::validatePropPaymentCount(int paymentCount) const
{
    if (paymentCount < 1) return { false, "Invalid payment count, must be greater than zero."};
    int nMaxPayments = getPropMaxPaymentsCount();
    if (paymentCount > nMaxPayments) {
        return { false, strprintf("Invalid payment count, cannot be greater than %d", nMaxPayments)};
    }
    return {true};
}

bool GovernanceModel::isTierTwoSync()
{
    return masternodeSync.IsBlockchainSynced();
}

OperationResult GovernanceModel::createProposal(const std::string& strProposalName,
                                                const std::string& strURL,
                                                int nPaymentCount,
                                                CAmount nAmount,
                                                const std::string& strPaymentAddr)
{
    // First get the next superblock height
    int nBlockStart = getNextSuperblockHeight();

    // Parse address
    const CTxDestination* dest = Standard::GetTransparentDestination(Standard::DecodeDestination(strPaymentAddr));
    if (!dest) return {false, "invalid recipient address for the proposal"};
    CScript scriptPubKey = GetScriptForDestination(*dest);

    // Validate proposal
    CBudgetProposal proposal(strProposalName, strURL, nPaymentCount, scriptPubKey, nAmount, nBlockStart, UINT256_ZERO);
    if (!proposal.IsWellFormed(g_budgetman.GetTotalBudget(proposal.GetBlockStart()))) {
        return {false, strprintf("Proposal is not valid %s", proposal.IsInvalidReason())};
    }

    // Craft and send transaction.
    auto opRes = walletModel->createAndSendProposalFeeTx(proposal);
    if (!opRes) return opRes;
    scheduleBroadcast(proposal);

    return {true};
}

OperationResult GovernanceModel::voteForProposal(const ProposalInfo& prop,
                                                 bool isVotePositive,
                                                 const std::vector<std::string>& mnVotingAlias)
{
    UniValue ret; // future: don't use UniValue here.
    for (const auto& mnAlias : mnVotingAlias) {
        bool fLegacyMN = true; // For now, only legacy MNs
        ret = mnBudgetVoteInner(nullptr,
                          fLegacyMN,
                          prop.id,
                          false,
                          isVotePositive ? CBudgetVote::VoteDirection::VOTE_YES : CBudgetVote::VoteDirection::VOTE_NO,
                          mnAlias);
        if (ret.exists("detail") && ret["detail"].isArray()) {
            const UniValue& obj = ret["detail"].get_array()[0];
            if (obj["result"].getValStr() != "success") {
                return {false, obj["error"].getValStr()};
            }
        }
    }
    // add more information with ret["overall"]
    return {true};
}

void GovernanceModel::scheduleBroadcast(const CBudgetProposal& proposal)
{
    // Cache the proposal to be sent as soon as it gets the minimum required confirmations
    // without requiring user interaction
    waitingPropsForConfirmations.emplace_back(proposal);

    // Launch timer if it's not already running
    if (!pollTimer) pollTimer = new QTimer(this);
    if (!pollTimer->isActive()) {
        connect(pollTimer, &QTimer::timeout, this, &GovernanceModel::pollGovernanceChanged);
        pollTimer->start(MODEL_UPDATE_DELAY * 60 * (walletModel->isTestNetwork() ? 0.5 : 3.5)); // Every 3.5 minutes
    }
}

void GovernanceModel::pollGovernanceChanged()
{
    if (!isTierTwoSync()) return;

    int chainHeight = clientModel->getNumBlocks();
    // Try to broadcast any pending for confirmations proposal
    auto it = waitingPropsForConfirmations.begin();
    while (it != waitingPropsForConfirmations.end()) {
        // Remove expired proposals
        if (it->IsExpired(clientModel->getNumBlocks())) {
            it = waitingPropsForConfirmations.erase(it);
            continue;
        }

        // Try to add it
        if (!g_budgetman.AddProposal(*it)) {
            LogPrint(BCLog::QT, "Cannot broadcast budget proposal - %s", it->IsInvalidReason());
            // Remove proposals who due a reorg lost their fee tx
            if (it->IsInvalidReason().find("Can't find collateral tx") != std::string::npos) {
                // future: notify the user about it.
                it = waitingPropsForConfirmations.erase(it);
                continue;
            }
            // Check if the proposal didn't exceed the superblock start height
            if (it->GetBlockStart() >= chainHeight) {
                // Edge case, the proposal was never broadcasted before the next superblock, can be removed.
                // future: notify the user about it.
                it = waitingPropsForConfirmations.erase(it);
            } else {
                it++;
            }
            continue;
        }
        it->Relay();
        it = waitingPropsForConfirmations.erase(it);
    }

    // If there are no more waiting proposals, turn the timer off.
    if (waitingPropsForConfirmations.empty()) {
        pollTimer->stop();
    }
}

void GovernanceModel::stopPolling()
{
    if (pollTimer && pollTimer->isActive()) {
        pollTimer->stop();
    }
}

void GovernanceModel::txLoaded(const QString& id, const int txType, const int txStatus)
{
    if (txType == TransactionRecord::SendToNobody) {
        // If the tx is not longer available in the mainchain, drop it.
        if (txStatus == TransactionStatus::Conflicted ||
            txStatus == TransactionStatus::NotAccepted) {
            return;
        }
        // If this is a proposal fee, parse it.
        const auto& wtx = walletModel->getTx(uint256S(id.toStdString()));
        assert(wtx);
        const auto& it = wtx->mapValue.find("proposal");
        if (it != wtx->mapValue.end()) {
            const std::vector<unsigned char> vec = ParseHex(it->second);
            if (vec.empty()) return;
            CDataStream ss(vec, SER_DISK, CLIENT_VERSION);
            CBudgetProposal proposal;
            ss >> proposal;
            if (!g_budgetman.HaveProposal(proposal.GetHash()) &&
                !proposal.IsExpired(clientModel->getNumBlocks()) &&
                proposal.GetBlockStart() < clientModel->getNumBlocks()) {
                scheduleBroadcast(proposal);
            }
        }
    }
}
<commit_msg>GUI: Governance model, add waiting proposal to the hasProposals() return.<commit_after>// Copyright (c) 2021 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or https://www.opensource.org/licenses/mit-license.php.

#include "qt/pivx/governancemodel.h"

#include "budget/budgetmanager.h"
#include "budget/budgetutil.h"
#include "destination_io.h"
#include "guiconstants.h"
#include "masternode-sync.h"
#include "script/standard.h"
#include "qt/transactiontablemodel.h"
#include "qt/transactionrecord.h"
#include "qt/pivx/mnmodel.h"
#include "utilmoneystr.h"
#include "utilstrencodings.h"
#include "walletmodel.h"

#include <algorithm>
#include <QTimer>

GovernanceModel::GovernanceModel(ClientModel* _clientModel, MNModel* _mnModel) : clientModel(_clientModel), mnModel(_mnModel) {}
GovernanceModel::~GovernanceModel() {}

void GovernanceModel::setWalletModel(WalletModel* _walletModel)
{
    walletModel = _walletModel;
    connect(walletModel->getTransactionTableModel(), &TransactionTableModel::txLoaded, this, &GovernanceModel::txLoaded);
}

ProposalInfo GovernanceModel::buidProposalInfo(const CBudgetProposal* prop, bool isPassing, bool isPending)
{
    CTxDestination recipient;
    ExtractDestination(prop->GetPayee(), recipient);

    // Calculate status
    int votesYes = prop->GetYeas();
    int votesNo = prop->GetNays();
    ProposalInfo::Status status;

    if (isPending) {
        // Proposal waiting for confirmation to be broadcasted.
        status = ProposalInfo::WAITING_FOR_APPROVAL;
    } else {
        if (isPassing) {
            status = ProposalInfo::PASSING;
        } else if (votesYes > votesNo) {
            status = ProposalInfo::PASSING_NOT_FUNDED;
        } else {
            status = ProposalInfo::NOT_PASSING;
        }
    }

    return ProposalInfo(prop->GetHash(),
            prop->GetName(),
            prop->GetURL(),
            votesYes,
            votesNo,
            Standard::EncodeDestination(recipient),
            prop->GetAmount(),
            prop->GetTotalPaymentCount(),
            prop->GetRemainingPaymentCount(clientModel->getLastBlockProcessedHeight()),
            status);
}

std::list<ProposalInfo> GovernanceModel::getProposals(const ProposalInfo::Status* filterByStatus)
{
    if (!clientModel) return {};
    std::list<ProposalInfo> ret;
    std::vector<CBudgetProposal> budget = g_budgetman.GetBudget();
    for (const auto& prop : g_budgetman.GetAllProposalsOrdered()) {
        bool isPassing = std::find(budget.begin(), budget.end(), *prop) != budget.end();
        ProposalInfo propInfo = buidProposalInfo(prop, isPassing, false);
        if (!filterByStatus || propInfo.status == *filterByStatus) {
            ret.emplace_back(propInfo);
        }
        if (isPassing) allocatedAmount += prop->GetAmount();
    }

    // Add pending proposals
    for (const auto& prop : waitingPropsForConfirmations) {
        ProposalInfo propInfo = buidProposalInfo(&prop, false, true);
        if (!filterByStatus || propInfo.status == *filterByStatus) {
            ret.emplace_back(propInfo);
        }
    }
    return ret;
}

bool GovernanceModel::hasProposals()
{
    return g_budgetman.HasAnyProposal() || !waitingPropsForConfirmations.empty();
}

CAmount GovernanceModel::getMaxAvailableBudgetAmount() const
{
    return g_budgetman.GetTotalBudget(clientModel->getNumBlocks());
}

int GovernanceModel::getNumBlocksPerBudgetCycle() const
{
    return Params().GetConsensus().nBudgetCycleBlocks;
}

int GovernanceModel::getPropMaxPaymentsCount() const
{
    return Params().GetConsensus().nMaxProposalPayments;
}

int GovernanceModel::getNextSuperblockHeight() const
{
    const int nBlocksPerCycle = getNumBlocksPerBudgetCycle();
    const int chainHeight = clientModel->getNumBlocks();
    return chainHeight - chainHeight % nBlocksPerCycle + nBlocksPerCycle;
}

std::vector<VoteInfo> GovernanceModel::getLocalMNsVotesForProposal(const ProposalInfo& propInfo)
{
    // First, get the local masternodes
    std::vector<std::pair<COutPoint, std::string>> vecLocalMn;
    for (int i = 0; i < mnModel->rowCount(); ++i) {
        vecLocalMn.emplace_back(std::make_pair(
                COutPoint(uint256S(mnModel->index(i, MNModel::COLLATERAL_ID, QModelIndex()).data().toString().toStdString()),
                mnModel->index(i, MNModel::COLLATERAL_OUT_INDEX, QModelIndex()).data().toInt()),
                mnModel->index(i, MNModel::ALIAS, QModelIndex()).data().toString().toStdString())
        );
    }

    std::vector<VoteInfo> localVotes;
    // Get the budget proposal, get the votes, then loop over it and return the ones that correspond to the local masternodes here.
    CBudgetProposal* prop = g_budgetman.FindProposal(propInfo.id);
    const auto& mapVotes = prop->GetVotes();
    for (const auto& it : mapVotes) {
        for (const auto& mn : vecLocalMn) {
            if (it.first == mn.first && it.second.IsValid()) {
                localVotes.emplace_back(mn.first, (VoteInfo::VoteDirection) it.second.GetDirection(), mn.second);
                break;
            }
        }
    }
    return localVotes;
}

OperationResult GovernanceModel::validatePropURL(const QString& url) const
{
    std::string strError;
    return {validateURL(url.toStdString(), strError, PROP_URL_MAX_SIZE), strError};
}

OperationResult GovernanceModel::validatePropAmount(CAmount amount) const
{
    if (amount > getMaxAvailableBudgetAmount()) {
        return {false, strprintf("Amount exceeding the maximum available budget amount of %s PIV", FormatMoney(amount))};
    }
    return {true};
}

OperationResult GovernanceModel::validatePropPaymentCount(int paymentCount) const
{
    if (paymentCount < 1) return { false, "Invalid payment count, must be greater than zero."};
    int nMaxPayments = getPropMaxPaymentsCount();
    if (paymentCount > nMaxPayments) {
        return { false, strprintf("Invalid payment count, cannot be greater than %d", nMaxPayments)};
    }
    return {true};
}

bool GovernanceModel::isTierTwoSync()
{
    return masternodeSync.IsBlockchainSynced();
}

OperationResult GovernanceModel::createProposal(const std::string& strProposalName,
                                                const std::string& strURL,
                                                int nPaymentCount,
                                                CAmount nAmount,
                                                const std::string& strPaymentAddr)
{
    // First get the next superblock height
    int nBlockStart = getNextSuperblockHeight();

    // Parse address
    const CTxDestination* dest = Standard::GetTransparentDestination(Standard::DecodeDestination(strPaymentAddr));
    if (!dest) return {false, "invalid recipient address for the proposal"};
    CScript scriptPubKey = GetScriptForDestination(*dest);

    // Validate proposal
    CBudgetProposal proposal(strProposalName, strURL, nPaymentCount, scriptPubKey, nAmount, nBlockStart, UINT256_ZERO);
    if (!proposal.IsWellFormed(g_budgetman.GetTotalBudget(proposal.GetBlockStart()))) {
        return {false, strprintf("Proposal is not valid %s", proposal.IsInvalidReason())};
    }

    // Craft and send transaction.
    auto opRes = walletModel->createAndSendProposalFeeTx(proposal);
    if (!opRes) return opRes;
    scheduleBroadcast(proposal);

    return {true};
}

OperationResult GovernanceModel::voteForProposal(const ProposalInfo& prop,
                                                 bool isVotePositive,
                                                 const std::vector<std::string>& mnVotingAlias)
{
    UniValue ret; // future: don't use UniValue here.
    for (const auto& mnAlias : mnVotingAlias) {
        bool fLegacyMN = true; // For now, only legacy MNs
        ret = mnBudgetVoteInner(nullptr,
                          fLegacyMN,
                          prop.id,
                          false,
                          isVotePositive ? CBudgetVote::VoteDirection::VOTE_YES : CBudgetVote::VoteDirection::VOTE_NO,
                          mnAlias);
        if (ret.exists("detail") && ret["detail"].isArray()) {
            const UniValue& obj = ret["detail"].get_array()[0];
            if (obj["result"].getValStr() != "success") {
                return {false, obj["error"].getValStr()};
            }
        }
    }
    // add more information with ret["overall"]
    return {true};
}

void GovernanceModel::scheduleBroadcast(const CBudgetProposal& proposal)
{
    // Cache the proposal to be sent as soon as it gets the minimum required confirmations
    // without requiring user interaction
    waitingPropsForConfirmations.emplace_back(proposal);

    // Launch timer if it's not already running
    if (!pollTimer) pollTimer = new QTimer(this);
    if (!pollTimer->isActive()) {
        connect(pollTimer, &QTimer::timeout, this, &GovernanceModel::pollGovernanceChanged);
        pollTimer->start(MODEL_UPDATE_DELAY * 60 * (walletModel->isTestNetwork() ? 0.5 : 3.5)); // Every 3.5 minutes
    }
}

void GovernanceModel::pollGovernanceChanged()
{
    if (!isTierTwoSync()) return;

    int chainHeight = clientModel->getNumBlocks();
    // Try to broadcast any pending for confirmations proposal
    auto it = waitingPropsForConfirmations.begin();
    while (it != waitingPropsForConfirmations.end()) {
        // Remove expired proposals
        if (it->IsExpired(clientModel->getNumBlocks())) {
            it = waitingPropsForConfirmations.erase(it);
            continue;
        }

        // Try to add it
        if (!g_budgetman.AddProposal(*it)) {
            LogPrint(BCLog::QT, "Cannot broadcast budget proposal - %s", it->IsInvalidReason());
            // Remove proposals who due a reorg lost their fee tx
            if (it->IsInvalidReason().find("Can't find collateral tx") != std::string::npos) {
                // future: notify the user about it.
                it = waitingPropsForConfirmations.erase(it);
                continue;
            }
            // Check if the proposal didn't exceed the superblock start height
            if (it->GetBlockStart() >= chainHeight) {
                // Edge case, the proposal was never broadcasted before the next superblock, can be removed.
                // future: notify the user about it.
                it = waitingPropsForConfirmations.erase(it);
            } else {
                it++;
            }
            continue;
        }
        it->Relay();
        it = waitingPropsForConfirmations.erase(it);
    }

    // If there are no more waiting proposals, turn the timer off.
    if (waitingPropsForConfirmations.empty()) {
        pollTimer->stop();
    }
}

void GovernanceModel::stopPolling()
{
    if (pollTimer && pollTimer->isActive()) {
        pollTimer->stop();
    }
}

void GovernanceModel::txLoaded(const QString& id, const int txType, const int txStatus)
{
    if (txType == TransactionRecord::SendToNobody) {
        // If the tx is not longer available in the mainchain, drop it.
        if (txStatus == TransactionStatus::Conflicted ||
            txStatus == TransactionStatus::NotAccepted) {
            return;
        }
        // If this is a proposal fee, parse it.
        const auto& wtx = walletModel->getTx(uint256S(id.toStdString()));
        assert(wtx);
        const auto& it = wtx->mapValue.find("proposal");
        if (it != wtx->mapValue.end()) {
            const std::vector<unsigned char> vec = ParseHex(it->second);
            if (vec.empty()) return;
            CDataStream ss(vec, SER_DISK, CLIENT_VERSION);
            CBudgetProposal proposal;
            ss >> proposal;
            if (!g_budgetman.HaveProposal(proposal.GetHash()) &&
                !proposal.IsExpired(clientModel->getNumBlocks()) &&
                proposal.GetBlockStart() < clientModel->getNumBlocks()) {
                scheduleBroadcast(proposal);
            }
        }
    }
}
<|endoftext|>


<commit_before>#ifndef MESCALINE_AUDIO_ENGINE_H_INCLUDED
#define MESCALINE_AUDIO_ENGINE_H_INCLUDED

#include <Mescaline/Audio.hpp>
#include <Mescaline/Audio/AudioBus.hpp>
#include <Mescaline/Audio/IO/Client.hpp>
#include <Mescaline/Audio/Node.hpp>
#include <Mescaline/Audio/Plugin/API.h>
#include <Mescaline/Audio/SynthDef.hpp>
#include <Mescaline/Exception.hpp>
#include <Mescaline/Memory/Manager.hpp>

#include <boost/container/vector.hpp>
#include <boost/cstdint.hpp>
#include <boost/lockfree/fifo.hpp>
#include <boost/lockfree/ringbuffer.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/thread/thread.hpp>
#include <boost/utility.hpp>

#include <oscpp/server.hpp>

#include <bitset>
#include <string>
#include <vector>

namespace Mescaline { namespace Audio
{
    using namespace Memory;

    class OSCPacket
    {
    public:
        OSCPacket(char data[], size_t size)
            : m_packet(data, size)
            , m_data(data)
        { }
        ~OSCPacket()
        {
            delete [] m_data;
        }

        OSC::ServerPacket   m_packet;
        char*               m_data;
    };

    // typedef int32_t ControlBusId;

    // class ControlBusId
    // {
    // public:
    //     ControlBusId()
    //         : m_id(-1)
    //     { }
    //     ControlBusId(
    //     uint32_t id() const { return m_id; }
    //     operator bool () const { return m_id != -1; }
    //
    // private:
    //     uint32_t m_id;
    // };

    // class ControlBus : boost::noncopyable
    // {
    // public:
    //     typedef sample_t ValueType;
    //
    // private:
    //     BusId       m_id;
    //     Epoch       m_epoch;
    //     ValueType   m_data;
    // };

    struct EngineException : virtual Mescaline::Exception { };
    struct InvalidNodeId : virtual EngineException { };
    struct DuplicateNodeId : virtual EngineException { };
    struct ErrorInfoNodeIdTag {};
    typedef boost::error_info<ErrorInfoNodeIdTag, NodeId> ErrorInfoNodeId;

    class Node;

    class NodeMap
    {
        typedef std::vector<Node*> Nodes;

    public:
        typedef Nodes::const_reference const_reference;

        NodeMap(size_t maxNumNodes)
            : m_nodes(maxNumNodes, 0)
        { }

        void insert(Node* node);
        const_reference lookup(const NodeId& nodeId) const { return m_nodes.at(nodeId); }
        void release(const NodeId& nodeId);

    private:
        Nodes m_nodes;
    };

    class Group;
    class PluginInterface;

//    class Message
//    {
//    public:
//        static const size_t kMaxPayloadBytes = 128;
//
//        typedef bool (*PerformFunc)(void*);
//
//        Message()
//            : m_perform(0)
//        {
//#ifndef NDEBUG
//            memset(m_payload, 0, kMaxPayloadBytes);
//#endif
//        }
//        Message(const Message& other)
//        {
//            m_perform = other.m_perform;
//            memcpy(m_payload, other.m_payload, kMaxPayloadBytes);
//        }
//
//        char* payload() { return m_payload.bytes; }
//
//    private:
//        bool (*m_perform)(void*);
//        char m_payload[kMaxPayloadBytes];
//    };

    class Environment : public boost::noncopyable
    {
    public:
        struct Options
        {
            Options()
                : maxNumNodes(1024)
                , maxNumAudioBuses(128)
                , maxNumControlBuses(4096)
                , sampleRate(44100)
                , blockSize(64)
                , numHardwareInputChannels(2)
                , numHardwareOutputChannels(2)
            { }

            size_t maxNumNodes;
            size_t maxNumAudioBuses;
            size_t maxNumControlBuses;
            size_t sampleRate;
            size_t blockSize;
            size_t numHardwareInputChannels;
            size_t numHardwareOutputChannels;
        };

        Environment(Plugin::Manager& pluginManager, const Options& options);
        ~Environment();

        void initModule(MescalineInitFunc moduleInitFunc);

        const Plugin::Manager::PluginHandle& lookupSynthDef(const char* name) { return m_synthDefs.lookup(name); }
        void registerSynthDef(SynthDef* synthDef) { /* m_synthDefs.insert(synthDef); */ }

        Group* rootNode() { return m_rootNode; }
        const NodeMap& nodes() const { return m_nodes; }

        size_t sampleRate() const { return m_sampleRate; }
        size_t blockSize() const { return m_blockSize; }

        AudioBus& audioBus(AudioBusId busId)
        {
            switch (busId.scope()) {
                case AudioBusId::kInput:
                    return m_audioInputChannels[busId.id()];
                case AudioBusId::kOutput:
                    return m_audioOutputChannels[busId.id()];
                case AudioBusId::kInternal:
                    return m_audioBuses[busId.id()];
            }
            BOOST_THROW_EXCEPTION(InvalidInput());
        }

        RTMemoryManager& rtMem() { return m_rtMem; }

        const Epoch& epoch() const { return m_epoch; }

        void process(size_t numFrames, sample_t** inputs, sample_t** outputs);

        typedef boost::lockfree::ringbuffer<OSCPacket*, 1024> CommandFifo;
//        typedef boost::lockfree::fifo<Message> MessageFifo;

    protected:
        friend class Node;

        void insertNode(Node* node);
        void releaseNodeId(const NodeId& nodeId);

    private:
        const size_t                m_sampleRate;
        const size_t                m_blockSize;
        PluginInterface*            m_pluginInterface;
        RTMemoryManager             m_rtMem;
//        SynthDefMap                 m_synthDefs;
        Plugin::Manager&            m_synthDefs;
        Group*                      m_rootNode;
        NodeMap                     m_nodes;
        boost::ptr_vector<ExternalAudioBus> m_audioInputChannels;
        boost::ptr_vector<ExternalAudioBus> m_audioOutputChannels;
        boost::ptr_vector<InternalAudioBus> m_audioBuses;
        Epoch                       m_epoch;
//        CommandFifo                 m_commandFifo;
//        MessageFifo                 m_nrtToRtFifo;
//        MessageFifo                 m_rtToNrtFifo;
    };

    // This is the interface that plugins use (via its function pointers,
    // inherited from MescalineHost).
    class PluginInterface : public MescalineHost
    {
    public:
        PluginInterface(Environment& env)
            : m_env(env)
        {
            fGetSampleRate = &GetSampleRate;
            fRegisterSynthDef = &RegisterSynthDef;
        }

    private:
        static unsigned int GetSampleRate(const MescalineHost* self)
            { return static_cast<const PluginInterface*>(self)->m_env.sampleRate(); }
        static void RegisterSynthDef(MescalineHost* self, MescalineSynthDef* synthDef)
            { static_cast<PluginInterface*>(self)->m_env.registerSynthDef(new SynthDef(self, synthDef)); }

    private:
        Environment& m_env;
    };

    class Engine : public IO::Client
    {
    public:
        Engine(Plugin::Loader* pluginLoader);
        virtual ~Engine();

        virtual void configure(const IO::Driver& driver);
        virtual void process(size_t numFrames, sample_t** inputs, sample_t** outputs);

        Environment& environment()
        {
            BOOST_ASSERT( m_env != 0 );
            return *m_env;
        }
        const Environment& environment() const
        {
            BOOST_ASSERT( m_env != 0 );
            return *m_env;
        }

    private:
        Plugin::Loader*     m_pluginLoader;
        Plugin::Manager     m_pluginManager;
        Environment*        m_env;
    };
}; };

#endif // MESCALINE_AUDIO_ENGINE_H_INCLUDED
<commit_msg>Remove OSCPacket class<commit_after>#ifndef MESCALINE_AUDIO_ENGINE_H_INCLUDED
#define MESCALINE_AUDIO_ENGINE_H_INCLUDED

#include <Mescaline/Audio.hpp>
#include <Mescaline/Audio/AudioBus.hpp>
#include <Mescaline/Audio/IO/Client.hpp>
#include <Mescaline/Audio/Node.hpp>
#include <Mescaline/Audio/Plugin/API.h>
#include <Mescaline/Audio/SynthDef.hpp>
#include <Mescaline/Exception.hpp>
#include <Mescaline/Memory/Manager.hpp>

#include <boost/container/vector.hpp>
#include <boost/cstdint.hpp>
#include <boost/lockfree/fifo.hpp>
#include <boost/lockfree/ringbuffer.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/thread/thread.hpp>
#include <boost/utility.hpp>

#include <oscpp/server.hpp>

#include <bitset>
#include <string>
#include <vector>

namespace Mescaline { namespace Audio
{
    using namespace Memory;

    // typedef int32_t ControlBusId;

    // class ControlBusId
    // {
    // public:
    //     ControlBusId()
    //         : m_id(-1)
    //     { }
    //     ControlBusId(
    //     uint32_t id() const { return m_id; }
    //     operator bool () const { return m_id != -1; }
    //
    // private:
    //     uint32_t m_id;
    // };

    // class ControlBus : boost::noncopyable
    // {
    // public:
    //     typedef sample_t ValueType;
    //
    // private:
    //     BusId       m_id;
    //     Epoch       m_epoch;
    //     ValueType   m_data;
    // };

    struct EngineException : virtual Mescaline::Exception { };
    struct InvalidNodeId : virtual EngineException { };
    struct DuplicateNodeId : virtual EngineException { };
    struct ErrorInfoNodeIdTag {};
    typedef boost::error_info<ErrorInfoNodeIdTag, NodeId> ErrorInfoNodeId;

    class Node;

    class NodeMap
    {
        typedef std::vector<Node*> Nodes;

    public:
        typedef Nodes::const_reference const_reference;

        NodeMap(size_t maxNumNodes)
            : m_nodes(maxNumNodes, 0)
        { }

        void insert(Node* node);
        const_reference lookup(const NodeId& nodeId) const { return m_nodes.at(nodeId); }
        void release(const NodeId& nodeId);

    private:
        Nodes m_nodes;
    };

    class Group;
    class PluginInterface;

//    class Message
//    {
//    public:
//        static const size_t kMaxPayloadBytes = 128;
//
//        typedef bool (*PerformFunc)(void*);
//
//        Message()
//            : m_perform(0)
//        {
//#ifndef NDEBUG
//            memset(m_payload, 0, kMaxPayloadBytes);
//#endif
//        }
//        Message(const Message& other)
//        {
//            m_perform = other.m_perform;
//            memcpy(m_payload, other.m_payload, kMaxPayloadBytes);
//        }
//
//        char* payload() { return m_payload.bytes; }
//
//    private:
//        bool (*m_perform)(void*);
//        char m_payload[kMaxPayloadBytes];
//    };

    class Environment : public boost::noncopyable
    {
    public:
        struct Options
        {
            Options()
                : maxNumNodes(1024)
                , maxNumAudioBuses(128)
                , maxNumControlBuses(4096)
                , sampleRate(44100)
                , blockSize(64)
                , numHardwareInputChannels(2)
                , numHardwareOutputChannels(2)
            { }

            size_t maxNumNodes;
            size_t maxNumAudioBuses;
            size_t maxNumControlBuses;
            size_t sampleRate;
            size_t blockSize;
            size_t numHardwareInputChannels;
            size_t numHardwareOutputChannels;
        };

        Environment(Plugin::Manager& pluginManager, const Options& options);
        ~Environment();

        void initModule(MescalineInitFunc moduleInitFunc);

        const Plugin::Manager::PluginHandle& lookupSynthDef(const char* name) { return m_synthDefs.lookup(name); }
        void registerSynthDef(SynthDef* synthDef) { /* m_synthDefs.insert(synthDef); */ }

        Group* rootNode() { return m_rootNode; }
        const NodeMap& nodes() const { return m_nodes; }

        size_t sampleRate() const { return m_sampleRate; }
        size_t blockSize() const { return m_blockSize; }

        AudioBus& audioBus(AudioBusId busId)
        {
            switch (busId.scope()) {
                case AudioBusId::kInput:
                    return m_audioInputChannels[busId.id()];
                case AudioBusId::kOutput:
                    return m_audioOutputChannels[busId.id()];
                case AudioBusId::kInternal:
                    return m_audioBuses[busId.id()];
            }
            BOOST_THROW_EXCEPTION(InvalidInput());
        }

        RTMemoryManager& rtMem() { return m_rtMem; }

        const Epoch& epoch() const { return m_epoch; }

        void process(size_t numFrames, sample_t** inputs, sample_t** outputs);

        typedef boost::lockfree::ringbuffer<OSCPacket*, 1024> CommandFifo;
//        typedef boost::lockfree::fifo<Message> MessageFifo;

    protected:
        friend class Node;

        void insertNode(Node* node);
        void releaseNodeId(const NodeId& nodeId);

    private:
        const size_t                m_sampleRate;
        const size_t                m_blockSize;
        PluginInterface*            m_pluginInterface;
        RTMemoryManager             m_rtMem;
//        SynthDefMap                 m_synthDefs;
        Plugin::Manager&            m_synthDefs;
        Group*                      m_rootNode;
        NodeMap                     m_nodes;
        boost::ptr_vector<ExternalAudioBus> m_audioInputChannels;
        boost::ptr_vector<ExternalAudioBus> m_audioOutputChannels;
        boost::ptr_vector<InternalAudioBus> m_audioBuses;
        Epoch                       m_epoch;
//        CommandFifo                 m_commandFifo;
//        MessageFifo                 m_nrtToRtFifo;
//        MessageFifo                 m_rtToNrtFifo;
    };

    // This is the interface that plugins use (via its function pointers,
    // inherited from MescalineHost).
    class PluginInterface : public MescalineHost
    {
    public:
        PluginInterface(Environment& env)
            : m_env(env)
        {
            fGetSampleRate = &GetSampleRate;
            fRegisterSynthDef = &RegisterSynthDef;
        }

    private:
        static unsigned int GetSampleRate(const MescalineHost* self)
            { return static_cast<const PluginInterface*>(self)->m_env.sampleRate(); }
        static void RegisterSynthDef(MescalineHost* self, MescalineSynthDef* synthDef)
            { static_cast<PluginInterface*>(self)->m_env.registerSynthDef(new SynthDef(self, synthDef)); }

    private:
        Environment& m_env;
    };

    class Engine : public IO::Client
    {
    public:
        Engine(Plugin::Loader* pluginLoader);
        virtual ~Engine();

        virtual void configure(const IO::Driver& driver);
        virtual void process(size_t numFrames, sample_t** inputs, sample_t** outputs);

        Environment& environment()
        {
            BOOST_ASSERT( m_env != 0 );
            return *m_env;
        }
        const Environment& environment() const
        {
            BOOST_ASSERT( m_env != 0 );
            return *m_env;
        }

    private:
        Plugin::Loader*     m_pluginLoader;
        Plugin::Manager     m_pluginManager;
        Environment*        m_env;
    };
}; };

#endif // MESCALINE_AUDIO_ENGINE_H_INCLUDED
<|endoftext|>


<commit_before>
#include "rdb_protocol/proto_utils.hpp"

std::string cJSON_print_primary(cJSON *json, const query_language::backtrace_t &backtrace) {
    guarantee_debug_throw_release(json, backtrace);
    if (json->type != cJSON_Number && json->type != cJSON_String) {
        throw query_language::runtime_exc_t(strprintf("Primary key must be a number or a string, not %s",
                                      cJSON_print_std_string(json).c_str()), backtrace);
    }
    std::string s = cJSON_print_lexicographic(json);
    if (s.size() > MAX_KEY_SIZE) {
        throw query_language::runtime_exc_t(strprintf("Primary key too long (max %d characters): %s",
                                                      MAX_KEY_SIZE-1, cJSON_print_std_string(json).c_str()), backtrace);
    }
    return s;
}

<commit_msg>Adjusted the indentation of something.<commit_after>
#include "rdb_protocol/proto_utils.hpp"

std::string cJSON_print_primary(cJSON *json, const query_language::backtrace_t &backtrace) {
    guarantee_debug_throw_release(json, backtrace);
    if (json->type != cJSON_Number && json->type != cJSON_String) {
        throw query_language::runtime_exc_t(strprintf("Primary key must be a number or a string, not %s",
                                                      cJSON_print_std_string(json).c_str()), backtrace);
    }
    std::string s = cJSON_print_lexicographic(json);
    if (s.size() > MAX_KEY_SIZE) {
        throw query_language::runtime_exc_t(strprintf("Primary key too long (max %d characters): %s",
                                                      MAX_KEY_SIZE-1, cJSON_print_std_string(json).c_str()), backtrace);
    }
    return s;
}

<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of meegotouch-controlpanelapplets.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "resetwidget.h"

#include <MContainer>
#include <MLayout>
#include <MLinearLayoutPolicy>
#include <MButton>
#include <MDialog>
#include <MMessageBox>

#undef DEBUG
#include "../debug.h"

ResetWidget::ResetWidget (
        ResetBusinessLogic     *resetBusinessLogic,
        QGraphicsWidget        *parent) :
    DcpWidget (parent),
    m_ResetBusinessLogic (resetBusinessLogic),
    m_currentPlan (None)
{
    createContent();

    connect (resetBusinessLogic, SIGNAL (gotAccess ()),
             this, SLOT (doTheWork ()));
}

ResetWidget::~ResetWidget ()
{
}

void
ResetWidget::createContent ()
{
    MLayout             *layout;
    MLinearLayoutPolicy *policy;
    MButton             *restoreButton;
    MButton             *clearButton;
    /*
     *
     */
    layout = new MLayout;
    policy = new MLinearLayoutPolicy (layout, Qt::Vertical);
    policy->setContentsMargins (0., 0., 0., 0.);
    policy->setSpacing (0.);

    /*
     *
     */
    //% "Restore original settings"
    restoreButton = new MButton (qtTrId("qtn_rset_restore"));
    restoreButton->setStyleName ("CommonTopButtonInverted");
    restoreButton->setObjectName ("ResetAppletRFSButton");
    connect (restoreButton, SIGNAL(clicked()),
            this, SLOT(restoreActivated()));

    /*
     * The second button.
     */
    //% "Clear device"
    clearButton = new MButton (qtTrId("qtn_rset_clear"));
    clearButton->setStyleName ("CommonBottomButtonInverted");
    clearButton->setObjectName ("ResetAppletCUDButton");
    connect (clearButton, SIGNAL(clicked()),
            this, SLOT(clearActivated()));

    addButtonContainer (policy, restoreButton, clearButton);

    /*
     *
     */
    layout->setPolicy (policy);
    setLayout (layout);
}

void
ResetWidget::addButtonContainer (
            MLinearLayoutPolicy *mainLayout,
            MButton             *button1,
            MButton             *button2)
{
    MContainer          *container;
    MLayout             *layout;
    MLinearLayoutPolicy *landscapePolicy;
    MLinearLayoutPolicy *portraitPolicy;

    /*
     * Creating a lcontainer and a layout.
     */
    container = new MContainer (this);
    container->setStyleName ("CommonLargePanelInverted");
    container->setHeaderVisible (false);

    layout = new MLayout;
    layout->setContentsMargins (0., 0., 0., 0.);

    landscapePolicy = new MLinearLayoutPolicy (layout, Qt::Horizontal);
    landscapePolicy->setContentsMargins (0., 0., 0., 0.);

    portraitPolicy = new MLinearLayoutPolicy (layout, Qt::Vertical);
    portraitPolicy->setContentsMargins (0., 0., 0., 0.);

    layout->setLandscapePolicy (landscapePolicy);
    layout->setPortraitPolicy (portraitPolicy);

    container->centralWidget()->setLayout (layout);

    /*
     * Adding the buttons to the layouts
     */
    landscapePolicy->addStretch ();
    landscapePolicy->addItem (button1);
    landscapePolicy->addItem (button2);
    landscapePolicy->addStretch ();

    portraitPolicy->addItem (button1);
    portraitPolicy->setAlignment (button1, Qt::AlignHCenter);
    portraitPolicy->addItem (button2);
    portraitPolicy->setAlignment (button2, Qt::AlignHCenter);

    /*
     *
     */
    mainLayout->addItem (container);
    mainLayout->setStretchFactor (container, 0);
}

void
ResetWidget::restoreActivated ()
{
    MDialog   *dialog;
    int        retval;

    //% "Restore original settings? The device will reboot, temporarily "
    //% "disabling all functions, including emergency calls. "
    //% "User created-content will be unaffected."
    QString    question = QString ("
") +
                          qtTrId("qtn_rset_restore_query") + "
";
    // It is a bit ugly, but translations contains \n stuffs:
    question.replace ("\\n", "
");
    question.replace ("\n", "
");

    SYS_DEBUG ("");
    dialog = new MMessageBox ("", question, M::YesButton | M::NoButton);
    dialog->setTitleBarVisible (false);

    retval = dialog->exec();
    switch (retval) {
        case M::YesButton:
            SYS_DEBUG ("YES");
            m_currentPlan = ResetSettings;
            m_ResetBusinessLogic->getAccess ();
            break;

        case M::NoButton:
            SYS_DEBUG ("NO");
            /*
             * We do not have to do anything.
             */
            break;
    }
}

void
ResetWidget::clearActivated ()
{
    MDialog   *dialog;
    int        retval;

    //% "Clear all user data and restore original settings? "
    //% "The device will reboot, temporarily disabling all "
    //% "functions, including emergency calls."
    QString    question = QString ("
") +
                          qtTrId("qtn_rset_clear_query") + "
";
    question.replace ("\\n", "
");
    question.replace ("\n", "
");

    SYS_DEBUG ("");
    dialog = new MMessageBox ("", question, M::YesButton | M::NoButton);
    dialog->setTitleBarVisible (false);

    retval = dialog->exec();
    switch (retval) {
        case M::YesButton:
            SYS_DEBUG ("YES");
            m_currentPlan = ClearData;
            m_ResetBusinessLogic->getAccess ();
            break;

        case M::NoButton:
            SYS_DEBUG ("NO");
            /*
             * We do not have to do anything.
             */
            break;
    }
}

void
ResetWidget::doTheWork ()
{
    switch (m_currentPlan)
    {
        case ResetSettings:
            m_ResetBusinessLogic->performRestoreSettings();
            break;
        case ClearData:
            m_ResetBusinessLogic->performClearData();
            break;
        default:
            SYS_WARNING ("Got access, but no plan ?!");
            break;
    }
    m_currentPlan = None;
}

<commit_msg>Changes: add title for reset applet dialogs<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of meegotouch-controlpanelapplets.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "resetwidget.h"

#include <MContainer>
#include <MLayout>
#include <MLinearLayoutPolicy>
#include <MButton>
#include <MDialog>
#include <MMessageBox>

#undef DEBUG
#include "../debug.h"

ResetWidget::ResetWidget (
        ResetBusinessLogic     *resetBusinessLogic,
        QGraphicsWidget        *parent) :
    DcpWidget (parent),
    m_ResetBusinessLogic (resetBusinessLogic),
    m_currentPlan (None)
{
    createContent();

    connect (resetBusinessLogic, SIGNAL (gotAccess ()),
             this, SLOT (doTheWork ()));
}

ResetWidget::~ResetWidget ()
{
}

void
ResetWidget::createContent ()
{
    MLayout             *layout;
    MLinearLayoutPolicy *policy;
    MButton             *restoreButton;
    MButton             *clearButton;
    /*
     *
     */
    layout = new MLayout;
    policy = new MLinearLayoutPolicy (layout, Qt::Vertical);
    policy->setContentsMargins (0., 0., 0., 0.);
    policy->setSpacing (0.);

    /*
     *
     */
    //% "Restore original settings"
    restoreButton = new MButton (qtTrId("qtn_rset_restore"));
    restoreButton->setStyleName ("CommonTopButtonInverted");
    restoreButton->setObjectName ("ResetAppletRFSButton");
    connect (restoreButton, SIGNAL(clicked()),
            this, SLOT(restoreActivated()));

    /*
     * The second button.
     */
    //% "Clear device"
    clearButton = new MButton (qtTrId("qtn_rset_clear"));
    clearButton->setStyleName ("CommonBottomButtonInverted");
    clearButton->setObjectName ("ResetAppletCUDButton");
    connect (clearButton, SIGNAL(clicked()),
            this, SLOT(clearActivated()));

    addButtonContainer (policy, restoreButton, clearButton);

    /*
     *
     */
    layout->setPolicy (policy);
    setLayout (layout);
}

void
ResetWidget::addButtonContainer (
            MLinearLayoutPolicy *mainLayout,
            MButton             *button1,
            MButton             *button2)
{
    MContainer          *container;
    MLayout             *layout;
    MLinearLayoutPolicy *landscapePolicy;
    MLinearLayoutPolicy *portraitPolicy;

    /*
     * Creating a lcontainer and a layout.
     */
    container = new MContainer (this);
    container->setStyleName ("CommonLargePanelInverted");
    container->setHeaderVisible (false);

    layout = new MLayout;
    layout->setContentsMargins (0., 0., 0., 0.);

    landscapePolicy = new MLinearLayoutPolicy (layout, Qt::Horizontal);
    landscapePolicy->setContentsMargins (0., 0., 0., 0.);

    portraitPolicy = new MLinearLayoutPolicy (layout, Qt::Vertical);
    portraitPolicy->setContentsMargins (0., 0., 0., 0.);

    layout->setLandscapePolicy (landscapePolicy);
    layout->setPortraitPolicy (portraitPolicy);

    container->centralWidget()->setLayout (layout);

    /*
     * Adding the buttons to the layouts
     */
    landscapePolicy->addStretch ();
    landscapePolicy->addItem (button1);
    landscapePolicy->addItem (button2);
    landscapePolicy->addStretch ();

    portraitPolicy->addItem (button1);
    portraitPolicy->setAlignment (button1, Qt::AlignHCenter);
    portraitPolicy->addItem (button2);
    portraitPolicy->setAlignment (button2, Qt::AlignHCenter);

    /*
     *
     */
    mainLayout->addItem (container);
    mainLayout->setStretchFactor (container, 0);
}

void
ResetWidget::restoreActivated ()
{
    MDialog   *dialog;
    int        retval;

    //% "Restore original settings? The device will reboot, temporarily "
    //% "disabling all functions, including emergency calls. "
    //% "User created-content will be unaffected."
    QString    question = QString ("
") +
                          qtTrId("qtn_rset_restore_query") + "
";
    // It is a bit ugly, but translations contains \n stuffs:
    question.replace ("\\n", "
");
    question.replace ("\n", "
");

    SYS_DEBUG ("");
    //% "Restore original settings?"
    dialog = new MMessageBox (qtTrId ("qtn_rset_restore_query_title"),
                              question, M::YesButton | M::NoButton);
    dialog->setTitleBarVisible (false);

    retval = dialog->exec();
    switch (retval) {
        case M::YesButton:
            SYS_DEBUG ("YES");
            m_currentPlan = ResetSettings;
            m_ResetBusinessLogic->getAccess ();
            break;

        case M::NoButton:
            SYS_DEBUG ("NO");
            /*
             * We do not have to do anything.
             */
            break;
    }
}

void
ResetWidget::clearActivated ()
{
    MDialog   *dialog;
    int        retval;

    //% "Clear all user data and restore original settings? "
    //% "The device will reboot, temporarily disabling all "
    //% "functions, including emergency calls."
    QString    question = QString ("
") +
                          qtTrId("qtn_rset_clear_query") + "
";
    question.replace ("\\n", "
");
    question.replace ("\n", "
");

    SYS_DEBUG ("");
    //% "Clear all data?"
    dialog = new MMessageBox (qtTrId ("qtn_rset_clear_query_title"),
                              question, M::YesButton | M::NoButton);
    dialog->setTitleBarVisible (false);

    retval = dialog->exec();
    switch (retval) {
        case M::YesButton:
            SYS_DEBUG ("YES");
            m_currentPlan = ClearData;
            m_ResetBusinessLogic->getAccess ();
            break;

        case M::NoButton:
            SYS_DEBUG ("NO");
            /*
             * We do not have to do anything.
             */
            break;
    }
}

void
ResetWidget::doTheWork ()
{
    switch (m_currentPlan)
    {
        case ResetSettings:
            m_ResetBusinessLogic->performRestoreSettings();
            break;
        case ClearData:
            m_ResetBusinessLogic->performClearData();
            break;
        default:
            SYS_WARNING ("Got access, but no plan ?!");
            break;
    }
    m_currentPlan = None;
}

<|endoftext|>


<commit_before>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * For simplicity, this file contains the accept implementation of all PlanIterators.
 * The majority of accept's can be implemented with a macro.
 **/

#include "runtime/visitors/planitervisitor.h"

#include "runtime/core/constructors.h"
#include "runtime/core/item_iterator.h"
#include "runtime/core/var_iterators.h"
#include "runtime/core/path_iterators.h"
#include "runtime/core/path.h"
#include "runtime/core/nodeid_iterators.h"
#include "runtime/core/sequencetypes.h"
#include "runtime/core/fncall_iterator.h"
#include "runtime/core/trycatch.h"
#include "runtime/core/gflwor/tuplestream_iterator.h"
#include "runtime/core/gflwor/for_iterator.h"
#include "runtime/core/gflwor/outerfor_iterator.h"
#include "runtime/core/gflwor/let_iterator.h"
#include "runtime/core/gflwor/where_iterator.h"
#include "runtime/core/gflwor/count_iterator.h"
#include "runtime/core/gflwor/tuplesource_iterator.h"
#include "runtime/booleans/BooleanImpl.h"
#include "runtime/validate/validate.h"
#include "runtime/strings/StringsImpl.h"
#include "runtime/numerics/NumericsImpl.h"
#include "runtime/indexing/value_index_builder.h"
#include "runtime/indexing/value_index_probe.h"
#include "runtime/accessors/AccessorsImpl.h"
#include "runtime/sequences/SequencesImpl.h"
#include "runtime/dateTime/DurationsDatesTimes.h"
#include "runtime/debug/debug_iterators.h"
#include "runtime/update/update.h"
#include "runtime/qnames/QNamesImpl.h"
#ifdef ZORBA_WITH_REST
#include "runtime/rest/rest.h"
#endif
#ifdef ZORBA_WITH_EMAIL
#include "runtime/email/EmailImpl.h"
#endif
#include "store/api/iterator.h"

#include "context/static_context.h"
#include "context/namespace_context.h"

#define NOARY_ACCEPT(type) \
  void type::accept(PlanIterVisitor& v) const { \
    v.beginVisit(*this); \
    v.endVisit(*this); \
  }

#define UNARY_ACCEPT(type) \
  void type::accept(PlanIterVisitor& v) const { \
    v.beginVisit(*this); \
    theChild->accept(v); \
    v.endVisit(*this); \
  }

#define BINARY_ACCEPT(type) \
  void type::accept(PlanIterVisitor& v) const { \
    v.beginVisit(*this); \
    theChild0->accept(v); \
    theChild1->accept(v); \
    v.endVisit(*this); \
  }

#define NARY_ACCEPT(type) \
  void type::accept(PlanIterVisitor& v) const { \
    v.beginVisit(*this); \
    std::vector<PlanIter_t>::const_iterator lIter = theChildren.begin(); \
    std::vector<PlanIter_t>::const_iterator lEnd = theChildren.end(); \
    for ( ; lIter != lEnd; ++lIter ) { \
      ( *lIter )->accept ( v ); \
    } \
    v.endVisit(*this); \
  }

namespace zorba {

  // noary iterators (iterators without children)
  NOARY_ACCEPT(LetVarIterator);
  NOARY_ACCEPT(ZorNumGen);
  NOARY_ACCEPT(EmptyIterator);
  NOARY_ACCEPT(SingletonIterator);
  NOARY_ACCEPT(ForVarIterator);
  NOARY_ACCEPT(flwor::TupleSourceIterator);

  // unary iterators
  UNARY_ACCEPT(NodeDistinctIterator);
  UNARY_ACCEPT(NodeSortIterator);
#ifdef PATH_ITERATOR
  UNARY_ACCEPT(PathIterator);
#endif
  UNARY_ACCEPT(SelfAxisIterator);
  UNARY_ACCEPT(AttributeAxisIterator);
  UNARY_ACCEPT(ParentAxisIterator);
  UNARY_ACCEPT(AncestorAxisIter);
  UNARY_ACCEPT(AncestorReverseAxisIter);
  UNARY_ACCEPT(AncestorSelfAxisIter);
  UNARY_ACCEPT(AncestorSelfReverseAxisIter);
  UNARY_ACCEPT(RSiblingAxisIter);
  UNARY_ACCEPT(LSiblingAxisIter);
  UNARY_ACCEPT(LSiblingReverseAxisIter);
  UNARY_ACCEPT(ChildAxisIterator);
  UNARY_ACCEPT(DescendantAxisIterator);
  UNARY_ACCEPT(DescendantSelfAxisIterator);
  UNARY_ACCEPT(PrecedingAxisIterator);
  UNARY_ACCEPT(PrecedingReverseAxisIter);
  UNARY_ACCEPT(FollowingAxisIterator);
  UNARY_ACCEPT(FnBooleanIterator);
#ifndef ZORBA_NO_XMLSCHEMA
  UNARY_ACCEPT(ValidateIterator);
#endif
  UNARY_ACCEPT(InstanceOfIterator);
  UNARY_ACCEPT(EnclosedIterator);
  UNARY_ACCEPT(FnDocIterator);
  UNARY_ACCEPT(OpNumericUnaryIterator);
  UNARY_ACCEPT(TextIterator);
  UNARY_ACCEPT(CommentIterator);
  UNARY_ACCEPT(CastIterator);
  UNARY_ACCEPT(NameCastIterator);
  UNARY_ACCEPT(CastableIterator);
  UNARY_ACCEPT(PromoteIterator);
  UNARY_ACCEPT(TreatIterator);
  UNARY_ACCEPT(PrefixFromQNameIterator);
  UNARY_ACCEPT(LocalNameFromQNameIterator);
  UNARY_ACCEPT(NamespaceUriFromQNameIterator);
  UNARY_ACCEPT(InScopePrefixesIterator);
  UNARY_ACCEPT(DocumentIterator);
  UNARY_ACCEPT(DocumentContentIterator);
  UNARY_ACCEPT(FnAdjustToTimeZoneIterator_1);
  UNARY_ACCEPT(DeleteIterator);
  UNARY_ACCEPT(FnDataIterator);
  UNARY_ACCEPT(flwor::CountIterator);
  UNARY_ACCEPT(CreateValueIndex);
  UNARY_ACCEPT(DropValueIndex);
  UNARY_ACCEPT(ValueIndexInsertSessionOpener);
  UNARY_ACCEPT(ValueIndexInsertSessionCloser);

  // binary iterators
  BINARY_ACCEPT(LogicIterator);
  BINARY_ACCEPT(CompareIterator);
  BINARY_ACCEPT(FnDateTimeConstructorIterator);
  BINARY_ACCEPT(AttributeIterator);
  BINARY_ACCEPT(PiIterator);
  BINARY_ACCEPT(QNameEqualIterator);
  BINARY_ACCEPT(ResolveQNameIterator);
  BINARY_ACCEPT(QNameIterator);
  BINARY_ACCEPT(FnAdjustToTimeZoneIterator_2);
  BINARY_ACCEPT(InsertIterator);
  BINARY_ACCEPT(ReplaceIterator);
  BINARY_ACCEPT(RenameIterator);
  BINARY_ACCEPT(flwor::TupleStreamIterator);
  BINARY_ACCEPT(flwor::OuterForIterator);
  BINARY_ACCEPT(flwor::WhereIterator);

  // nary iterators
  NARY_ACCEPT(ValueIndexBuilder);
  NARY_ACCEPT(ValueIndexPointProbe);
  NARY_ACCEPT(ValueIndexRangeProbe);
  NARY_ACCEPT(FnDistinctValuesIterator);
  NARY_ACCEPT(UDFunctionCallIterator);
  NARY_ACCEPT(StatelessExtFunctionCallIterator);
  NARY_ACCEPT(FnMinMaxIterator);
  NARY_ACCEPT(HashSemiJoinIterator);
  NARY_ACCEPT(SortSemiJoinIterator);
  NARY_ACCEPT(FnStringIterator);
  NARY_ACCEPT(FnConcatIterator);

  // special iterators
  void ElementIterator::accept(PlanIterVisitor& v) const
  {
    v.beginVisit(*this);

    if (theQNameIter != 0)
      theQNameIter->accept(v);

    if (theAttributesIter != 0)
      theAttributesIter->accept(v);

    if (theChildrenIter != 0)
      theChildrenIter->accept(v);

    if (theNamespacesIter != 0)
      theNamespacesIter->accept(v);

    v.endVisit(*this);
  }

  void IfThenElseIterator::accept(PlanIterVisitor& v) const {
    v.beginVisit(*this);
    theCondIter->accept ( v );
    theThenIter->accept ( v );
    theElseIter->accept ( v );
    v.endVisit(*this);
  }

  void TransformIterator::accept(PlanIterVisitor &v) const {
    v.beginVisit(*this);
    CopyClause::const_iter_t lIter = theCopyClauses.begin();
    CopyClause::const_iter_t lEnd = theCopyClauses.end();
    for ( ; lIter != lEnd; ++lIter ) {
      lIter->theInput->accept ( v );
    }
    theModifyIter->accept(v);
    theReturnIter->accept(v);
    v.endVisit(*this);
  }
} /* namespace zorba */
<commit_msg>Removed unused code.<commit_after>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * For simplicity, this file contains the accept implementation of all PlanIterators.
 * The majority of accept's can be implemented with a macro.
 **/

#include "runtime/visitors/planitervisitor.h"

#include "runtime/core/constructors.h"
#include "runtime/core/item_iterator.h"
#include "runtime/core/var_iterators.h"
#include "runtime/core/path_iterators.h"
#include "runtime/core/path.h"
#include "runtime/core/nodeid_iterators.h"
#include "runtime/core/sequencetypes.h"
#include "runtime/core/fncall_iterator.h"
#include "runtime/core/trycatch.h"
#include "runtime/core/gflwor/tuplestream_iterator.h"
#include "runtime/core/gflwor/for_iterator.h"
#include "runtime/core/gflwor/outerfor_iterator.h"
#include "runtime/core/gflwor/let_iterator.h"
#include "runtime/core/gflwor/where_iterator.h"
#include "runtime/core/gflwor/count_iterator.h"
#include "runtime/core/gflwor/tuplesource_iterator.h"
#include "runtime/booleans/BooleanImpl.h"
#include "runtime/validate/validate.h"
#include "runtime/strings/StringsImpl.h"
#include "runtime/numerics/NumericsImpl.h"
#include "runtime/indexing/value_index_builder.h"
#include "runtime/indexing/value_index_probe.h"
#include "runtime/accessors/AccessorsImpl.h"
#include "runtime/sequences/SequencesImpl.h"
#include "runtime/dateTime/DurationsDatesTimes.h"
#include "runtime/debug/debug_iterators.h"
#include "runtime/update/update.h"
#include "runtime/qnames/QNamesImpl.h"
#ifdef ZORBA_WITH_REST
#include "runtime/rest/rest.h"
#endif

#include "store/api/iterator.h"

#include "context/static_context.h"
#include "context/namespace_context.h"

#define NOARY_ACCEPT(type) \
  void type::accept(PlanIterVisitor& v) const { \
    v.beginVisit(*this); \
    v.endVisit(*this); \
  }

#define UNARY_ACCEPT(type) \
  void type::accept(PlanIterVisitor& v) const { \
    v.beginVisit(*this); \
    theChild->accept(v); \
    v.endVisit(*this); \
  }

#define BINARY_ACCEPT(type) \
  void type::accept(PlanIterVisitor& v) const { \
    v.beginVisit(*this); \
    theChild0->accept(v); \
    theChild1->accept(v); \
    v.endVisit(*this); \
  }

#define NARY_ACCEPT(type) \
  void type::accept(PlanIterVisitor& v) const { \
    v.beginVisit(*this); \
    std::vector<PlanIter_t>::const_iterator lIter = theChildren.begin(); \
    std::vector<PlanIter_t>::const_iterator lEnd = theChildren.end(); \
    for ( ; lIter != lEnd; ++lIter ) { \
      ( *lIter )->accept ( v ); \
    } \
    v.endVisit(*this); \
  }

namespace zorba {

  // noary iterators (iterators without children)
  NOARY_ACCEPT(LetVarIterator);
  NOARY_ACCEPT(ZorNumGen);
  NOARY_ACCEPT(EmptyIterator);
  NOARY_ACCEPT(SingletonIterator);
  NOARY_ACCEPT(ForVarIterator);
  NOARY_ACCEPT(flwor::TupleSourceIterator);

  // unary iterators
  UNARY_ACCEPT(NodeDistinctIterator);
  UNARY_ACCEPT(NodeSortIterator);
#ifdef PATH_ITERATOR
  UNARY_ACCEPT(PathIterator);
#endif
  UNARY_ACCEPT(SelfAxisIterator);
  UNARY_ACCEPT(AttributeAxisIterator);
  UNARY_ACCEPT(ParentAxisIterator);
  UNARY_ACCEPT(AncestorAxisIter);
  UNARY_ACCEPT(AncestorReverseAxisIter);
  UNARY_ACCEPT(AncestorSelfAxisIter);
  UNARY_ACCEPT(AncestorSelfReverseAxisIter);
  UNARY_ACCEPT(RSiblingAxisIter);
  UNARY_ACCEPT(LSiblingAxisIter);
  UNARY_ACCEPT(LSiblingReverseAxisIter);
  UNARY_ACCEPT(ChildAxisIterator);
  UNARY_ACCEPT(DescendantAxisIterator);
  UNARY_ACCEPT(DescendantSelfAxisIterator);
  UNARY_ACCEPT(PrecedingAxisIterator);
  UNARY_ACCEPT(PrecedingReverseAxisIter);
  UNARY_ACCEPT(FollowingAxisIterator);
  UNARY_ACCEPT(FnBooleanIterator);
#ifndef ZORBA_NO_XMLSCHEMA
  UNARY_ACCEPT(ValidateIterator);
#endif
  UNARY_ACCEPT(InstanceOfIterator);
  UNARY_ACCEPT(EnclosedIterator);
  UNARY_ACCEPT(FnDocIterator);
  UNARY_ACCEPT(OpNumericUnaryIterator);
  UNARY_ACCEPT(TextIterator);
  UNARY_ACCEPT(CommentIterator);
  UNARY_ACCEPT(CastIterator);
  UNARY_ACCEPT(NameCastIterator);
  UNARY_ACCEPT(CastableIterator);
  UNARY_ACCEPT(PromoteIterator);
  UNARY_ACCEPT(TreatIterator);
  UNARY_ACCEPT(PrefixFromQNameIterator);
  UNARY_ACCEPT(LocalNameFromQNameIterator);
  UNARY_ACCEPT(NamespaceUriFromQNameIterator);
  UNARY_ACCEPT(InScopePrefixesIterator);
  UNARY_ACCEPT(DocumentIterator);
  UNARY_ACCEPT(DocumentContentIterator);
  UNARY_ACCEPT(FnAdjustToTimeZoneIterator_1);
  UNARY_ACCEPT(DeleteIterator);
  UNARY_ACCEPT(FnDataIterator);
  UNARY_ACCEPT(flwor::CountIterator);
  UNARY_ACCEPT(CreateValueIndex);
  UNARY_ACCEPT(DropValueIndex);
  UNARY_ACCEPT(ValueIndexInsertSessionOpener);
  UNARY_ACCEPT(ValueIndexInsertSessionCloser);

  // binary iterators
  BINARY_ACCEPT(LogicIterator);
  BINARY_ACCEPT(CompareIterator);
  BINARY_ACCEPT(FnDateTimeConstructorIterator);
  BINARY_ACCEPT(AttributeIterator);
  BINARY_ACCEPT(PiIterator);
  BINARY_ACCEPT(QNameEqualIterator);
  BINARY_ACCEPT(ResolveQNameIterator);
  BINARY_ACCEPT(QNameIterator);
  BINARY_ACCEPT(FnAdjustToTimeZoneIterator_2);
  BINARY_ACCEPT(InsertIterator);
  BINARY_ACCEPT(ReplaceIterator);
  BINARY_ACCEPT(RenameIterator);
  BINARY_ACCEPT(flwor::TupleStreamIterator);
  BINARY_ACCEPT(flwor::OuterForIterator);
  BINARY_ACCEPT(flwor::WhereIterator);

  // nary iterators
  NARY_ACCEPT(ValueIndexBuilder);
  NARY_ACCEPT(ValueIndexPointProbe);
  NARY_ACCEPT(ValueIndexRangeProbe);
  NARY_ACCEPT(FnDistinctValuesIterator);
  NARY_ACCEPT(UDFunctionCallIterator);
  NARY_ACCEPT(StatelessExtFunctionCallIterator);
  NARY_ACCEPT(FnMinMaxIterator);
  NARY_ACCEPT(HashSemiJoinIterator);
  NARY_ACCEPT(SortSemiJoinIterator);
  NARY_ACCEPT(FnStringIterator);
  NARY_ACCEPT(FnConcatIterator);

  // special iterators
  void ElementIterator::accept(PlanIterVisitor& v) const
  {
    v.beginVisit(*this);

    if (theQNameIter != 0)
      theQNameIter->accept(v);

    if (theAttributesIter != 0)
      theAttributesIter->accept(v);

    if (theChildrenIter != 0)
      theChildrenIter->accept(v);

    if (theNamespacesIter != 0)
      theNamespacesIter->accept(v);

    v.endVisit(*this);
  }

  void IfThenElseIterator::accept(PlanIterVisitor& v) const {
    v.beginVisit(*this);
    theCondIter->accept ( v );
    theThenIter->accept ( v );
    theElseIter->accept ( v );
    v.endVisit(*this);
  }

  void TransformIterator::accept(PlanIterVisitor &v) const {
    v.beginVisit(*this);
    CopyClause::const_iter_t lIter = theCopyClauses.begin();
    CopyClause::const_iter_t lEnd = theCopyClauses.end();
    for ( ; lIter != lEnd; ++lIter ) {
      lIter->theInput->accept ( v );
    }
    theModifyIter->accept(v);
    theReturnIter->accept(v);
    v.endVisit(*this);
  }
} /* namespace zorba */
<|endoftext|>


<commit_before>#include "settings_manager.hpp"

#include <cstdlib>
#include <cstring>

#include <map>
#include <string>

#include <pugixml.hpp>

#include <base/error.hpp>
#include <base/macros.hpp>

namespace {

std::string BuildKey(const pugi::xml_node& node) {
  CHECK(node.type() == pugi::node_element);
  if(node.parent().type() == pugi::node_document) {
    return std::string(node.name());
  } else if(node.parent().type() == pugi::node_element) {
    return BuildKey(node.parent()) + "." + std::string(node.name());
  }
  CHECK(false);
  return "";
}

struct SettingsWalker : public pugi::xml_tree_walker {
  typedef std::map<std::string, std::string> SettingsMap;

  SettingsWalker(SettingsMap* settings)
    : pugi::xml_tree_walker(), _settings(settings) { }

  virtual bool for_each(pugi::xml_node& node) {
    if(node.type() == pugi::node_pcdata) {
      std::string key = BuildKey(node.parent());
      std::string value = std::string(node.value());
      (*_settings)[key] = value;
      printf("'%s' '%s'\n", key.c_str(), value.c_str());
    }
    return true;
  }

  SettingsMap* _settings;
};

} // anonymous namespace

namespace bm {

SettingsManager::SettingsManager() { }
SettingsManager::~SettingsManager() { }

bool SettingsManager::Load(const std::string& path) {
  pugi::xml_document document;
  pugi::xml_parse_result parse_result = document.load_file(path.c_str());
  if(!parse_result) {
    BM_ERROR("Unable to parse settings.");
    return false;
  }

  SettingsWalker walker(&_settings);
  document.traverse(walker);

  return true;
}

std::string SettingsManager::GetValue(const std::string& key, std::string def_value) const {
  SettingsMap::const_iterator i = _settings.find(key);
  if(i != _settings.end()) {
    return i->second;
  }
  printf("Warning: returning default value.\n");
  return def_value;
}
int SettingsManager::GetValue(const std::string& key, int def_value) const {
  SettingsMap::const_iterator i = _settings.find(key);
  if(i != _settings.end()) {
    // XXX[21.08.2012 xairy]: malformed int?
    return atoi(i->second.c_str());
  }
  printf("Warning: returning default value.\n");
  return def_value;
}
bool SettingsManager::GetValue(const std::string& key, bool def_value) const {
  SettingsMap::const_iterator i = _settings.find(key);
  if(i != _settings.end()) {
    std::string value = i->second;
    return (value == "1" || value == "yes" || value == "true");
  }
  printf("Warning: returning default value.\n");
  return def_value;
}
float SettingsManager::GetValue(const std::string& key, float def_value) const {
  SettingsMap::const_iterator i = _settings.find(key);
  if(i != _settings.end()) {
    // XXX[21.08.2012 xairy]: malformed float?
    return static_cast<float>(atof(i->second.c_str()));
  }
  printf("Warning: returning default value.\n");
  return def_value;
}
double SettingsManager::GetValue(const std::string& key, double def_value) const {
  SettingsMap::const_iterator i = _settings.find(key);
  if(i != _settings.end()) {
    // XXX[21.08.2012 xairy]: malformed double?
    return atof(i->second.c_str());
  }
  printf("Warning: returning default value.\n");
  return def_value;
}

} // namespace bm
<commit_msg>When returning a default value from SettingManager::GetValue() key value is printed<commit_after>#include "settings_manager.hpp"

#include <cstdlib>
#include <cstring>

#include <map>
#include <string>

#include <pugixml.hpp>

#include <base/error.hpp>
#include <base/macros.hpp>

namespace {

std::string BuildKey(const pugi::xml_node& node) {
  CHECK(node.type() == pugi::node_element);
  if(node.parent().type() == pugi::node_document) {
    return std::string(node.name());
  } else if(node.parent().type() == pugi::node_element) {
    return BuildKey(node.parent()) + "." + std::string(node.name());
  }
  CHECK(false);
  return "";
}

struct SettingsWalker : public pugi::xml_tree_walker {
  typedef std::map<std::string, std::string> SettingsMap;

  SettingsWalker(SettingsMap* settings)
    : pugi::xml_tree_walker(), _settings(settings) { }

  virtual bool for_each(pugi::xml_node& node) {
    if(node.type() == pugi::node_pcdata) {
      std::string key = BuildKey(node.parent());
      std::string value = std::string(node.value());
      (*_settings)[key] = value;
      printf("'%s' = '%s'\n", key.c_str(), value.c_str());
    }
    return true;
  }

  SettingsMap* _settings;
};

} // anonymous namespace

namespace bm {

SettingsManager::SettingsManager() { }
SettingsManager::~SettingsManager() { }

bool SettingsManager::Load(const std::string& path) {
  pugi::xml_document document;
  pugi::xml_parse_result parse_result = document.load_file(path.c_str());
  if(!parse_result) {
    BM_ERROR("Unable to parse settings.");
    return false;
  }

  SettingsWalker walker(&_settings);
  document.traverse(walker);

  return true;
}

std::string SettingsManager::GetValue(const std::string& key, std::string def_value) const {
  SettingsMap::const_iterator i = _settings.find(key);
  if(i != _settings.end()) {
    return i->second;
  }
  printf("Warning: returning default value for '%s'.\n", key.c_str());
  return def_value;
}
int SettingsManager::GetValue(const std::string& key, int def_value) const {
  SettingsMap::const_iterator i = _settings.find(key);
  if(i != _settings.end()) {
    // XXX[21.08.2012 xairy]: malformed int?
    return atoi(i->second.c_str());
  }
  printf("Warning: returning default value for '%s'.\n", key.c_str());
  return def_value;
}
bool SettingsManager::GetValue(const std::string& key, bool def_value) const {
  SettingsMap::const_iterator i = _settings.find(key);
  if(i != _settings.end()) {
    std::string value = i->second;
    return (value == "1" || value == "yes" || value == "true");
  }
  printf("Warning: returning default value for '%s'.\n", key.c_str());
  return def_value;
}
float SettingsManager::GetValue(const std::string& key, float def_value) const {
  SettingsMap::const_iterator i = _settings.find(key);
  if(i != _settings.end()) {
    // XXX[21.08.2012 xairy]: malformed float?
    return static_cast<float>(atof(i->second.c_str()));
  }
  printf("Warning: returning default value for '%s'.\n", key.c_str());
  return def_value;
}
double SettingsManager::GetValue(const std::string& key, double def_value) const {
  SettingsMap::const_iterator i = _settings.find(key);
  if(i != _settings.end()) {
    // XXX[21.08.2012 xairy]: malformed double?
    return atof(i->second.c_str());
  }
  printf("Warning: returning default value for '%s'.\n", key.c_str());
  return def_value;
}

} // namespace bm
<|endoftext|>