text
stringlengths 54
60.6k
|
|---|
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file EthereumHost.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include "EthereumHost.h"
#include <chrono>
#include <thread>
#include <libdevcore/Common.h>
#include <libp2p/Host.h>
#include <libp2p/Session.h>
#include <libethcore/Exceptions.h>
#include <libethcore/Params.h>
#include "BlockChain.h"
#include "TransactionQueue.h"
#include "BlockQueue.h"
#include "EthereumPeer.h"
#include "DownloadMan.h"
#include "BlockChainSync.h"
using namespace std;
using namespace dev;
using namespace dev::eth;
using namespace p2p;
unsigned const EthereumHost::c_oldProtocolVersion = 60; //TODO: remove this once v61+ is common
unsigned const c_chainReorgSize = 30000;
char const* const EthereumHost::s_stateNames[static_cast<int>(SyncState::Size)] = {"Idle", "Waiting", "Hashes", "Blocks", "NewBlocks" };
EthereumHost::EthereumHost(BlockChain const& _ch, TransactionQueue& _tq, BlockQueue& _bq, u256 _networkId):
HostCapability<EthereumPeer>(),
Worker ("ethsync"),
m_chain (_ch),
m_tq (_tq),
m_bq (_bq),
m_networkId (_networkId)
{
m_latestBlockSent = _ch.currentHash();
}
EthereumHost::~EthereumHost()
{
}
bool EthereumHost::ensureInitialised()
{
if (!m_latestBlockSent)
{
// First time - just initialise.
m_latestBlockSent = m_chain.currentHash();
clog(NetNote) << "Initialising: latest=" << m_latestBlockSent;
for (auto const& i: m_tq.transactions())
m_transactionsSent.insert(i.first);
return true;
}
return false;
}
void EthereumHost::reset()
{
Guard l(x_sync);
if (m_sync)
m_sync->abortSync();
m_sync.reset();
m_latestBlockSent = h256();
m_transactionsSent.clear();
}
void EthereumHost::doWork()
{
bool netChange = ensureInitialised();
auto h = m_chain.currentHash();
// If we've finished our initial sync (including getting all the blocks into the chain so as to reduce invalid transactions), start trading transactions & blocks
if (!isSyncing() && m_chain.isKnown(m_latestBlockSent))
{
if (m_newTransactions)
{
m_newTransactions = false;
maintainTransactions();
}
if (m_newBlocks)
{
m_newBlocks = false;
maintainBlocks(h);
}
}
foreachPeer([](EthereumPeer* _p) { _p->tick(); return true; });
// return netChange;
// TODO: Figure out what to do with netChange.
(void)netChange;
}
void EthereumHost::maintainTransactions()
{
// Send any new transactions.
unordered_map<std::shared_ptr<EthereumPeer>, h256s> peerTransactions;
auto ts = m_tq.transactions();
for (auto const& i: ts)
{
bool unsent = !m_transactionsSent.count(i.first);
auto peers = get<1>(randomSelection(0, [&](EthereumPeer* p) { return p->m_requireTransactions || (unsent && !p->m_knownTransactions.count(i.first)); }));
for (auto const& p: peers)
peerTransactions[p].push_back(i.first);
}
for (auto const& t: ts)
m_transactionsSent.insert(t.first);
foreachPeerPtr([&](shared_ptr<EthereumPeer> _p)
{
bytes b;
unsigned n = 0;
for (auto const& h: peerTransactions[_p])
{
_p->m_knownTransactions.insert(h);
b += ts[h].rlp();
++n;
}
_p->clearKnownTransactions();
if (n || _p->m_requireTransactions)
{
RLPStream ts;
_p->prep(ts, TransactionsPacket, n).appendRaw(b, n);
_p->sealAndSend(ts);
cnote << "Sent" << n << "transactions to " << _p->session()->info().clientVersion;
}
_p->m_requireTransactions = false;
return true;
});
}
void EthereumHost::foreachPeer(std::function<bool(EthereumPeer*)> const& _f) const
{
foreachPeerPtr([&](std::shared_ptr<EthereumPeer> _p)
{
if (_p)
return _f(_p.get());
return true;
});
}
void EthereumHost::foreachPeerPtr(std::function<bool(std::shared_ptr<EthereumPeer>)> const& _f) const
{
for (auto s: peerSessions())
if (!_f(s.first->cap<EthereumPeer>()))
return;
for (auto s: peerSessions(c_oldProtocolVersion)) //TODO: remove once v61+ is common
if (!_f(s.first->cap<EthereumPeer>(c_oldProtocolVersion)))
return;
}
tuple<vector<shared_ptr<EthereumPeer>>, vector<shared_ptr<EthereumPeer>>, vector<shared_ptr<Session>>> EthereumHost::randomSelection(unsigned _percent, std::function<bool(EthereumPeer*)> const& _allow)
{
vector<shared_ptr<EthereumPeer>> chosen;
vector<shared_ptr<EthereumPeer>> allowed;
vector<shared_ptr<Session>> sessions;
auto const& ps = peerSessions();
allowed.reserve(ps.size());
for (auto const& j: ps)
{
auto pp = j.first->cap<EthereumPeer>();
if (_allow(pp.get()))
{
allowed.push_back(move(pp));
sessions.push_back(move(j.first));
}
}
chosen.reserve((ps.size() * _percent + 99) / 100);
for (unsigned i = (ps.size() * _percent + 99) / 100; i-- && allowed.size();)
{
unsigned n = rand() % allowed.size();
chosen.push_back(std::move(allowed[n]));
allowed.erase(allowed.begin() + n);
}
return make_tuple(move(chosen), move(allowed), move(sessions));
}
void EthereumHost::maintainBlocks(h256 const& _currentHash)
{
// Send any new blocks.
auto detailsFrom = m_chain.details(m_latestBlockSent);
auto detailsTo = m_chain.details(_currentHash);
if (detailsFrom.totalDifficulty < detailsTo.totalDifficulty)
{
if (diff(detailsFrom.number, detailsTo.number) < 20)
{
// don't be sending more than 20 "new" blocks. if there are any more we were probably waaaay behind.
clog(NetMessageSummary) << "Sending a new block (current is" << _currentHash << ", was" << m_latestBlockSent << ")";
h256s blocks = get<0>(m_chain.treeRoute(m_latestBlockSent, _currentHash, false, false, true));
auto s = randomSelection(25, [&](EthereumPeer* p){ DEV_GUARDED(p->x_knownBlocks) return !p->m_knownBlocks.count(_currentHash); return false; });
for (shared_ptr<EthereumPeer> const& p: get<0>(s))
for (auto const& b: blocks)
{
RLPStream ts;
p->prep(ts, NewBlockPacket, 2).appendRaw(m_chain.block(b), 1).append(m_chain.details(b).totalDifficulty);
Guard l(p->x_knownBlocks);
p->sealAndSend(ts);
p->m_knownBlocks.clear();
}
for (shared_ptr<EthereumPeer> const& p: get<1>(s))
{
RLPStream ts;
p->prep(ts, NewBlockHashesPacket, blocks.size());
for (auto const& b: blocks)
ts.append(b);
Guard l(p->x_knownBlocks);
p->sealAndSend(ts);
p->m_knownBlocks.clear();
}
}
m_latestBlockSent = _currentHash;
}
}
BlockChainSync& EthereumHost::sync()
{
if (m_sync)
return *m_sync; // We only chose sync strategy once
bool pv61 = false;
foreachPeer([&](EthereumPeer* _p)
{
if (_p->m_protocolVersion == protocolVersion())
pv61 = true;
return !pv61;
});
m_sync.reset(pv61 ? new PV60Sync(*this) : new PV60Sync(*this));
return *m_sync;
}
void EthereumHost::onPeerStatus(EthereumPeer* _peer)
{
Guard l(x_sync);
sync().onPeerStatus(_peer);
}
void EthereumHost::onPeerHashes(EthereumPeer* _peer, h256s const& _hashes)
{
Guard l(x_sync);
sync().onPeerHashes(_peer, _hashes);
}
void EthereumHost::onPeerBlocks(EthereumPeer* _peer, RLP const& _r)
{
Guard l(x_sync);
sync().onPeerBlocks(_peer, _r);
}
void EthereumHost::onPeerNewHashes(EthereumPeer* _peer, h256s const& _hashes)
{
Guard l(x_sync);
sync().onPeerNewHashes(_peer, _hashes);
}
void EthereumHost::onPeerNewBlock(EthereumPeer* _peer, RLP const& _r)
{
Guard l(x_sync);
sync().onPeerNewBlock(_peer, _r);
}
void EthereumHost::onPeerTransactions(EthereumPeer* _peer, RLP const& _r)
{
if (_peer->isCriticalSyncing())
{
clog(NetAllDetail) << "Ignoring transaction from peer we are syncing with";
return;
}
unsigned itemCount = _r.itemCount();
clog(NetAllDetail) << "Transactions (" << dec << itemCount << "entries)";
Guard l(_peer->x_knownTransactions);
for (unsigned i = 0; i < min<unsigned>(itemCount, 256); ++i) // process 256 transactions at most. TODO: much better solution.
{
auto h = sha3(_r[i].data());
_peer->m_knownTransactions.insert(h);
ImportResult ir = m_tq.import(_r[i].data());
switch (ir)
{
case ImportResult::Malformed:
_peer->addRating(-100);
break;
case ImportResult::AlreadyKnown:
// if we already had the transaction, then don't bother sending it on.
m_transactionsSent.insert(h);
_peer->addRating(0);
break;
case ImportResult::Success:
_peer->addRating(100);
break;
default:;
}
}
}
void EthereumHost::onPeerAborting(EthereumPeer* _peer)
{
Guard l(x_sync);
if (m_sync)
m_sync->onPeerAborting(_peer);
}
bool EthereumHost::isSyncing() const
{
Guard l(x_sync);
if (!m_sync)
return false;
return m_sync->isSyncing();
}
SyncStatus EthereumHost::status() const
{
Guard l(x_sync);
if (!m_sync)
return SyncStatus();
return m_sync->status();
}
<commit_msg>Remove unused constant<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file EthereumHost.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include "EthereumHost.h"
#include <chrono>
#include <thread>
#include <libdevcore/Common.h>
#include <libp2p/Host.h>
#include <libp2p/Session.h>
#include <libethcore/Exceptions.h>
#include <libethcore/Params.h>
#include "BlockChain.h"
#include "TransactionQueue.h"
#include "BlockQueue.h"
#include "EthereumPeer.h"
#include "DownloadMan.h"
#include "BlockChainSync.h"
using namespace std;
using namespace dev;
using namespace dev::eth;
using namespace p2p;
unsigned const EthereumHost::c_oldProtocolVersion = 60; //TODO: remove this once v61+ is common
char const* const EthereumHost::s_stateNames[static_cast<int>(SyncState::Size)] = {"Idle", "Waiting", "Hashes", "Blocks", "NewBlocks" };
EthereumHost::EthereumHost(BlockChain const& _ch, TransactionQueue& _tq, BlockQueue& _bq, u256 _networkId):
HostCapability<EthereumPeer>(),
Worker ("ethsync"),
m_chain (_ch),
m_tq (_tq),
m_bq (_bq),
m_networkId (_networkId)
{
m_latestBlockSent = _ch.currentHash();
}
EthereumHost::~EthereumHost()
{
}
bool EthereumHost::ensureInitialised()
{
if (!m_latestBlockSent)
{
// First time - just initialise.
m_latestBlockSent = m_chain.currentHash();
clog(NetNote) << "Initialising: latest=" << m_latestBlockSent;
for (auto const& i: m_tq.transactions())
m_transactionsSent.insert(i.first);
return true;
}
return false;
}
void EthereumHost::reset()
{
Guard l(x_sync);
if (m_sync)
m_sync->abortSync();
m_sync.reset();
m_latestBlockSent = h256();
m_transactionsSent.clear();
}
void EthereumHost::doWork()
{
bool netChange = ensureInitialised();
auto h = m_chain.currentHash();
// If we've finished our initial sync (including getting all the blocks into the chain so as to reduce invalid transactions), start trading transactions & blocks
if (!isSyncing() && m_chain.isKnown(m_latestBlockSent))
{
if (m_newTransactions)
{
m_newTransactions = false;
maintainTransactions();
}
if (m_newBlocks)
{
m_newBlocks = false;
maintainBlocks(h);
}
}
foreachPeer([](EthereumPeer* _p) { _p->tick(); return true; });
// return netChange;
// TODO: Figure out what to do with netChange.
(void)netChange;
}
void EthereumHost::maintainTransactions()
{
// Send any new transactions.
unordered_map<std::shared_ptr<EthereumPeer>, h256s> peerTransactions;
auto ts = m_tq.transactions();
for (auto const& i: ts)
{
bool unsent = !m_transactionsSent.count(i.first);
auto peers = get<1>(randomSelection(0, [&](EthereumPeer* p) { return p->m_requireTransactions || (unsent && !p->m_knownTransactions.count(i.first)); }));
for (auto const& p: peers)
peerTransactions[p].push_back(i.first);
}
for (auto const& t: ts)
m_transactionsSent.insert(t.first);
foreachPeerPtr([&](shared_ptr<EthereumPeer> _p)
{
bytes b;
unsigned n = 0;
for (auto const& h: peerTransactions[_p])
{
_p->m_knownTransactions.insert(h);
b += ts[h].rlp();
++n;
}
_p->clearKnownTransactions();
if (n || _p->m_requireTransactions)
{
RLPStream ts;
_p->prep(ts, TransactionsPacket, n).appendRaw(b, n);
_p->sealAndSend(ts);
cnote << "Sent" << n << "transactions to " << _p->session()->info().clientVersion;
}
_p->m_requireTransactions = false;
return true;
});
}
void EthereumHost::foreachPeer(std::function<bool(EthereumPeer*)> const& _f) const
{
foreachPeerPtr([&](std::shared_ptr<EthereumPeer> _p)
{
if (_p)
return _f(_p.get());
return true;
});
}
void EthereumHost::foreachPeerPtr(std::function<bool(std::shared_ptr<EthereumPeer>)> const& _f) const
{
for (auto s: peerSessions())
if (!_f(s.first->cap<EthereumPeer>()))
return;
for (auto s: peerSessions(c_oldProtocolVersion)) //TODO: remove once v61+ is common
if (!_f(s.first->cap<EthereumPeer>(c_oldProtocolVersion)))
return;
}
tuple<vector<shared_ptr<EthereumPeer>>, vector<shared_ptr<EthereumPeer>>, vector<shared_ptr<Session>>> EthereumHost::randomSelection(unsigned _percent, std::function<bool(EthereumPeer*)> const& _allow)
{
vector<shared_ptr<EthereumPeer>> chosen;
vector<shared_ptr<EthereumPeer>> allowed;
vector<shared_ptr<Session>> sessions;
auto const& ps = peerSessions();
allowed.reserve(ps.size());
for (auto const& j: ps)
{
auto pp = j.first->cap<EthereumPeer>();
if (_allow(pp.get()))
{
allowed.push_back(move(pp));
sessions.push_back(move(j.first));
}
}
chosen.reserve((ps.size() * _percent + 99) / 100);
for (unsigned i = (ps.size() * _percent + 99) / 100; i-- && allowed.size();)
{
unsigned n = rand() % allowed.size();
chosen.push_back(std::move(allowed[n]));
allowed.erase(allowed.begin() + n);
}
return make_tuple(move(chosen), move(allowed), move(sessions));
}
void EthereumHost::maintainBlocks(h256 const& _currentHash)
{
// Send any new blocks.
auto detailsFrom = m_chain.details(m_latestBlockSent);
auto detailsTo = m_chain.details(_currentHash);
if (detailsFrom.totalDifficulty < detailsTo.totalDifficulty)
{
if (diff(detailsFrom.number, detailsTo.number) < 20)
{
// don't be sending more than 20 "new" blocks. if there are any more we were probably waaaay behind.
clog(NetMessageSummary) << "Sending a new block (current is" << _currentHash << ", was" << m_latestBlockSent << ")";
h256s blocks = get<0>(m_chain.treeRoute(m_latestBlockSent, _currentHash, false, false, true));
auto s = randomSelection(25, [&](EthereumPeer* p){ DEV_GUARDED(p->x_knownBlocks) return !p->m_knownBlocks.count(_currentHash); return false; });
for (shared_ptr<EthereumPeer> const& p: get<0>(s))
for (auto const& b: blocks)
{
RLPStream ts;
p->prep(ts, NewBlockPacket, 2).appendRaw(m_chain.block(b), 1).append(m_chain.details(b).totalDifficulty);
Guard l(p->x_knownBlocks);
p->sealAndSend(ts);
p->m_knownBlocks.clear();
}
for (shared_ptr<EthereumPeer> const& p: get<1>(s))
{
RLPStream ts;
p->prep(ts, NewBlockHashesPacket, blocks.size());
for (auto const& b: blocks)
ts.append(b);
Guard l(p->x_knownBlocks);
p->sealAndSend(ts);
p->m_knownBlocks.clear();
}
}
m_latestBlockSent = _currentHash;
}
}
BlockChainSync& EthereumHost::sync()
{
if (m_sync)
return *m_sync; // We only chose sync strategy once
bool pv61 = false;
foreachPeer([&](EthereumPeer* _p)
{
if (_p->m_protocolVersion == protocolVersion())
pv61 = true;
return !pv61;
});
m_sync.reset(pv61 ? new PV60Sync(*this) : new PV60Sync(*this));
return *m_sync;
}
void EthereumHost::onPeerStatus(EthereumPeer* _peer)
{
Guard l(x_sync);
sync().onPeerStatus(_peer);
}
void EthereumHost::onPeerHashes(EthereumPeer* _peer, h256s const& _hashes)
{
Guard l(x_sync);
sync().onPeerHashes(_peer, _hashes);
}
void EthereumHost::onPeerBlocks(EthereumPeer* _peer, RLP const& _r)
{
Guard l(x_sync);
sync().onPeerBlocks(_peer, _r);
}
void EthereumHost::onPeerNewHashes(EthereumPeer* _peer, h256s const& _hashes)
{
Guard l(x_sync);
sync().onPeerNewHashes(_peer, _hashes);
}
void EthereumHost::onPeerNewBlock(EthereumPeer* _peer, RLP const& _r)
{
Guard l(x_sync);
sync().onPeerNewBlock(_peer, _r);
}
void EthereumHost::onPeerTransactions(EthereumPeer* _peer, RLP const& _r)
{
if (_peer->isCriticalSyncing())
{
clog(NetAllDetail) << "Ignoring transaction from peer we are syncing with";
return;
}
unsigned itemCount = _r.itemCount();
clog(NetAllDetail) << "Transactions (" << dec << itemCount << "entries)";
Guard l(_peer->x_knownTransactions);
for (unsigned i = 0; i < min<unsigned>(itemCount, 256); ++i) // process 256 transactions at most. TODO: much better solution.
{
auto h = sha3(_r[i].data());
_peer->m_knownTransactions.insert(h);
ImportResult ir = m_tq.import(_r[i].data());
switch (ir)
{
case ImportResult::Malformed:
_peer->addRating(-100);
break;
case ImportResult::AlreadyKnown:
// if we already had the transaction, then don't bother sending it on.
m_transactionsSent.insert(h);
_peer->addRating(0);
break;
case ImportResult::Success:
_peer->addRating(100);
break;
default:;
}
}
}
void EthereumHost::onPeerAborting(EthereumPeer* _peer)
{
Guard l(x_sync);
if (m_sync)
m_sync->onPeerAborting(_peer);
}
bool EthereumHost::isSyncing() const
{
Guard l(x_sync);
if (!m_sync)
return false;
return m_sync->isSyncing();
}
SyncStatus EthereumHost::status() const
{
Guard l(x_sync);
if (!m_sync)
return SyncStatus();
return m_sync->status();
}
<|endoftext|>
|
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file EthereumPeer.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include "EthereumPeer.h"
#include <chrono>
#include <libdevcore/Common.h>
#include <libethcore/Exceptions.h>
#include <libp2p/Session.h>
#include "BlockChain.h"
#include "EthereumHost.h"
#include "TransactionQueue.h"
#include "BlockQueue.h"
using namespace std;
using namespace dev;
using namespace dev::eth;
using namespace p2p;
EthereumPeer::EthereumPeer(Session* _s, HostCapabilityFace* _h, unsigned _i, CapDesc const& _cap):
Capability(_s, _h, _i),
m_sub(host()->downloadMan()),
m_hashSub(host()->hashDownloadMan()),
m_peerCapabilityVersion(_cap.second)
{
m_isRude = host()->isRude(session()->id(), session()->info().clientVersion);
session()->addNote("manners", m_isRude ? "RUDE" : "nice");
m_syncHashNumber = host()->chain().number() + 1;
requestStatus();
}
EthereumPeer::~EthereumPeer()
{
clog(NetMessageSummary) << "Aborting Sync :-(";
abortSync();
}
void EthereumPeer::abortSync()
{
host()->onPeerAborting(this);
}
void EthereumPeer::setRude()
{
m_isRude = true;
host()->noteRude(session()->id(), session()->info().clientVersion);
session()->addNote("manners", m_isRude ? "RUDE" : "nice");
}
EthereumHost* EthereumPeer::host() const
{
return static_cast<EthereumHost*>(Capability::hostCapability());
}
/*
* Possible asking/syncing states for two peers:
*/
string toString(Asking _a)
{
switch (_a)
{
case Asking::Blocks: return "Blocks";
case Asking::Hashes: return "Hashes";
case Asking::Nothing: return "Nothing";
case Asking::State: return "State";
}
return "?";
}
void EthereumPeer::setIdle()
{
m_sub.doneFetch();
m_hashSub.doneFetch();
setAsking(Asking::Nothing);
}
void EthereumPeer::requestStatus()
{
assert(m_asking == Asking::Nothing);
setAsking(Asking::State);
RLPStream s;
bool latest = m_peerCapabilityVersion == host()->protocolVersion();
prep(s, StatusPacket, latest ? 6 : 5)
<< (latest ? host()->protocolVersion() : EthereumHost::c_oldProtocolVersion)
<< host()->networkId()
<< host()->chain().details().totalDifficulty
<< host()->chain().currentHash()
<< host()->chain().genesisHash();
if (latest)
s << u256(host()->chain().number());
sealAndSend(s);
}
void EthereumPeer::requestHashes()
{
assert(m_asking == Asking::Nothing);
m_syncHashNumber = m_hashSub.nextFetch(c_maxHashesAsk);
m_syncHash = h256();
setAsking(Asking::Hashes);
RLPStream s;
prep(s, GetBlockHashesByNumberPacket, 2) << m_syncHashNumber << c_maxHashesAsk;
clog(NetMessageDetail) << "Requesting block hashes for numbers " << m_syncHashNumber << "-" << m_syncHashNumber + c_maxHashesAsk - 1;
sealAndSend(s);
}
void EthereumPeer::requestHashes(h256 const& _lastHash)
{
assert(m_asking == Asking::Nothing);
setAsking(Asking::Hashes);
RLPStream s;
prep(s, GetBlockHashesPacket, 2) << _lastHash << c_maxHashesAsk;
clog(NetMessageDetail) << "Requesting block hashes staring from " << _lastHash;
m_syncHash = _lastHash;
m_syncHashNumber = 0;
sealAndSend(s);
}
void EthereumPeer::requestBlocks()
{
setAsking(Asking::Blocks);
auto blocks = m_sub.nextFetch(c_maxBlocksAsk);
if (blocks.size())
{
RLPStream s;
prep(s, GetBlocksPacket, blocks.size());
for (auto const& i: blocks)
s << i;
sealAndSend(s);
}
else
setIdle();
return;
}
void EthereumPeer::setAsking(Asking _a)
{
m_asking = _a;
m_lastAsk = chrono::system_clock::now();
session()->addNote("ask", _a == Asking::Nothing ? "nothing" : _a == Asking::State ? "state" : _a == Asking::Hashes ? "hashes" : _a == Asking::Blocks ? "blocks" : "?");
session()->addNote("sync", string(isSyncing() ? "ongoing" : "holding") + (needsSyncing() ? " & needed" : ""));
}
void EthereumPeer::tick()
{
if (chrono::system_clock::now() - m_lastAsk > chrono::seconds(10) && m_asking != Asking::Nothing)
// timeout
session()->disconnect(PingTimeout);
}
bool EthereumPeer::isSyncing() const
{
return m_asking != Asking::Nothing;
}
bool EthereumPeer::interpret(unsigned _id, RLP const& _r)
{
try
{
switch (_id)
{
case StatusPacket:
{
m_protocolVersion = _r[0].toInt<unsigned>();
m_networkId = _r[1].toInt<u256>();
m_totalDifficulty = _r[2].toInt<u256>();
m_latestHash = _r[3].toHash<h256>();
m_genesisHash = _r[4].toHash<h256>();
if (m_peerCapabilityVersion == host()->protocolVersion())
{
m_protocolVersion = host()->protocolVersion();
m_latestBlockNumber = _r[5].toInt<u256>();
}
clog(NetMessageSummary) << "Status:" << m_protocolVersion << "/" << m_networkId << "/" << m_genesisHash << "/" << m_latestBlockNumber << ", TD:" << m_totalDifficulty << "=" << m_latestHash;
setAsking(Asking::Nothing);
host()->onPeerStatus(this);
break;
}
case TransactionsPacket:
{
host()->onPeerTransactions(this, _r);
break;
}
case GetBlockHashesPacket:
{
h256 later = _r[0].toHash<h256>();
unsigned limit = _r[1].toInt<unsigned>();
clog(NetMessageSummary) << "GetBlockHashes (" << limit << "entries," << later << ")";
unsigned c = min<unsigned>(host()->chain().number(later), limit);
RLPStream s;
prep(s, BlockHashesPacket, c);
h256 p = host()->chain().details(later).parent;
for (unsigned i = 0; i < c && p; ++i, p = host()->chain().details(p).parent)
s << p;
sealAndSend(s);
addRating(0);
break;
}
case GetBlockHashesByNumberPacket:
{
u256 number256 = _r[0].toInt<u256>();
unsigned number = (unsigned) number256;
unsigned limit = _r[1].toInt<unsigned>();
clog(NetMessageSummary) << "GetBlockHashesByNumber (" << number << "-" << number + limit - 1 << ")";
RLPStream s;
if (number <= host()->chain().number())
{
unsigned c = min<unsigned>(host()->chain().number() - number + 1, limit);
prep(s, BlockHashesPacket, c);
for (unsigned n = number; n < number + c; n++)
{
h256 p = host()->chain().numberHash(n);
s << p;
}
}
else
prep(s, BlockHashesPacket, 0);
sealAndSend(s);
addRating(0);
break;
}
case BlockHashesPacket:
{
unsigned itemCount = _r.itemCount();
clog(NetMessageSummary) << "BlockHashes (" << dec << itemCount << "entries)" << (itemCount ? "" : ": NoMoreHashes");
if (m_asking != Asking::Hashes)
{
clog(NetWarn) << "Peer giving us hashes when we didn't ask for them.";
break;
}
setAsking(Asking::Nothing);
h256s hashes(itemCount);
for (unsigned i = 0; i < itemCount; ++i)
hashes[i] = _r[i].toHash<h256>();
if (m_syncHashNumber > 0)
m_syncHashNumber += itemCount;
host()->onPeerHashes(this, hashes);
break;
}
case GetBlocksPacket:
{
unsigned count = _r.itemCount();
clog(NetMessageSummary) << "GetBlocks (" << dec << count << "entries)";
if (!count)
{
clog(NetImpolite) << "Zero-entry GetBlocks: Not replying.";
addRating(-10);
break;
}
// return the requested blocks.
bytes rlp;
unsigned n = 0;
for (unsigned i = 0; i < min(count, c_maxBlocks) && rlp.size() < c_maxPayload; ++i)
{
auto h = _r[i].toHash<h256>();
if (host()->chain().isKnown(h))
{
rlp += host()->chain().block(_r[i].toHash<h256>());
++n;
}
}
if (count > 20 && n == 0)
clog(NetWarn) << "all" << count << "unknown blocks requested; peer on different chain?";
else
clog(NetMessageSummary) << n << "blocks known and returned;" << (min(count, c_maxBlocks) - n) << "blocks unknown;" << (count > c_maxBlocks ? count - c_maxBlocks : 0) << "blocks ignored";
addRating(0);
RLPStream s;
prep(s, BlocksPacket, n).appendRaw(rlp, n);
sealAndSend(s);
break;
}
case BlocksPacket:
{
if (m_asking != Asking::Blocks)
clog(NetImpolite) << "Peer giving us blocks when we didn't ask for them.";
else
{
setAsking(Asking::Nothing);
host()->onPeerBlocks(this, _r);
}
break;
}
case NewBlockPacket:
{
host()->onPeerNewBlock(this, _r);
break;
}
case NewBlockHashesPacket:
{
unsigned itemCount = _r.itemCount();
clog(NetMessageSummary) << "BlockHashes (" << dec << itemCount << "entries)" << (itemCount ? "" : ": NoMoreHashes");
h256s hashes(itemCount);
for (unsigned i = 0; i < itemCount; ++i)
hashes[i] = _r[i].toHash<h256>();
host()->onPeerNewHashes(this, hashes);
break;
}
default:
return false;
}
}
catch (Exception const& _e)
{
clog(NetWarn) << "Peer causing an Exception:" << _e.what() << _r;
}
catch (std::exception const& _e)
{
clog(NetWarn) << "Peer causing an exception:" << _e.what() << _r;
}
return true;
}
<commit_msg>handle missing status field gracefully<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file EthereumPeer.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include "EthereumPeer.h"
#include <chrono>
#include <libdevcore/Common.h>
#include <libethcore/Exceptions.h>
#include <libp2p/Session.h>
#include "BlockChain.h"
#include "EthereumHost.h"
#include "TransactionQueue.h"
#include "BlockQueue.h"
using namespace std;
using namespace dev;
using namespace dev::eth;
using namespace p2p;
EthereumPeer::EthereumPeer(Session* _s, HostCapabilityFace* _h, unsigned _i, CapDesc const& _cap):
Capability(_s, _h, _i),
m_sub(host()->downloadMan()),
m_hashSub(host()->hashDownloadMan()),
m_peerCapabilityVersion(_cap.second)
{
m_isRude = host()->isRude(session()->id(), session()->info().clientVersion);
session()->addNote("manners", m_isRude ? "RUDE" : "nice");
m_syncHashNumber = host()->chain().number() + 1;
requestStatus();
}
EthereumPeer::~EthereumPeer()
{
clog(NetMessageSummary) << "Aborting Sync :-(";
abortSync();
}
void EthereumPeer::abortSync()
{
host()->onPeerAborting(this);
}
void EthereumPeer::setRude()
{
m_isRude = true;
host()->noteRude(session()->id(), session()->info().clientVersion);
session()->addNote("manners", m_isRude ? "RUDE" : "nice");
}
EthereumHost* EthereumPeer::host() const
{
return static_cast<EthereumHost*>(Capability::hostCapability());
}
/*
* Possible asking/syncing states for two peers:
*/
string toString(Asking _a)
{
switch (_a)
{
case Asking::Blocks: return "Blocks";
case Asking::Hashes: return "Hashes";
case Asking::Nothing: return "Nothing";
case Asking::State: return "State";
}
return "?";
}
void EthereumPeer::setIdle()
{
m_sub.doneFetch();
m_hashSub.doneFetch();
setAsking(Asking::Nothing);
}
void EthereumPeer::requestStatus()
{
assert(m_asking == Asking::Nothing);
setAsking(Asking::State);
RLPStream s;
bool latest = m_peerCapabilityVersion == host()->protocolVersion();
prep(s, StatusPacket, latest ? 6 : 5)
<< (latest ? host()->protocolVersion() : EthereumHost::c_oldProtocolVersion)
<< host()->networkId()
<< host()->chain().details().totalDifficulty
<< host()->chain().currentHash()
<< host()->chain().genesisHash();
if (latest)
s << u256(host()->chain().number());
sealAndSend(s);
}
void EthereumPeer::requestHashes()
{
assert(m_asking == Asking::Nothing);
m_syncHashNumber = m_hashSub.nextFetch(c_maxHashesAsk);
m_syncHash = h256();
setAsking(Asking::Hashes);
RLPStream s;
prep(s, GetBlockHashesByNumberPacket, 2) << m_syncHashNumber << c_maxHashesAsk;
clog(NetMessageDetail) << "Requesting block hashes for numbers " << m_syncHashNumber << "-" << m_syncHashNumber + c_maxHashesAsk - 1;
sealAndSend(s);
}
void EthereumPeer::requestHashes(h256 const& _lastHash)
{
assert(m_asking == Asking::Nothing);
setAsking(Asking::Hashes);
RLPStream s;
prep(s, GetBlockHashesPacket, 2) << _lastHash << c_maxHashesAsk;
clog(NetMessageDetail) << "Requesting block hashes staring from " << _lastHash;
m_syncHash = _lastHash;
m_syncHashNumber = 0;
sealAndSend(s);
}
void EthereumPeer::requestBlocks()
{
setAsking(Asking::Blocks);
auto blocks = m_sub.nextFetch(c_maxBlocksAsk);
if (blocks.size())
{
RLPStream s;
prep(s, GetBlocksPacket, blocks.size());
for (auto const& i: blocks)
s << i;
sealAndSend(s);
}
else
setIdle();
return;
}
void EthereumPeer::setAsking(Asking _a)
{
m_asking = _a;
m_lastAsk = chrono::system_clock::now();
session()->addNote("ask", _a == Asking::Nothing ? "nothing" : _a == Asking::State ? "state" : _a == Asking::Hashes ? "hashes" : _a == Asking::Blocks ? "blocks" : "?");
session()->addNote("sync", string(isSyncing() ? "ongoing" : "holding") + (needsSyncing() ? " & needed" : ""));
}
void EthereumPeer::tick()
{
if (chrono::system_clock::now() - m_lastAsk > chrono::seconds(10) && m_asking != Asking::Nothing)
// timeout
session()->disconnect(PingTimeout);
}
bool EthereumPeer::isSyncing() const
{
return m_asking != Asking::Nothing;
}
bool EthereumPeer::interpret(unsigned _id, RLP const& _r)
{
try
{
switch (_id)
{
case StatusPacket:
{
m_protocolVersion = _r[0].toInt<unsigned>();
m_networkId = _r[1].toInt<u256>();
m_totalDifficulty = _r[2].toInt<u256>();
m_latestHash = _r[3].toHash<h256>();
m_genesisHash = _r[4].toHash<h256>();
if (m_peerCapabilityVersion == host()->protocolVersion())
{
if (_r.itemCount() != 6)
{
clog(NetImpolite) << "Peer does not support PV61+ status extension.";
m_protocolVersion = EthereumHost::c_oldProtocolVersion;
}
else
{
m_protocolVersion = host()->protocolVersion();
m_latestBlockNumber = _r[5].toInt<u256>();
}
}
clog(NetMessageSummary) << "Status:" << m_protocolVersion << "/" << m_networkId << "/" << m_genesisHash << "/" << m_latestBlockNumber << ", TD:" << m_totalDifficulty << "=" << m_latestHash;
setAsking(Asking::Nothing);
host()->onPeerStatus(this);
break;
}
case TransactionsPacket:
{
host()->onPeerTransactions(this, _r);
break;
}
case GetBlockHashesPacket:
{
h256 later = _r[0].toHash<h256>();
unsigned limit = _r[1].toInt<unsigned>();
clog(NetMessageSummary) << "GetBlockHashes (" << limit << "entries," << later << ")";
unsigned c = min<unsigned>(host()->chain().number(later), limit);
RLPStream s;
prep(s, BlockHashesPacket, c);
h256 p = host()->chain().details(later).parent;
for (unsigned i = 0; i < c && p; ++i, p = host()->chain().details(p).parent)
s << p;
sealAndSend(s);
addRating(0);
break;
}
case GetBlockHashesByNumberPacket:
{
u256 number256 = _r[0].toInt<u256>();
unsigned number = (unsigned) number256;
unsigned limit = _r[1].toInt<unsigned>();
clog(NetMessageSummary) << "GetBlockHashesByNumber (" << number << "-" << number + limit - 1 << ")";
RLPStream s;
if (number <= host()->chain().number())
{
unsigned c = min<unsigned>(host()->chain().number() - number + 1, limit);
prep(s, BlockHashesPacket, c);
for (unsigned n = number; n < number + c; n++)
{
h256 p = host()->chain().numberHash(n);
s << p;
}
}
else
prep(s, BlockHashesPacket, 0);
sealAndSend(s);
addRating(0);
break;
}
case BlockHashesPacket:
{
unsigned itemCount = _r.itemCount();
clog(NetMessageSummary) << "BlockHashes (" << dec << itemCount << "entries)" << (itemCount ? "" : ": NoMoreHashes");
if (m_asking != Asking::Hashes)
{
clog(NetWarn) << "Peer giving us hashes when we didn't ask for them.";
break;
}
setAsking(Asking::Nothing);
h256s hashes(itemCount);
for (unsigned i = 0; i < itemCount; ++i)
hashes[i] = _r[i].toHash<h256>();
if (m_syncHashNumber > 0)
m_syncHashNumber += itemCount;
host()->onPeerHashes(this, hashes);
break;
}
case GetBlocksPacket:
{
unsigned count = _r.itemCount();
clog(NetMessageSummary) << "GetBlocks (" << dec << count << "entries)";
if (!count)
{
clog(NetImpolite) << "Zero-entry GetBlocks: Not replying.";
addRating(-10);
break;
}
// return the requested blocks.
bytes rlp;
unsigned n = 0;
for (unsigned i = 0; i < min(count, c_maxBlocks) && rlp.size() < c_maxPayload; ++i)
{
auto h = _r[i].toHash<h256>();
if (host()->chain().isKnown(h))
{
rlp += host()->chain().block(_r[i].toHash<h256>());
++n;
}
}
if (count > 20 && n == 0)
clog(NetWarn) << "all" << count << "unknown blocks requested; peer on different chain?";
else
clog(NetMessageSummary) << n << "blocks known and returned;" << (min(count, c_maxBlocks) - n) << "blocks unknown;" << (count > c_maxBlocks ? count - c_maxBlocks : 0) << "blocks ignored";
addRating(0);
RLPStream s;
prep(s, BlocksPacket, n).appendRaw(rlp, n);
sealAndSend(s);
break;
}
case BlocksPacket:
{
if (m_asking != Asking::Blocks)
clog(NetImpolite) << "Peer giving us blocks when we didn't ask for them.";
else
{
setAsking(Asking::Nothing);
host()->onPeerBlocks(this, _r);
}
break;
}
case NewBlockPacket:
{
host()->onPeerNewBlock(this, _r);
break;
}
case NewBlockHashesPacket:
{
unsigned itemCount = _r.itemCount();
clog(NetMessageSummary) << "BlockHashes (" << dec << itemCount << "entries)" << (itemCount ? "" : ": NoMoreHashes");
h256s hashes(itemCount);
for (unsigned i = 0; i < itemCount; ++i)
hashes[i] = _r[i].toHash<h256>();
host()->onPeerNewHashes(this, hashes);
break;
}
default:
return false;
}
}
catch (Exception const& _e)
{
clog(NetWarn) << "Peer causing an Exception:" << _e.what() << _r;
}
catch (std::exception const& _e)
{
clog(NetWarn) << "Peer causing an exception:" << _e.what() << _r;
}
return true;
}
<|endoftext|>
|
<commit_before>/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009 - 2015 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QGROUNDCONTROL is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief Definition of Bluetooth connection for unmanned vehicles
* @author Gus Grubba <mavlink@grubba.com>
*
*/
#include <QtGlobal>
#include <QTimer>
#include <QList>
#include <QDebug>
#include <iostream>
#include <QtBluetooth/QBluetoothDeviceDiscoveryAgent>
#include <QtBluetooth/QBluetoothLocalDevice>
#include <QtBluetooth/QBluetoothUuid>
#include <QtBluetooth/QBluetoothSocket>
#include "BluetoothLink.h"
#include "QGC.h"
BluetoothLink::BluetoothLink(BluetoothConfiguration* config)
: _connectState(false)
, _targetSocket(NULL)
#ifdef __ios__
, _discoveryAgent(NULL)
#endif
, _shutDown(false)
{
Q_ASSERT(config != NULL);
_config = config;
_config->setLink(this);
//moveToThread(this);
}
BluetoothLink::~BluetoothLink()
{
// Disconnect link from configuration
_config->setLink(NULL);
_disconnect();
#ifdef __ios__
if(_discoveryAgent) {
_shutDown = true;
_discoveryAgent->stop();
_discoveryAgent->deleteLater();
_discoveryAgent = NULL;
}
#endif
}
void BluetoothLink::run()
{
}
void BluetoothLink::_restartConnection()
{
if(this->isConnected())
{
_disconnect();
_connect();
}
}
QString BluetoothLink::getName() const
{
return _config->name();
}
void BluetoothLink::writeBytes(const QByteArray bytes)
{
if(_targetSocket)
{
if(_targetSocket->isWritable())
{
if(_targetSocket->write(bytes) > 0) {
_logOutputDataRate(size, QDateTime::currentMSecsSinceEpoch());
}
else
qWarning() << "Bluetooth write error";
}
else
qWarning() << "Bluetooth not writable error";
}
}
void BluetoothLink::readBytes()
{
while (_targetSocket->bytesAvailable() > 0)
{
QByteArray datagram;
datagram.resize(_targetSocket->bytesAvailable());
_targetSocket->read(datagram.data(), datagram.size());
emit bytesReceived(this, datagram);
_logInputDataRate(datagram.length(), QDateTime::currentMSecsSinceEpoch());
}
}
void BluetoothLink::_disconnect(void)
{
#ifdef __ios__
if(_discoveryAgent) {
_shutDown = true;
_discoveryAgent->stop();
_discoveryAgent->deleteLater();
_discoveryAgent = NULL;
}
#endif
if(_targetSocket)
{
delete _targetSocket;
_targetSocket = NULL;
emit disconnected();
}
_connectState = false;
}
bool BluetoothLink::_connect(void)
{
_hardwareConnect();
return true;
}
bool BluetoothLink::_hardwareConnect()
{
#ifdef __ios__
if(_discoveryAgent) {
_shutDown = true;
_discoveryAgent->stop();
_discoveryAgent->deleteLater();
_discoveryAgent = NULL;
}
_discoveryAgent = new QBluetoothServiceDiscoveryAgent(this);
QObject::connect(_discoveryAgent, &QBluetoothServiceDiscoveryAgent::serviceDiscovered, this, &BluetoothLink::serviceDiscovered);
QObject::connect(_discoveryAgent, &QBluetoothServiceDiscoveryAgent::finished, this, &BluetoothLink::discoveryFinished);
QObject::connect(_discoveryAgent, &QBluetoothServiceDiscoveryAgent::canceled, this, &BluetoothLink::discoveryFinished);
QObject::connect(_discoveryAgent, static_cast<void (QBluetoothServiceDiscoveryAgent::*)(QBluetoothSocket::SocketError)>(&QBluetoothServiceDiscoveryAgent::error),
this, &BluetoothLink::discoveryError);
_shutDown = false;
_discoveryAgent->start();
#else
_createSocket();
_targetSocket->connectToService(QBluetoothAddress(_config->device().address), QBluetoothUuid(QBluetoothUuid::Rfcomm));
#endif
return true;
}
void BluetoothLink::_createSocket()
{
if(_targetSocket)
{
delete _targetSocket;
_targetSocket = NULL;
}
_targetSocket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol, this);
QObject::connect(_targetSocket, &QBluetoothSocket::connected, this, &BluetoothLink::deviceConnected);
QObject::connect(_targetSocket, &QBluetoothSocket::readyRead, this, &BluetoothLink::readBytes);
QObject::connect(_targetSocket, &QBluetoothSocket::disconnected, this, &BluetoothLink::deviceDisconnected);
QObject::connect(_targetSocket, static_cast<void (QBluetoothSocket::*)(QBluetoothSocket::SocketError)>(&QBluetoothSocket::error),
this, &BluetoothLink::deviceError);
}
#ifdef __ios__
void BluetoothLink::discoveryError(QBluetoothServiceDiscoveryAgent::Error error)
{
qDebug() << "Discovery error:" << error;
qDebug() << _discoveryAgent->errorString();
}
#endif
#ifdef __ios__
void BluetoothLink::serviceDiscovered(const QBluetoothServiceInfo& info)
{
if(!info.device().name().isEmpty() && !_targetSocket)
{
if(_config->device().uuid == info.device().deviceUuid() && _config->device().name == info.device().name())
{
_createSocket();
_targetSocket->connectToService(info);
}
}
}
#endif
#ifdef __ios__
void BluetoothLink::discoveryFinished()
{
if(_discoveryAgent && !_shutDown)
{
_shutDown = true;
_discoveryAgent->deleteLater();
_discoveryAgent = NULL;
if(!_targetSocket)
{
_connectState = false;
emit communicationError("Could not locate Bluetooth device:", _config->device().name);
}
}
}
#endif
void BluetoothLink::deviceConnected()
{
_connectState = true;
emit connected();
}
void BluetoothLink::deviceDisconnected()
{
_connectState = false;
qWarning() << "Bluetooth disconnected";
}
void BluetoothLink::deviceError(QBluetoothSocket::SocketError error)
{
_connectState = false;
qWarning() << "Bluetooth error" << error;
emit communicationError("Bluetooth Link Error", _targetSocket->errorString());
}
bool BluetoothLink::isConnected() const
{
return _connectState;
}
qint64 BluetoothLink::getConnectionSpeed() const
{
return 1000000; // 1 Mbit
}
qint64 BluetoothLink::getCurrentInDataRate() const
{
return 0;
}
qint64 BluetoothLink::getCurrentOutDataRate() const
{
return 0;
}
//--------------------------------------------------------------------------
//-- BluetoothConfiguration
BluetoothConfiguration::BluetoothConfiguration(const QString& name)
: LinkConfiguration(name)
, _deviceDiscover(NULL)
{
}
BluetoothConfiguration::BluetoothConfiguration(BluetoothConfiguration* source)
: LinkConfiguration(source)
, _deviceDiscover(NULL)
{
_device = source->device();
}
BluetoothConfiguration::~BluetoothConfiguration()
{
if(_deviceDiscover)
{
_deviceDiscover->stop();
delete _deviceDiscover;
}
}
void BluetoothConfiguration::copyFrom(LinkConfiguration *source)
{
LinkConfiguration::copyFrom(source);
BluetoothConfiguration* usource = dynamic_cast<BluetoothConfiguration*>(source);
Q_ASSERT(usource != NULL);
_device = usource->device();
}
void BluetoothConfiguration::saveSettings(QSettings& settings, const QString& root)
{
settings.beginGroup(root);
settings.setValue("deviceName", _device.name);
#ifdef __ios__
settings.setValue("uuid", _device.uuid.toString());
#else
settings.setValue("address",_device.address);
#endif
settings.endGroup();
}
void BluetoothConfiguration::loadSettings(QSettings& settings, const QString& root)
{
settings.beginGroup(root);
_device.name = settings.value("deviceName", _device.name).toString();
#ifdef __ios__
QString suuid = settings.value("uuid", _device.uuid.toString()).toString();
_device.uuid = QUuid(suuid);
#else
_device.address = settings.value("address", _device.address).toString();
#endif
settings.endGroup();
}
void BluetoothConfiguration::updateSettings()
{
if(_link) {
BluetoothLink* ulink = dynamic_cast<BluetoothLink*>(_link);
if(ulink) {
ulink->_restartConnection();
}
}
}
void BluetoothConfiguration::stopScan()
{
if(_deviceDiscover)
{
_deviceDiscover->stop();
_deviceDiscover->deleteLater();
_deviceDiscover = NULL;
emit scanningChanged();
}
}
void BluetoothConfiguration::startScan()
{
if(!_deviceDiscover)
{
_deviceDiscover = new QBluetoothDeviceDiscoveryAgent(this);
connect(_deviceDiscover, &QBluetoothDeviceDiscoveryAgent::deviceDiscovered, this, &BluetoothConfiguration::deviceDiscovered);
connect(_deviceDiscover, &QBluetoothDeviceDiscoveryAgent::finished, this, &BluetoothConfiguration::doneScanning);
emit scanningChanged();
}
else
{
_deviceDiscover->stop();
}
_nameList.clear();
_deviceList.clear();
emit nameListChanged();
_deviceDiscover->setInquiryType(QBluetoothDeviceDiscoveryAgent::GeneralUnlimitedInquiry);
_deviceDiscover->start();
}
void BluetoothConfiguration::deviceDiscovered(QBluetoothDeviceInfo info)
{
//print_device_info(info);
if(!info.name().isEmpty() && info.isValid())
{
BluetoothData data;
data.name = info.name();
#ifdef __ios__
data.uuid = info.deviceUuid();
#else
data.address = info.address().toString();
#endif
if(!_deviceList.contains(data))
{
_deviceList += data;
_nameList += data.name;
emit nameListChanged();
return;
}
}
}
void BluetoothConfiguration::doneScanning()
{
if(_deviceDiscover)
{
_deviceDiscover->deleteLater();
_deviceDiscover = NULL;
emit scanningChanged();
}
}
void BluetoothConfiguration::setDevName(const QString &name)
{
foreach(const BluetoothData& data, _deviceList)
{
if(data.name == name)
{
_device = data;
emit devNameChanged();
#ifndef __ios__
emit addressChanged();
#endif
return;
}
}
}
QString BluetoothConfiguration::address()
{
#ifdef __ios__
return QString("");
#else
return _device.address;
#endif
}
<commit_msg>Fix BluetoothLink::writeBytes reference to size<commit_after>/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009 - 2015 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QGROUNDCONTROL is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief Definition of Bluetooth connection for unmanned vehicles
* @author Gus Grubba <mavlink@grubba.com>
*
*/
#include <QtGlobal>
#include <QTimer>
#include <QList>
#include <QDebug>
#include <iostream>
#include <QtBluetooth/QBluetoothDeviceDiscoveryAgent>
#include <QtBluetooth/QBluetoothLocalDevice>
#include <QtBluetooth/QBluetoothUuid>
#include <QtBluetooth/QBluetoothSocket>
#include "BluetoothLink.h"
#include "QGC.h"
BluetoothLink::BluetoothLink(BluetoothConfiguration* config)
: _connectState(false)
, _targetSocket(NULL)
#ifdef __ios__
, _discoveryAgent(NULL)
#endif
, _shutDown(false)
{
Q_ASSERT(config != NULL);
_config = config;
_config->setLink(this);
//moveToThread(this);
}
BluetoothLink::~BluetoothLink()
{
// Disconnect link from configuration
_config->setLink(NULL);
_disconnect();
#ifdef __ios__
if(_discoveryAgent) {
_shutDown = true;
_discoveryAgent->stop();
_discoveryAgent->deleteLater();
_discoveryAgent = NULL;
}
#endif
}
void BluetoothLink::run()
{
}
void BluetoothLink::_restartConnection()
{
if(this->isConnected())
{
_disconnect();
_connect();
}
}
QString BluetoothLink::getName() const
{
return _config->name();
}
void BluetoothLink::writeBytes(const QByteArray bytes)
{
if(_targetSocket)
{
if(_targetSocket->isWritable())
{
if(_targetSocket->write(bytes) > 0) {
_logOutputDataRate(bytes.size(), QDateTime::currentMSecsSinceEpoch());
}
else
qWarning() << "Bluetooth write error";
}
else
qWarning() << "Bluetooth not writable error";
}
}
void BluetoothLink::readBytes()
{
while (_targetSocket->bytesAvailable() > 0)
{
QByteArray datagram;
datagram.resize(_targetSocket->bytesAvailable());
_targetSocket->read(datagram.data(), datagram.size());
emit bytesReceived(this, datagram);
_logInputDataRate(datagram.length(), QDateTime::currentMSecsSinceEpoch());
}
}
void BluetoothLink::_disconnect(void)
{
#ifdef __ios__
if(_discoveryAgent) {
_shutDown = true;
_discoveryAgent->stop();
_discoveryAgent->deleteLater();
_discoveryAgent = NULL;
}
#endif
if(_targetSocket)
{
delete _targetSocket;
_targetSocket = NULL;
emit disconnected();
}
_connectState = false;
}
bool BluetoothLink::_connect(void)
{
_hardwareConnect();
return true;
}
bool BluetoothLink::_hardwareConnect()
{
#ifdef __ios__
if(_discoveryAgent) {
_shutDown = true;
_discoveryAgent->stop();
_discoveryAgent->deleteLater();
_discoveryAgent = NULL;
}
_discoveryAgent = new QBluetoothServiceDiscoveryAgent(this);
QObject::connect(_discoveryAgent, &QBluetoothServiceDiscoveryAgent::serviceDiscovered, this, &BluetoothLink::serviceDiscovered);
QObject::connect(_discoveryAgent, &QBluetoothServiceDiscoveryAgent::finished, this, &BluetoothLink::discoveryFinished);
QObject::connect(_discoveryAgent, &QBluetoothServiceDiscoveryAgent::canceled, this, &BluetoothLink::discoveryFinished);
QObject::connect(_discoveryAgent, static_cast<void (QBluetoothServiceDiscoveryAgent::*)(QBluetoothSocket::SocketError)>(&QBluetoothServiceDiscoveryAgent::error),
this, &BluetoothLink::discoveryError);
_shutDown = false;
_discoveryAgent->start();
#else
_createSocket();
_targetSocket->connectToService(QBluetoothAddress(_config->device().address), QBluetoothUuid(QBluetoothUuid::Rfcomm));
#endif
return true;
}
void BluetoothLink::_createSocket()
{
if(_targetSocket)
{
delete _targetSocket;
_targetSocket = NULL;
}
_targetSocket = new QBluetoothSocket(QBluetoothServiceInfo::RfcommProtocol, this);
QObject::connect(_targetSocket, &QBluetoothSocket::connected, this, &BluetoothLink::deviceConnected);
QObject::connect(_targetSocket, &QBluetoothSocket::readyRead, this, &BluetoothLink::readBytes);
QObject::connect(_targetSocket, &QBluetoothSocket::disconnected, this, &BluetoothLink::deviceDisconnected);
QObject::connect(_targetSocket, static_cast<void (QBluetoothSocket::*)(QBluetoothSocket::SocketError)>(&QBluetoothSocket::error),
this, &BluetoothLink::deviceError);
}
#ifdef __ios__
void BluetoothLink::discoveryError(QBluetoothServiceDiscoveryAgent::Error error)
{
qDebug() << "Discovery error:" << error;
qDebug() << _discoveryAgent->errorString();
}
#endif
#ifdef __ios__
void BluetoothLink::serviceDiscovered(const QBluetoothServiceInfo& info)
{
if(!info.device().name().isEmpty() && !_targetSocket)
{
if(_config->device().uuid == info.device().deviceUuid() && _config->device().name == info.device().name())
{
_createSocket();
_targetSocket->connectToService(info);
}
}
}
#endif
#ifdef __ios__
void BluetoothLink::discoveryFinished()
{
if(_discoveryAgent && !_shutDown)
{
_shutDown = true;
_discoveryAgent->deleteLater();
_discoveryAgent = NULL;
if(!_targetSocket)
{
_connectState = false;
emit communicationError("Could not locate Bluetooth device:", _config->device().name);
}
}
}
#endif
void BluetoothLink::deviceConnected()
{
_connectState = true;
emit connected();
}
void BluetoothLink::deviceDisconnected()
{
_connectState = false;
qWarning() << "Bluetooth disconnected";
}
void BluetoothLink::deviceError(QBluetoothSocket::SocketError error)
{
_connectState = false;
qWarning() << "Bluetooth error" << error;
emit communicationError("Bluetooth Link Error", _targetSocket->errorString());
}
bool BluetoothLink::isConnected() const
{
return _connectState;
}
qint64 BluetoothLink::getConnectionSpeed() const
{
return 1000000; // 1 Mbit
}
qint64 BluetoothLink::getCurrentInDataRate() const
{
return 0;
}
qint64 BluetoothLink::getCurrentOutDataRate() const
{
return 0;
}
//--------------------------------------------------------------------------
//-- BluetoothConfiguration
BluetoothConfiguration::BluetoothConfiguration(const QString& name)
: LinkConfiguration(name)
, _deviceDiscover(NULL)
{
}
BluetoothConfiguration::BluetoothConfiguration(BluetoothConfiguration* source)
: LinkConfiguration(source)
, _deviceDiscover(NULL)
{
_device = source->device();
}
BluetoothConfiguration::~BluetoothConfiguration()
{
if(_deviceDiscover)
{
_deviceDiscover->stop();
delete _deviceDiscover;
}
}
void BluetoothConfiguration::copyFrom(LinkConfiguration *source)
{
LinkConfiguration::copyFrom(source);
BluetoothConfiguration* usource = dynamic_cast<BluetoothConfiguration*>(source);
Q_ASSERT(usource != NULL);
_device = usource->device();
}
void BluetoothConfiguration::saveSettings(QSettings& settings, const QString& root)
{
settings.beginGroup(root);
settings.setValue("deviceName", _device.name);
#ifdef __ios__
settings.setValue("uuid", _device.uuid.toString());
#else
settings.setValue("address",_device.address);
#endif
settings.endGroup();
}
void BluetoothConfiguration::loadSettings(QSettings& settings, const QString& root)
{
settings.beginGroup(root);
_device.name = settings.value("deviceName", _device.name).toString();
#ifdef __ios__
QString suuid = settings.value("uuid", _device.uuid.toString()).toString();
_device.uuid = QUuid(suuid);
#else
_device.address = settings.value("address", _device.address).toString();
#endif
settings.endGroup();
}
void BluetoothConfiguration::updateSettings()
{
if(_link) {
BluetoothLink* ulink = dynamic_cast<BluetoothLink*>(_link);
if(ulink) {
ulink->_restartConnection();
}
}
}
void BluetoothConfiguration::stopScan()
{
if(_deviceDiscover)
{
_deviceDiscover->stop();
_deviceDiscover->deleteLater();
_deviceDiscover = NULL;
emit scanningChanged();
}
}
void BluetoothConfiguration::startScan()
{
if(!_deviceDiscover)
{
_deviceDiscover = new QBluetoothDeviceDiscoveryAgent(this);
connect(_deviceDiscover, &QBluetoothDeviceDiscoveryAgent::deviceDiscovered, this, &BluetoothConfiguration::deviceDiscovered);
connect(_deviceDiscover, &QBluetoothDeviceDiscoveryAgent::finished, this, &BluetoothConfiguration::doneScanning);
emit scanningChanged();
}
else
{
_deviceDiscover->stop();
}
_nameList.clear();
_deviceList.clear();
emit nameListChanged();
_deviceDiscover->setInquiryType(QBluetoothDeviceDiscoveryAgent::GeneralUnlimitedInquiry);
_deviceDiscover->start();
}
void BluetoothConfiguration::deviceDiscovered(QBluetoothDeviceInfo info)
{
//print_device_info(info);
if(!info.name().isEmpty() && info.isValid())
{
BluetoothData data;
data.name = info.name();
#ifdef __ios__
data.uuid = info.deviceUuid();
#else
data.address = info.address().toString();
#endif
if(!_deviceList.contains(data))
{
_deviceList += data;
_nameList += data.name;
emit nameListChanged();
return;
}
}
}
void BluetoothConfiguration::doneScanning()
{
if(_deviceDiscover)
{
_deviceDiscover->deleteLater();
_deviceDiscover = NULL;
emit scanningChanged();
}
}
void BluetoothConfiguration::setDevName(const QString &name)
{
foreach(const BluetoothData& data, _deviceList)
{
if(data.name == name)
{
_device = data;
emit devNameChanged();
#ifndef __ios__
emit addressChanged();
#endif
return;
}
}
}
QString BluetoothConfiguration::address()
{
#ifdef __ios__
return QString("");
#else
return _device.address;
#endif
}
<|endoftext|>
|
<commit_before>
#include "samson/common/coding.h" // KVFILE_NUM_HASHGROUPS
#include "samson/common/MessagesOperations.h"
#include "samson/common/SamsonSetup.h" // samson::SamsonSetup
#include "StreamManager.h" // samson::stream::StreamManager
#include "BlockBreakQueueTask.h" // samson::stream::BlockBreakQueueTask
#include "Block.h" // samson::stream::Block
#include "BlockList.h" // samson::stream::BlockList
#include "Queue.h" // OwnInterface
size_t next_pow_2( size_t value )
{
if( value < 2)
return 1;
int p = 1;
while ( true )
{
if( value == pow(2.0 , p))
return pow( 2.0 , p);
if( value < pow( 2.0 , p ) )
return pow( 2.0 , p );
p++;
}
LM_X(1,("Internal error"));
return 1;
}
namespace samson {
namespace stream
{
void BlockIdList::addIds( BlockList *list )
{
au::list< Block >::iterator block_it;
for ( block_it = list->blocks.begin() ; block_it != list->blocks.end() ; block_it++)
{
Block* block = *block_it;
size_t block_id = block->getId();
addId( block_id );
}
}
void BlockIdList::removeIds( BlockList *list )
{
au::list< Block >::iterator block_it;
for ( block_it = list->blocks.begin() ; block_it != list->blocks.end() ; block_it++)
{
Block* block = *block_it;
size_t block_id = block->getId();
removeId( block_id );
}
}
void BlockIdList::addId( size_t id )
{
block_ids.insert( id );
}
void BlockIdList::removeId( size_t id )
{
block_ids.erase( id );
}
size_t BlockIdList::num_ids()
{
return block_ids.size();
}
bool BlockIdList::containsBlockId( size_t id )
{
return ( block_ids.find( id ) != block_ids.end() );
}
#pragma mark Queue
Queue::Queue( std::string _name , StreamManager* _streamManager )
{
// Keep the name
name = _name;
// Still pending of the block
format = KVFormat("*","*");
// Create a list for blocks pending to be broken...
list = new BlockList( "queue_" + name );
// Pointer to StreamManager
streamManager = _streamManager;
// Default number of divisions
num_divisions = 1;
rate_kvs.setTimeLength( 60 );
rate_size.setTimeLength( 60 );
}
Queue::~Queue()
{
delete list;
}
void Queue::push( BlockList *list )
{
BlockInfo block_info = list->getBlockInfo();
rate_kvs.push( block_info.info.kvs );
rate_size.push( block_info.info.size );
au::list< Block >::iterator b;
for (b = list->blocks.begin() ; b != list->blocks.end() ; b++ )
push( *b );
}
void Queue::push( Block *block )
{
if( format == KVFormat("*","*") )
format = block->header->getKVFormat(); // Get the format of the first one...
else
{
if( format != block->header->getKVFormat() )
{
LM_W(("Trying to push a block with format %s to queue %s with format %s. Block rejected", block->header->getKVFormat().str().c_str() , name.c_str() , format.str().c_str() ));
return;
}
}
// Add to the list for this queue
list->add( block );
}
void Queue::getInfo( std::ostringstream& output)
{
au::xml_open(output, "queue");
au::xml_simple(output, "name", name );
// Information about the format
format.getInfo(output);
// Block list information
list->getInfo( output );
// Informat description of queue status
std::ostringstream status;
au::xml_simple(output, "num_divisions", num_divisions );
if( lock_block_ids.num_ids() > 0)
status << au::str("[ Locked %d/%d blocks ] " , lock_block_ids.num_ids() , list->getNumBlocks());
if( status.str() == "" )
status << "ready";
au::xml_simple( output , "status" , status.str() );
// Information about content
BlockInfo block_info;
update( block_info );
block_info.getInfo(output);
au::xml_simple( output , "environment" , environment.getEnvironmentDescription() );
// Information about simple rate
au::xml_single_element( output , "rate_kvs" , &rate_kvs );
au::xml_single_element( output , "rate_size" , &rate_size );
au::xml_close(output, "queue");
}
void Queue::update( BlockInfo& block_info )
{
list->update( block_info );
}
void Queue::setProperty( std::string property , std::string value )
{
environment.set( property , value );
}
void Queue::replaceAndUnlock( BlockList *from , BlockList *to )
{
replace( from , to );
unlock(from);
}
void Queue::replace( BlockList *from , BlockList *to )
{
// Replace a list of blocks by another list
list->replace( from , to );
}
void Queue::removeAndUnlock( BlockList *_list )
{
list->remove( _list );
unlock( _list );
}
void Queue::remove ( BlockList *_list )
{
list->remove( _list );
}
void Queue::unlock ( BlockList *list )
{
// Remove this ids from any possible concept
lock_block_ids.removeIds( list );
}
bool Queue::lock ( BlockList *list )
{
if( !canBelock( list ) )
return false;
// Add the block sto the id
lock_block_ids.addIds( list );
return true;
}
bool Queue::canBelock ( BlockList *list )
{
au::list< Block >::iterator block_it;
for ( block_it = list->blocks.begin() ; block_it != list->blocks.end() ; block_it++ )
{
Block* block = *block_it;
if( lock_block_ids.containsBlockId( block->getId() ) )
return false;
}
return true;
}
void Queue::getBlocksForKVRange( KVRange range , BlockList *outputBlockList )
{
au::list< Block >::iterator block_it;
for ( block_it = list->blocks.begin() ; block_it != list->blocks.end() ; block_it++ )
{
Block *block = *block_it;
KVRange block_range = block->getKVRange();
if( block_range.overlap( range ) )
outputBlockList->add( block );
}
}
bool Queue::getAndLockBlocksForKVRange( KVRange range , BlockList *outputBlockList )
{
if( !canLockBlocksForKVRange(range) )
return false;
au::list< Block >::iterator block_it;
for ( block_it = list->blocks.begin() ; block_it != list->blocks.end() ; block_it++ )
{
Block *block = *block_it;
size_t block_id = block->getId();
KVRange block_range = block->getKVRange();
if( block_range.overlap( range ) )
{
lock_block_ids.addId( block_id );
outputBlockList->add( block );
}
}
return true;
}
bool Queue::canLockBlocksForKVRange( KVRange range )
{
au::list< Block >::iterator block_it;
for ( block_it = list->blocks.begin() ; block_it != list->blocks.end() ; block_it++ )
{
Block *block = *block_it;
size_t block_id = block->getId();
KVRange block_range = block->getKVRange();
if( block_range.overlap( range ) )
if( lock_block_ids.containsBlockId(block_id) )
return false;
}
return true;
}
void Queue::review()
{
au::ExecesiveTimeAlarm alarm("Queue::review");
// Review the size contained in this queue if there is a limit defined....
size_t max_size = environment.getSizeT( "max_size" , 0 );
if( max_size > 0 )
{
BlockList tmp_block_list; // Temporal list to put extracted blocks...
while( list->getBlockInfo().size > max_size )
tmp_block_list.extractBlockFrom( list );
}
//LM_M(("Intern review queue %s" , name.c_str() ));
// Schedule new Block Break operations if necessary
if( format == KVFormat("txt","txt") )
{
//LM_M(("Queue %s nor revised since format %s= txt" , name.c_str() , format.str().c_str() ));
return; // No necessary operations for txt elements
}
// Set the minimum number of divisions ( when possible )
// Only in state queues when trying to run update-state operations
// setMinimumNumDivisions();
// Not break blocks any more
/*
while( true )
{
//LM_M(("Queue %s: Num divisions %d.... %lu blocks" , name.c_str() , num_divisions , list->blocks.size() ));
size_t max_size = SamsonSetup::shared()->getUInt64("stream.max_operation_input_size");
BlockList inputBlockList("candidates_block_division");
getBlocksToBreak( &inputBlockList , max_size );
if( inputBlockList.isEmpty() )
break;
// Schedule a block break operation
size_t id = streamManager->queueTaskManager.getNewId();
BlockBreakQueueTask *task = new BlockBreakQueueTask( id , name , num_divisions );
BlockList *input = task->getBlockList("input_0");
input->copyFrom( &inputBlockList , 0 );
task->setWorkingSize();
streamManager->queueTaskManager.add( task );
LM_T(LmtBlockManager,("Running a block-break operation for queue %s %s" , name.c_str() , input->strBlockIds().c_str() ));
}
*/
/*
// Compact if the over-headed is too high for a particular division
//LM_TODO(("To be completed..."));
if ( num_divisions > 1 )
{
for ( int n = 0 ; n < num_divisions ; n++)
{
// Create a list with all the blocks exclusive for this division
BlockList *tmp = new BlockList("compactation_for_queue");
KVRange range = rangeForDivision(n, num_divisions);
au::list< Block >::iterator block_it;
for ( block_it = list->blocks.begin() ; block_it != list->blocks.end() ; block_it++)
{
Block *block = *block_it;
if ( range.includes( block->getKVRange() ) )
tmp->add( block );
}
// If overhead is too large, compactation is required
BlockInfo block_info = tmp->getBlockInfo();
//LM_M(("Queue %s: division %d/%d %d blocks with %f overhead", name.c_str() , n , num_divisions , block_info.num_blocks , block_info.getOverhead() ));
if ( block_info.getOverhead() > 0.2 )
{
// Run a compact operation over this set
// Future work...
}
delete tmp;
}
}
*/
}
// Get some blocks that need to be broken to meet a particular number of divisions ( not locked )
void Queue::getBlocksToBreak( BlockList *outputBlockList , size_t max_size )
{
size_t total_size = 0 ;
int num_blocks = 0;
au::list< Block >::iterator b;
for (b = list->blocks.begin() ; b != list->blocks.end() ; b++)
{
Block *block = *b;
size_t block_id = block->getId();
KVRange block_range = block->getKVRange();
if( !lock_block_ids.containsBlockId( block_id ) )
{
if( !block_range.isValidForNumDivisions( num_divisions ) )
{
total_size += block->getSize();
if( num_blocks > 0 )
if (( max_size > 0) && ( total_size > max_size ))
return;
LM_T(LmtBlockManager,("Adds block to be partitioned id=%lu, num_divisions:%d, total_size:%lu, max_size:%lu" , block->getId(), num_divisions, total_size, max_size ));
lock_block_ids.addId( block->getId() );
outputBlockList->add( *b );
num_blocks++;
}
}
}
}
bool Queue::isReadyForDivisions( )
{
// Check the queue is ready for the number of divisions ( all the block break operations have finished )
au::list< Block >::iterator block_it;
for ( block_it = list->blocks.begin() ; block_it != list->blocks.end() ; block_it++ )
{
Block *block = *block_it;
KVRange block_range = block->getKVRange();
if( !block_range.isValidForNumDivisions( num_divisions ) )
return false;
}
return true;
}
void Queue::fill( samson::network::CollectionRecord* record , VisualitzationOptions options )
{
// Get block information for this queue
BlockInfo blockInfo;
update( blockInfo );
// Last component of name
/*
std::string last_component_name = name;
size_t pos = name.find_last_of("/");
if( pos != std::string::npos )
last_component_name = name.substr( pos+1 );
*/
add( record , "name" , name , "left,different" );
add( record , "#kvs" , blockInfo.info.kvs , "f=uint64,sum" );
add( record , "size" , blockInfo.info.size , "f=uint64,sum" );
if( ( options == normal ) || (options == all ) )
{
add( record , "key" , format.keyFormat , "different");
add( record , "value" , format.valueFormat , "different" );
}
if( ( options == verbose ) || (options == all ) )
{
add( record , "#kvs/s" , (size_t)rate_kvs.getRate() , "f=uint64,sum" );
add( record , "Bytes/s" , (size_t)rate_size.getRate() , "f=uint64,sum" );
}
if( ( options == verbose2 ) || (options == all ) )
{
add( record , "#Blocs" , blockInfo.num_blocks , "f=uint64,sum" );
add( record , "Size" , blockInfo.size , "f=uint64,sum" );
add( record , "on Memory" , blockInfo.size_on_memory , "f=uint64,sum" );
add( record , "on Disk" , blockInfo.size_on_disk , "f=uint64,sum" );
add( record , "Locked" , blockInfo.size_locked , "f=uint64,sum" );
add( record , "Time from" , (size_t)blockInfo.min_time , "f=time,different" );
add( record , "Time to" , (size_t)blockInfo.max_time , "f=time,different" );
}
}
}
}
<commit_msg>Minor update in ls_queue<commit_after>
#include "samson/common/coding.h" // KVFILE_NUM_HASHGROUPS
#include "samson/common/MessagesOperations.h"
#include "samson/common/SamsonSetup.h" // samson::SamsonSetup
#include "StreamManager.h" // samson::stream::StreamManager
#include "BlockBreakQueueTask.h" // samson::stream::BlockBreakQueueTask
#include "Block.h" // samson::stream::Block
#include "BlockList.h" // samson::stream::BlockList
#include "Queue.h" // OwnInterface
size_t next_pow_2( size_t value )
{
if( value < 2)
return 1;
int p = 1;
while ( true )
{
if( value == pow(2.0 , p))
return pow( 2.0 , p);
if( value < pow( 2.0 , p ) )
return pow( 2.0 , p );
p++;
}
LM_X(1,("Internal error"));
return 1;
}
namespace samson {
namespace stream
{
void BlockIdList::addIds( BlockList *list )
{
au::list< Block >::iterator block_it;
for ( block_it = list->blocks.begin() ; block_it != list->blocks.end() ; block_it++)
{
Block* block = *block_it;
size_t block_id = block->getId();
addId( block_id );
}
}
void BlockIdList::removeIds( BlockList *list )
{
au::list< Block >::iterator block_it;
for ( block_it = list->blocks.begin() ; block_it != list->blocks.end() ; block_it++)
{
Block* block = *block_it;
size_t block_id = block->getId();
removeId( block_id );
}
}
void BlockIdList::addId( size_t id )
{
block_ids.insert( id );
}
void BlockIdList::removeId( size_t id )
{
block_ids.erase( id );
}
size_t BlockIdList::num_ids()
{
return block_ids.size();
}
bool BlockIdList::containsBlockId( size_t id )
{
return ( block_ids.find( id ) != block_ids.end() );
}
#pragma mark Queue
Queue::Queue( std::string _name , StreamManager* _streamManager )
{
// Keep the name
name = _name;
// Still pending of the block
format = KVFormat("*","*");
// Create a list for blocks pending to be broken...
list = new BlockList( "queue_" + name );
// Pointer to StreamManager
streamManager = _streamManager;
// Default number of divisions
num_divisions = 1;
rate_kvs.setTimeLength( 60 );
rate_size.setTimeLength( 60 );
}
Queue::~Queue()
{
delete list;
}
void Queue::push( BlockList *list )
{
BlockInfo block_info = list->getBlockInfo();
rate_kvs.push( block_info.info.kvs );
rate_size.push( block_info.info.size );
au::list< Block >::iterator b;
for (b = list->blocks.begin() ; b != list->blocks.end() ; b++ )
push( *b );
}
void Queue::push( Block *block )
{
if( format == KVFormat("*","*") )
format = block->header->getKVFormat(); // Get the format of the first one...
else
{
if( format != block->header->getKVFormat() )
{
LM_W(("Trying to push a block with format %s to queue %s with format %s. Block rejected", block->header->getKVFormat().str().c_str() , name.c_str() , format.str().c_str() ));
return;
}
}
// Add to the list for this queue
list->add( block );
}
void Queue::getInfo( std::ostringstream& output)
{
au::xml_open(output, "queue");
au::xml_simple(output, "name", name );
// Information about the format
format.getInfo(output);
// Block list information
list->getInfo( output );
// Informat description of queue status
std::ostringstream status;
au::xml_simple(output, "num_divisions", num_divisions );
if( lock_block_ids.num_ids() > 0)
status << au::str("[ Locked %d/%d blocks ] " , lock_block_ids.num_ids() , list->getNumBlocks());
if( status.str() == "" )
status << "ready";
au::xml_simple( output , "status" , status.str() );
// Information about content
BlockInfo block_info;
update( block_info );
block_info.getInfo(output);
au::xml_simple( output , "environment" , environment.getEnvironmentDescription() );
// Information about simple rate
au::xml_single_element( output , "rate_kvs" , &rate_kvs );
au::xml_single_element( output , "rate_size" , &rate_size );
au::xml_close(output, "queue");
}
void Queue::update( BlockInfo& block_info )
{
list->update( block_info );
}
void Queue::setProperty( std::string property , std::string value )
{
environment.set( property , value );
}
void Queue::replaceAndUnlock( BlockList *from , BlockList *to )
{
replace( from , to );
unlock(from);
}
void Queue::replace( BlockList *from , BlockList *to )
{
// Replace a list of blocks by another list
list->replace( from , to );
}
void Queue::removeAndUnlock( BlockList *_list )
{
list->remove( _list );
unlock( _list );
}
void Queue::remove ( BlockList *_list )
{
list->remove( _list );
}
void Queue::unlock ( BlockList *list )
{
// Remove this ids from any possible concept
lock_block_ids.removeIds( list );
}
bool Queue::lock ( BlockList *list )
{
if( !canBelock( list ) )
return false;
// Add the block sto the id
lock_block_ids.addIds( list );
return true;
}
bool Queue::canBelock ( BlockList *list )
{
au::list< Block >::iterator block_it;
for ( block_it = list->blocks.begin() ; block_it != list->blocks.end() ; block_it++ )
{
Block* block = *block_it;
if( lock_block_ids.containsBlockId( block->getId() ) )
return false;
}
return true;
}
void Queue::getBlocksForKVRange( KVRange range , BlockList *outputBlockList )
{
au::list< Block >::iterator block_it;
for ( block_it = list->blocks.begin() ; block_it != list->blocks.end() ; block_it++ )
{
Block *block = *block_it;
KVRange block_range = block->getKVRange();
if( block_range.overlap( range ) )
outputBlockList->add( block );
}
}
bool Queue::getAndLockBlocksForKVRange( KVRange range , BlockList *outputBlockList )
{
if( !canLockBlocksForKVRange(range) )
return false;
au::list< Block >::iterator block_it;
for ( block_it = list->blocks.begin() ; block_it != list->blocks.end() ; block_it++ )
{
Block *block = *block_it;
size_t block_id = block->getId();
KVRange block_range = block->getKVRange();
if( block_range.overlap( range ) )
{
lock_block_ids.addId( block_id );
outputBlockList->add( block );
}
}
return true;
}
bool Queue::canLockBlocksForKVRange( KVRange range )
{
au::list< Block >::iterator block_it;
for ( block_it = list->blocks.begin() ; block_it != list->blocks.end() ; block_it++ )
{
Block *block = *block_it;
size_t block_id = block->getId();
KVRange block_range = block->getKVRange();
if( block_range.overlap( range ) )
if( lock_block_ids.containsBlockId(block_id) )
return false;
}
return true;
}
void Queue::review()
{
au::ExecesiveTimeAlarm alarm("Queue::review");
// Review the size contained in this queue if there is a limit defined....
size_t max_size = environment.getSizeT( "max_size" , 0 );
if( max_size > 0 )
{
BlockList tmp_block_list; // Temporal list to put extracted blocks...
while( list->getBlockInfo().size > max_size )
tmp_block_list.extractBlockFrom( list );
}
//LM_M(("Intern review queue %s" , name.c_str() ));
// Schedule new Block Break operations if necessary
if( format == KVFormat("txt","txt") )
{
//LM_M(("Queue %s nor revised since format %s= txt" , name.c_str() , format.str().c_str() ));
return; // No necessary operations for txt elements
}
// Set the minimum number of divisions ( when possible )
// Only in state queues when trying to run update-state operations
// setMinimumNumDivisions();
// Not break blocks any more
/*
while( true )
{
//LM_M(("Queue %s: Num divisions %d.... %lu blocks" , name.c_str() , num_divisions , list->blocks.size() ));
size_t max_size = SamsonSetup::shared()->getUInt64("stream.max_operation_input_size");
BlockList inputBlockList("candidates_block_division");
getBlocksToBreak( &inputBlockList , max_size );
if( inputBlockList.isEmpty() )
break;
// Schedule a block break operation
size_t id = streamManager->queueTaskManager.getNewId();
BlockBreakQueueTask *task = new BlockBreakQueueTask( id , name , num_divisions );
BlockList *input = task->getBlockList("input_0");
input->copyFrom( &inputBlockList , 0 );
task->setWorkingSize();
streamManager->queueTaskManager.add( task );
LM_T(LmtBlockManager,("Running a block-break operation for queue %s %s" , name.c_str() , input->strBlockIds().c_str() ));
}
*/
/*
// Compact if the over-headed is too high for a particular division
//LM_TODO(("To be completed..."));
if ( num_divisions > 1 )
{
for ( int n = 0 ; n < num_divisions ; n++)
{
// Create a list with all the blocks exclusive for this division
BlockList *tmp = new BlockList("compactation_for_queue");
KVRange range = rangeForDivision(n, num_divisions);
au::list< Block >::iterator block_it;
for ( block_it = list->blocks.begin() ; block_it != list->blocks.end() ; block_it++)
{
Block *block = *block_it;
if ( range.includes( block->getKVRange() ) )
tmp->add( block );
}
// If overhead is too large, compactation is required
BlockInfo block_info = tmp->getBlockInfo();
//LM_M(("Queue %s: division %d/%d %d blocks with %f overhead", name.c_str() , n , num_divisions , block_info.num_blocks , block_info.getOverhead() ));
if ( block_info.getOverhead() > 0.2 )
{
// Run a compact operation over this set
// Future work...
}
delete tmp;
}
}
*/
}
// Get some blocks that need to be broken to meet a particular number of divisions ( not locked )
void Queue::getBlocksToBreak( BlockList *outputBlockList , size_t max_size )
{
size_t total_size = 0 ;
int num_blocks = 0;
au::list< Block >::iterator b;
for (b = list->blocks.begin() ; b != list->blocks.end() ; b++)
{
Block *block = *b;
size_t block_id = block->getId();
KVRange block_range = block->getKVRange();
if( !lock_block_ids.containsBlockId( block_id ) )
{
if( !block_range.isValidForNumDivisions( num_divisions ) )
{
total_size += block->getSize();
if( num_blocks > 0 )
if (( max_size > 0) && ( total_size > max_size ))
return;
LM_T(LmtBlockManager,("Adds block to be partitioned id=%lu, num_divisions:%d, total_size:%lu, max_size:%lu" , block->getId(), num_divisions, total_size, max_size ));
lock_block_ids.addId( block->getId() );
outputBlockList->add( *b );
num_blocks++;
}
}
}
}
bool Queue::isReadyForDivisions( )
{
// Check the queue is ready for the number of divisions ( all the block break operations have finished )
au::list< Block >::iterator block_it;
for ( block_it = list->blocks.begin() ; block_it != list->blocks.end() ; block_it++ )
{
Block *block = *block_it;
KVRange block_range = block->getKVRange();
if( !block_range.isValidForNumDivisions( num_divisions ) )
return false;
}
return true;
}
void Queue::fill( samson::network::CollectionRecord* record , VisualitzationOptions options )
{
// Get block information for this queue
BlockInfo blockInfo;
update( blockInfo );
// Last component of name
/*
std::string last_component_name = name;
size_t pos = name.find_last_of("/");
if( pos != std::string::npos )
last_component_name = name.substr( pos+1 );
*/
add( record , "name" , name , "left,different" );
add( record , "#kvs" , blockInfo.info.kvs , "f=uint64,sum" );
add( record , "size" , blockInfo.info.size , "f=uint64,sum" );
if( ( options == normal ) || (options == all ) )
{
add( record , "key" , format.keyFormat , "different");
add( record , "value" , format.valueFormat , "different" );
}
if( ( options == verbose ) || (options == all ) )
{
add( record , "Total #kvs" , (size_t)rate_kvs.getTotalSize() , "f=uint64,sum" );
add( record , "Total size" , (size_t)rate_size.getTotalSize() , "f=uint64,sum" );
add( record , "#kvs/s" , (size_t)rate_kvs.getRate() , "f=uint64,sum" );
add( record , "Bytes/s" , (size_t)rate_size.getRate() , "f=uint64,sum" );
}
if( ( options == verbose2 ) || (options == all ) )
{
add( record , "#Blocs" , blockInfo.num_blocks , "f=uint64,sum" );
add( record , "Size" , blockInfo.size , "f=uint64,sum" );
add( record , "on Memory" , blockInfo.size_on_memory , "f=uint64,sum" );
add( record , "on Disk" , blockInfo.size_on_disk , "f=uint64,sum" );
add( record , "Locked" , blockInfo.size_locked , "f=uint64,sum" );
add( record , "Time from" , (size_t)blockInfo.min_time , "f=time,different" );
add( record , "Time to" , (size_t)blockInfo.max_time , "f=time,different" );
}
}
}
}
<|endoftext|>
|
<commit_before>
// STL includes
#include <cassert>
// QT includes
#include <QDateTime>
#include <QThread>
#include <QRegExp>
#include <QString>
#include <QStringList>
// JsonSchema include
#include <utils/jsonschema/JsonFactory.h>
// hyperion include
#include <hyperion/Hyperion.h>
#include <hyperion/ImageProcessorFactory.h>
// Leddevice includes
#include <leddevice/LedDevice.h>
#include <leddevice/LedDeviceFactory.h>
#include "MultiColorTransform.h"
#include "LinearColorSmoothing.h"
// effect engine includes
#include <effectengine/EffectEngine.h>
Hyperion::ColorOrder Hyperion::createColorOrder(const Json::Value &deviceConfig)
{
// deprecated: force BGR when the deprecated flag is present and set to true
if (deviceConfig.get("bgr-output", false).asBool())
{
return ORDER_BGR;
}
std::string order = deviceConfig.get("colorOrder", "rgb").asString();
if (order == "rgb")
{
return ORDER_RGB;
}
else if (order == "bgr")
{
return ORDER_BGR;
}
else if (order == "rbg")
{
return ORDER_RBG;
}
else if (order == "brg")
{
return ORDER_BRG;
}
else if (order == "gbr")
{
return ORDER_GBR;
}
else if (order == "grb")
{
return ORDER_GRB;
}
else
{
std::cout << "Unknown color order defined (" << order << "). Using RGB." << std::endl;
}
return ORDER_RGB;
}
ColorTransform * Hyperion::createColorTransform(const Json::Value & transformConfig)
{
const std::string id = transformConfig.get("id", "default").asString();
RgbChannelTransform * redTransform = createRgbChannelTransform(transformConfig["red"]);
RgbChannelTransform * greenTransform = createRgbChannelTransform(transformConfig["green"]);
RgbChannelTransform * blueTransform = createRgbChannelTransform(transformConfig["blue"]);
HsvTransform * hsvTransform = createHsvTransform(transformConfig["hsv"]);
ColorTransform * transform = new ColorTransform();
transform->_id = id;
transform->_rgbRedTransform = *redTransform;
transform->_rgbGreenTransform = *greenTransform;
transform->_rgbBlueTransform = *blueTransform;
transform->_hsvTransform = *hsvTransform;
// Cleanup the allocated individual transforms
delete redTransform;
delete greenTransform;
delete blueTransform;
delete hsvTransform;
return transform;
}
MultiColorTransform * Hyperion::createLedColorsTransform(const unsigned ledCnt, const Json::Value & colorConfig)
{
// Create the result, the transforms are added to this
MultiColorTransform * transform = new MultiColorTransform(ledCnt);
const Json::Value transformConfig = colorConfig.get("transform", Json::nullValue);
if (transformConfig.isNull())
{
// Old style color transformation config (just one for all leds)
ColorTransform * colorTransform = createColorTransform(colorConfig);
transform->addTransform(colorTransform);
transform->setTransformForLed(colorTransform->_id, 0, ledCnt-1);
}
else if (!transformConfig.isArray())
{
ColorTransform * colorTransform = createColorTransform(transformConfig);
transform->addTransform(colorTransform);
transform->setTransformForLed(colorTransform->_id, 0, ledCnt-1);
}
else
{
const QRegExp overallExp("([0-9]+(\\-[0-9]+)?)(,[ ]*([0-9]+(\\-[0-9]+)?))*");
for (Json::UInt i = 0; i < transformConfig.size(); ++i)
{
const Json::Value & config = transformConfig[i];
ColorTransform * colorTransform = createColorTransform(config);
transform->addTransform(colorTransform);
const QString ledIndicesStr = QString(config.get("leds", "").asCString()).trimmed();
if (ledIndicesStr.compare("*") == 0)
{
// Special case for indices '*' => all leds
transform->setTransformForLed(colorTransform->_id, 0, ledCnt-1);
std::cout << "ColorTransform '" << colorTransform->_id << "' => [0; "<< ledCnt-1 << "]" << std::endl;
continue;
}
if (!overallExp.exactMatch(ledIndicesStr))
{
std::cerr << "Given led indices " << i << " not correct format: " << ledIndicesStr.toStdString() << std::endl;
continue;
}
std::cout << "ColorTransform '" << colorTransform->_id << "' => [";
const QStringList ledIndexList = ledIndicesStr.split(",");
for (int i=0; i<ledIndexList.size(); ++i) {
if (i > 0)
{
std::cout << ", ";
}
if (ledIndexList[i].contains("-"))
{
QStringList ledIndices = ledIndexList[i].split("-");
int startInd = ledIndices[0].toInt();
int endInd = ledIndices[1].toInt();
transform->setTransformForLed(colorTransform->_id, startInd, endInd);
std::cout << startInd << "-" << endInd;
}
else
{
int index = ledIndexList[i].toInt();
transform->setTransformForLed(colorTransform->_id, index, index);
std::cout << index;
}
}
std::cout << "]" << std::endl;
}
}
return transform;
}
HsvTransform * Hyperion::createHsvTransform(const Json::Value & hsvConfig)
{
const double saturationGain = hsvConfig.get("saturationGain", 1.0).asDouble();
const double valueGain = hsvConfig.get("valueGain", 1.0).asDouble();
return new HsvTransform(saturationGain, valueGain);
}
RgbChannelTransform* Hyperion::createRgbChannelTransform(const Json::Value& colorConfig)
{
const double threshold = colorConfig.get("threshold", 0.0).asDouble();
const double gamma = colorConfig.get("gamma", 1.0).asDouble();
const double blacklevel = colorConfig.get("blacklevel", 0.0).asDouble();
const double whitelevel = colorConfig.get("whitelevel", 1.0).asDouble();
RgbChannelTransform* transform = new RgbChannelTransform(threshold, gamma, blacklevel, whitelevel);
return transform;
}
LedString Hyperion::createLedString(const Json::Value& ledsConfig)
{
LedString ledString;
for (const Json::Value& ledConfig : ledsConfig)
{
Led led;
led.index = ledConfig["index"].asInt();
const Json::Value& hscanConfig = ledConfig["hscan"];
const Json::Value& vscanConfig = ledConfig["vscan"];
led.minX_frac = std::max(0.0, std::min(1.0, hscanConfig["minimum"].asDouble()));
led.maxX_frac = std::max(0.0, std::min(1.0, hscanConfig["maximum"].asDouble()));
led.minY_frac = std::max(0.0, std::min(1.0, vscanConfig["minimum"].asDouble()));
led.maxY_frac = std::max(0.0, std::min(1.0, vscanConfig["maximum"].asDouble()));
// Fix if the user swapped min and max
if (led.minX_frac > led.maxX_frac)
{
std::swap(led.minX_frac, led.maxX_frac);
}
if (led.minY_frac > led.maxY_frac)
{
std::swap(led.minY_frac, led.maxY_frac);
}
ledString.leds().push_back(led);
}
// Make sure the leds are sorted (on their indices)
std::sort(ledString.leds().begin(), ledString.leds().end(), [](const Led& lhs, const Led& rhs){ return lhs.index < rhs.index; });
return ledString;
}
LedDevice * Hyperion::createColorSmoothing(const Json::Value & smoothingConfig, LedDevice * ledDevice)
{
std::string type = smoothingConfig.get("type", "none").asString();
std::transform(type.begin(), type.end(), type.begin(), ::tolower);
if (type == "none")
{
std::cout << "Not creating any smoothing" << std::endl;
return ledDevice;
}
else if (type == "linear")
{
if (!smoothingConfig.isMember("time_ms"))
{
std::cout << "Unable to create smoothing of type linear because of missing parameter 'time_ms'" << std::endl;
}
else if (!smoothingConfig.isMember("updateFrequency"))
{
std::cout << "Unable to create smoothing of type linear because of missing parameter 'updateFrequency'" << std::endl;
}
else
{
std::cout << "Creating linear smoothing" << std::endl;
return new LinearColorSmoothing(ledDevice, smoothingConfig["updateFrequency"].asDouble(), smoothingConfig["time_ms"].asInt());
}
}
else
{
std::cout << "Unable to create smoothing of type " << type << std::endl;
}
return ledDevice;
}
Hyperion::Hyperion(const Json::Value &jsonConfig) :
_ledString(createLedString(jsonConfig["leds"])),
_muxer(_ledString.leds().size()),
_raw2ledTransform(createLedColorsTransform(_ledString.leds().size(), jsonConfig["color"])),
_colorOrder(createColorOrder(jsonConfig["device"])),
_device(LedDeviceFactory::construct(jsonConfig["device"])),
_effectEngine(nullptr),
_timer()
{
if (!_raw2ledTransform->verifyTransforms())
{
throw std::runtime_error("Color transformation incorrectly set");
}
// initialize the image processor factory
ImageProcessorFactory::getInstance().init(_ledString, jsonConfig["blackborderdetector"].get("enable", true).asBool());
// initialize the color smoothing filter
_device = createColorSmoothing(jsonConfig["color"]["smoothing"], _device);
// setup the timer
_timer.setSingleShot(true);
QObject::connect(&_timer, SIGNAL(timeout()), this, SLOT(update()));
// create the effect engine
_effectEngine = new EffectEngine(this, jsonConfig["effects"]);
// initialize the leds
update();
}
Hyperion::~Hyperion()
{
// switch off all leds
clearall();
_device->switchOff();
// delete the effect engine
delete _effectEngine;
// Delete the Led-String
delete _device;
// delete the color transform
delete _raw2ledTransform;
}
unsigned Hyperion::getLedCount() const
{
return _ledString.leds().size();
}
void Hyperion::setColor(int priority, const ColorRgb &color, const int timeout_ms, bool clearEffects)
{
// create led output
std::vector<ColorRgb> ledColors(_ledString.leds().size(), color);
// set colors
setColors(priority, ledColors, timeout_ms, clearEffects);
}
void Hyperion::setColors(int priority, const std::vector<ColorRgb>& ledColors, const int timeout_ms, bool clearEffects)
{
// clear effects if this call does not come from an effect
if (clearEffects)
{
_effectEngine->channelCleared(priority);
}
if (timeout_ms > 0)
{
const uint64_t timeoutTime = QDateTime::currentMSecsSinceEpoch() + timeout_ms;
_muxer.setInput(priority, ledColors, timeoutTime);
}
else
{
_muxer.setInput(priority, ledColors);
}
if (priority == _muxer.getCurrentPriority())
{
update();
}
}
const std::vector<std::string> & Hyperion::getTransformIds() const
{
return _raw2ledTransform->getTransformIds();
}
ColorTransform * Hyperion::getTransform(const std::string& id)
{
return _raw2ledTransform->getTransform(id);
}
void Hyperion::transformsUpdated()
{
update();
}
void Hyperion::clear(int priority)
{
if (_muxer.hasPriority(priority))
{
_muxer.clearInput(priority);
// update leds if necessary
if (priority < _muxer.getCurrentPriority());
{
update();
}
}
// send clear signal to the effect engine
// (outside the check so the effect gets cleared even when the effect is not sending colors)
_effectEngine->channelCleared(priority);
}
void Hyperion::clearall()
{
_muxer.clearAll();
// update leds
update();
// send clearall signal to the effect engine
_effectEngine->allChannelsCleared();
}
QList<int> Hyperion::getActivePriorities() const
{
return _muxer.getPriorities();
}
const Hyperion::InputInfo &Hyperion::getPriorityInfo(const int priority) const
{
return _muxer.getInputInfo(priority);
}
const std::list<EffectDefinition> & Hyperion::getEffects() const
{
return _effectEngine->getEffects();
}
int Hyperion::setEffect(const std::string &effectName, int priority, int timeout)
{
return _effectEngine->runEffect(effectName, priority, timeout);
}
int Hyperion::setEffect(const std::string &effectName, const Json::Value &args, int priority, int timeout)
{
return _effectEngine->runEffect(effectName, args, priority, timeout);
}
void Hyperion::update()
{
// Update the muxer, cleaning obsolete priorities
_muxer.setCurrentTime(QDateTime::currentMSecsSinceEpoch());
// Obtain the current priority channel
int priority = _muxer.getCurrentPriority();
const PriorityMuxer::InputInfo & priorityInfo = _muxer.getInputInfo(priority);
// Apply the transform to each led and color-channel
std::vector<ColorRgb> ledColors = _raw2ledTransform->applyTransform(priorityInfo.ledColors);
for (ColorRgb& color : ledColors)
{
// correct the color byte order
switch (_colorOrder)
{
case ORDER_RGB:
// leave as it is
break;
case ORDER_BGR:
std::swap(color.red, color.blue);
break;
case ORDER_RBG:
std::swap(color.green, color.blue);
break;
case ORDER_GRB:
std::swap(color.red, color.green);
break;
case ORDER_GBR:
{
uint8_t temp = color.red;
color.red = color.green;
color.green = color.blue;
color.blue = temp;
break;
}
case ORDER_BRG:
{
uint8_t temp = color.red;
color.red = color.blue;
color.blue = color.green;
color.green = temp;
break;
}
}
}
// Write the data to the device
_device->write(ledColors);
// Start the timeout-timer
if (priorityInfo.timeoutTime_ms == -1)
{
_timer.stop();
}
else
{
int timeout_ms = std::max(0, int(priorityInfo.timeoutTime_ms - QDateTime::currentMSecsSinceEpoch()));
_timer.start(timeout_ms);
}
}
<commit_msg>Fixed minor bug (found by clang :-) ) with incorrect ; after if statemtn<commit_after>
// STL includes
#include <cassert>
// QT includes
#include <QDateTime>
#include <QThread>
#include <QRegExp>
#include <QString>
#include <QStringList>
// JsonSchema include
#include <utils/jsonschema/JsonFactory.h>
// hyperion include
#include <hyperion/Hyperion.h>
#include <hyperion/ImageProcessorFactory.h>
// Leddevice includes
#include <leddevice/LedDevice.h>
#include <leddevice/LedDeviceFactory.h>
#include "MultiColorTransform.h"
#include "LinearColorSmoothing.h"
// effect engine includes
#include <effectengine/EffectEngine.h>
Hyperion::ColorOrder Hyperion::createColorOrder(const Json::Value &deviceConfig)
{
// deprecated: force BGR when the deprecated flag is present and set to true
if (deviceConfig.get("bgr-output", false).asBool())
{
return ORDER_BGR;
}
std::string order = deviceConfig.get("colorOrder", "rgb").asString();
if (order == "rgb")
{
return ORDER_RGB;
}
else if (order == "bgr")
{
return ORDER_BGR;
}
else if (order == "rbg")
{
return ORDER_RBG;
}
else if (order == "brg")
{
return ORDER_BRG;
}
else if (order == "gbr")
{
return ORDER_GBR;
}
else if (order == "grb")
{
return ORDER_GRB;
}
else
{
std::cout << "Unknown color order defined (" << order << "). Using RGB." << std::endl;
}
return ORDER_RGB;
}
ColorTransform * Hyperion::createColorTransform(const Json::Value & transformConfig)
{
const std::string id = transformConfig.get("id", "default").asString();
RgbChannelTransform * redTransform = createRgbChannelTransform(transformConfig["red"]);
RgbChannelTransform * greenTransform = createRgbChannelTransform(transformConfig["green"]);
RgbChannelTransform * blueTransform = createRgbChannelTransform(transformConfig["blue"]);
HsvTransform * hsvTransform = createHsvTransform(transformConfig["hsv"]);
ColorTransform * transform = new ColorTransform();
transform->_id = id;
transform->_rgbRedTransform = *redTransform;
transform->_rgbGreenTransform = *greenTransform;
transform->_rgbBlueTransform = *blueTransform;
transform->_hsvTransform = *hsvTransform;
// Cleanup the allocated individual transforms
delete redTransform;
delete greenTransform;
delete blueTransform;
delete hsvTransform;
return transform;
}
MultiColorTransform * Hyperion::createLedColorsTransform(const unsigned ledCnt, const Json::Value & colorConfig)
{
// Create the result, the transforms are added to this
MultiColorTransform * transform = new MultiColorTransform(ledCnt);
const Json::Value transformConfig = colorConfig.get("transform", Json::nullValue);
if (transformConfig.isNull())
{
// Old style color transformation config (just one for all leds)
ColorTransform * colorTransform = createColorTransform(colorConfig);
transform->addTransform(colorTransform);
transform->setTransformForLed(colorTransform->_id, 0, ledCnt-1);
}
else if (!transformConfig.isArray())
{
ColorTransform * colorTransform = createColorTransform(transformConfig);
transform->addTransform(colorTransform);
transform->setTransformForLed(colorTransform->_id, 0, ledCnt-1);
}
else
{
const QRegExp overallExp("([0-9]+(\\-[0-9]+)?)(,[ ]*([0-9]+(\\-[0-9]+)?))*");
for (Json::UInt i = 0; i < transformConfig.size(); ++i)
{
const Json::Value & config = transformConfig[i];
ColorTransform * colorTransform = createColorTransform(config);
transform->addTransform(colorTransform);
const QString ledIndicesStr = QString(config.get("leds", "").asCString()).trimmed();
if (ledIndicesStr.compare("*") == 0)
{
// Special case for indices '*' => all leds
transform->setTransformForLed(colorTransform->_id, 0, ledCnt-1);
std::cout << "ColorTransform '" << colorTransform->_id << "' => [0; "<< ledCnt-1 << "]" << std::endl;
continue;
}
if (!overallExp.exactMatch(ledIndicesStr))
{
std::cerr << "Given led indices " << i << " not correct format: " << ledIndicesStr.toStdString() << std::endl;
continue;
}
std::cout << "ColorTransform '" << colorTransform->_id << "' => [";
const QStringList ledIndexList = ledIndicesStr.split(",");
for (int i=0; i<ledIndexList.size(); ++i) {
if (i > 0)
{
std::cout << ", ";
}
if (ledIndexList[i].contains("-"))
{
QStringList ledIndices = ledIndexList[i].split("-");
int startInd = ledIndices[0].toInt();
int endInd = ledIndices[1].toInt();
transform->setTransformForLed(colorTransform->_id, startInd, endInd);
std::cout << startInd << "-" << endInd;
}
else
{
int index = ledIndexList[i].toInt();
transform->setTransformForLed(colorTransform->_id, index, index);
std::cout << index;
}
}
std::cout << "]" << std::endl;
}
}
return transform;
}
HsvTransform * Hyperion::createHsvTransform(const Json::Value & hsvConfig)
{
const double saturationGain = hsvConfig.get("saturationGain", 1.0).asDouble();
const double valueGain = hsvConfig.get("valueGain", 1.0).asDouble();
return new HsvTransform(saturationGain, valueGain);
}
RgbChannelTransform* Hyperion::createRgbChannelTransform(const Json::Value& colorConfig)
{
const double threshold = colorConfig.get("threshold", 0.0).asDouble();
const double gamma = colorConfig.get("gamma", 1.0).asDouble();
const double blacklevel = colorConfig.get("blacklevel", 0.0).asDouble();
const double whitelevel = colorConfig.get("whitelevel", 1.0).asDouble();
RgbChannelTransform* transform = new RgbChannelTransform(threshold, gamma, blacklevel, whitelevel);
return transform;
}
LedString Hyperion::createLedString(const Json::Value& ledsConfig)
{
LedString ledString;
for (const Json::Value& ledConfig : ledsConfig)
{
Led led;
led.index = ledConfig["index"].asInt();
const Json::Value& hscanConfig = ledConfig["hscan"];
const Json::Value& vscanConfig = ledConfig["vscan"];
led.minX_frac = std::max(0.0, std::min(1.0, hscanConfig["minimum"].asDouble()));
led.maxX_frac = std::max(0.0, std::min(1.0, hscanConfig["maximum"].asDouble()));
led.minY_frac = std::max(0.0, std::min(1.0, vscanConfig["minimum"].asDouble()));
led.maxY_frac = std::max(0.0, std::min(1.0, vscanConfig["maximum"].asDouble()));
// Fix if the user swapped min and max
if (led.minX_frac > led.maxX_frac)
{
std::swap(led.minX_frac, led.maxX_frac);
}
if (led.minY_frac > led.maxY_frac)
{
std::swap(led.minY_frac, led.maxY_frac);
}
ledString.leds().push_back(led);
}
// Make sure the leds are sorted (on their indices)
std::sort(ledString.leds().begin(), ledString.leds().end(), [](const Led& lhs, const Led& rhs){ return lhs.index < rhs.index; });
return ledString;
}
LedDevice * Hyperion::createColorSmoothing(const Json::Value & smoothingConfig, LedDevice * ledDevice)
{
std::string type = smoothingConfig.get("type", "none").asString();
std::transform(type.begin(), type.end(), type.begin(), ::tolower);
if (type == "none")
{
std::cout << "Not creating any smoothing" << std::endl;
return ledDevice;
}
else if (type == "linear")
{
if (!smoothingConfig.isMember("time_ms"))
{
std::cout << "Unable to create smoothing of type linear because of missing parameter 'time_ms'" << std::endl;
}
else if (!smoothingConfig.isMember("updateFrequency"))
{
std::cout << "Unable to create smoothing of type linear because of missing parameter 'updateFrequency'" << std::endl;
}
else
{
std::cout << "Creating linear smoothing" << std::endl;
return new LinearColorSmoothing(ledDevice, smoothingConfig["updateFrequency"].asDouble(), smoothingConfig["time_ms"].asInt());
}
}
else
{
std::cout << "Unable to create smoothing of type " << type << std::endl;
}
return ledDevice;
}
Hyperion::Hyperion(const Json::Value &jsonConfig) :
_ledString(createLedString(jsonConfig["leds"])),
_muxer(_ledString.leds().size()),
_raw2ledTransform(createLedColorsTransform(_ledString.leds().size(), jsonConfig["color"])),
_colorOrder(createColorOrder(jsonConfig["device"])),
_device(LedDeviceFactory::construct(jsonConfig["device"])),
_effectEngine(nullptr),
_timer()
{
if (!_raw2ledTransform->verifyTransforms())
{
throw std::runtime_error("Color transformation incorrectly set");
}
// initialize the image processor factory
ImageProcessorFactory::getInstance().init(_ledString, jsonConfig["blackborderdetector"].get("enable", true).asBool());
// initialize the color smoothing filter
_device = createColorSmoothing(jsonConfig["color"]["smoothing"], _device);
// setup the timer
_timer.setSingleShot(true);
QObject::connect(&_timer, SIGNAL(timeout()), this, SLOT(update()));
// create the effect engine
_effectEngine = new EffectEngine(this, jsonConfig["effects"]);
// initialize the leds
update();
}
Hyperion::~Hyperion()
{
// switch off all leds
clearall();
_device->switchOff();
// delete the effect engine
delete _effectEngine;
// Delete the Led-String
delete _device;
// delete the color transform
delete _raw2ledTransform;
}
unsigned Hyperion::getLedCount() const
{
return _ledString.leds().size();
}
void Hyperion::setColor(int priority, const ColorRgb &color, const int timeout_ms, bool clearEffects)
{
// create led output
std::vector<ColorRgb> ledColors(_ledString.leds().size(), color);
// set colors
setColors(priority, ledColors, timeout_ms, clearEffects);
}
void Hyperion::setColors(int priority, const std::vector<ColorRgb>& ledColors, const int timeout_ms, bool clearEffects)
{
// clear effects if this call does not come from an effect
if (clearEffects)
{
_effectEngine->channelCleared(priority);
}
if (timeout_ms > 0)
{
const uint64_t timeoutTime = QDateTime::currentMSecsSinceEpoch() + timeout_ms;
_muxer.setInput(priority, ledColors, timeoutTime);
}
else
{
_muxer.setInput(priority, ledColors);
}
if (priority == _muxer.getCurrentPriority())
{
update();
}
}
const std::vector<std::string> & Hyperion::getTransformIds() const
{
return _raw2ledTransform->getTransformIds();
}
ColorTransform * Hyperion::getTransform(const std::string& id)
{
return _raw2ledTransform->getTransform(id);
}
void Hyperion::transformsUpdated()
{
update();
}
void Hyperion::clear(int priority)
{
if (_muxer.hasPriority(priority))
{
_muxer.clearInput(priority);
// update leds if necessary
if (priority < _muxer.getCurrentPriority())
{
update();
}
}
// send clear signal to the effect engine
// (outside the check so the effect gets cleared even when the effect is not sending colors)
_effectEngine->channelCleared(priority);
}
void Hyperion::clearall()
{
_muxer.clearAll();
// update leds
update();
// send clearall signal to the effect engine
_effectEngine->allChannelsCleared();
}
QList<int> Hyperion::getActivePriorities() const
{
return _muxer.getPriorities();
}
const Hyperion::InputInfo &Hyperion::getPriorityInfo(const int priority) const
{
return _muxer.getInputInfo(priority);
}
const std::list<EffectDefinition> & Hyperion::getEffects() const
{
return _effectEngine->getEffects();
}
int Hyperion::setEffect(const std::string &effectName, int priority, int timeout)
{
return _effectEngine->runEffect(effectName, priority, timeout);
}
int Hyperion::setEffect(const std::string &effectName, const Json::Value &args, int priority, int timeout)
{
return _effectEngine->runEffect(effectName, args, priority, timeout);
}
void Hyperion::update()
{
// Update the muxer, cleaning obsolete priorities
_muxer.setCurrentTime(QDateTime::currentMSecsSinceEpoch());
// Obtain the current priority channel
int priority = _muxer.getCurrentPriority();
const PriorityMuxer::InputInfo & priorityInfo = _muxer.getInputInfo(priority);
// Apply the transform to each led and color-channel
std::vector<ColorRgb> ledColors = _raw2ledTransform->applyTransform(priorityInfo.ledColors);
for (ColorRgb& color : ledColors)
{
// correct the color byte order
switch (_colorOrder)
{
case ORDER_RGB:
// leave as it is
break;
case ORDER_BGR:
std::swap(color.red, color.blue);
break;
case ORDER_RBG:
std::swap(color.green, color.blue);
break;
case ORDER_GRB:
std::swap(color.red, color.green);
break;
case ORDER_GBR:
{
uint8_t temp = color.red;
color.red = color.green;
color.green = color.blue;
color.blue = temp;
break;
}
case ORDER_BRG:
{
uint8_t temp = color.red;
color.red = color.blue;
color.blue = color.green;
color.green = temp;
break;
}
}
}
// Write the data to the device
_device->write(ledColors);
// Start the timeout-timer
if (priorityInfo.timeoutTime_ms == -1)
{
_timer.stop();
}
else
{
int timeout_ms = std::max(0, int(priorityInfo.timeoutTime_ms - QDateTime::currentMSecsSinceEpoch()));
_timer.start(timeout_ms);
}
}
<|endoftext|>
|
<commit_before>#include <ScriptObject.h>
#include <Actor/Player.h>
#include "Actor/EventObject.h"
#include "Territory/HousingZone.h"
#include "Manager/TerritoryMgr.h"
#include "Framework.h"
using namespace Sapphire;
class HousingEstateEntrance :
public Sapphire::ScriptAPI::EventObjectScript
{
public:
HousingEstateEntrance() :
Sapphire::ScriptAPI::EventObjectScript( 2002737 )
{
}
void onTalk( uint32_t eventId, Entity::Player& player, Entity::EventObject& eobj ) override
{
player.sendDebug( "Found plot entrance for plot: " + std::to_string( eobj.getHousingLink() >> 8 ) );
player.playScene( eventId, 0, 0, [this, eobj]( Entity::Player& player, const Event::SceneResult& result )
{
auto terriMgr = getFramework()->get< Sapphire::World::Manager::TerritoryMgr >();
if( !terriMgr )
return;
auto zone = std::dynamic_pointer_cast< HousingZone >( player.getCurrentZone() );
if( !zone )
return;
Common::LandIdent ident;
ident.landId = eobj.getHousingLink() >> 8;
ident.territoryTypeId = zone->getTerritoryTypeId();
ident.wardNum = zone->getWardNum();
ident.worldId = 67;
auto internalZone = terriMgr->findOrCreateHousingInterior( ident );
if( internalZone )
{
player.sendDebug( "created zone with guid: " + std::to_string( internalZone->getGuId() ) + "\nname: " + internalZone->getName() );
}
// param2 == 1 when player wants to enter house
if( result.param2 != 1 )
return;
player.eventFinish( result.eventId, 1 );
player.setPos( { 0.f, 0.f, 0.f } );
player.setInstance( internalZone );
} );
}
};<commit_msg>only spawn/lookup house instance if player chooses to enter<commit_after>#include <ScriptObject.h>
#include <Actor/Player.h>
#include "Actor/EventObject.h"
#include "Territory/HousingZone.h"
#include "Manager/TerritoryMgr.h"
#include "Framework.h"
using namespace Sapphire;
class HousingEstateEntrance :
public Sapphire::ScriptAPI::EventObjectScript
{
public:
HousingEstateEntrance() :
Sapphire::ScriptAPI::EventObjectScript( 2002737 )
{
}
void onTalk( uint32_t eventId, Entity::Player& player, Entity::EventObject& eobj ) override
{
player.sendDebug( "Found plot entrance for plot: " + std::to_string( eobj.getHousingLink() >> 8 ) );
player.playScene( eventId, 0, 0, [this, eobj]( Entity::Player& player, const Event::SceneResult& result )
{
// param2 == 1 when player wants to enter house
if( result.param2 != 1 )
return;
auto terriMgr = getFramework()->get< Sapphire::World::Manager::TerritoryMgr >();
if( !terriMgr )
return;
auto zone = std::dynamic_pointer_cast< HousingZone >( player.getCurrentZone() );
if( !zone )
return;
Common::LandIdent ident;
ident.landId = eobj.getHousingLink() >> 8;
ident.territoryTypeId = zone->getTerritoryTypeId();
ident.wardNum = zone->getWardNum();
ident.worldId = 67;
auto internalZone = terriMgr->findOrCreateHousingInterior( ident );
if( internalZone )
{
player.sendDebug( "created zone with guid: " + std::to_string( internalZone->getGuId() ) + "\nname: " + internalZone->getName() );
}
player.eventFinish( result.eventId, 1 );
player.setPos( { 0.f, 0.f, 0.f } );
player.setInstance( internalZone );
} );
}
};<|endoftext|>
|
<commit_before>/*
Copyright 2012 Joe Hermaszewski. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY JOE HERMASZEWSKI "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL JOE HERMASZEWSKI OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are
those of the authors and should not be interpreted as representing official
policies, either expressed or implied, of Joe Hermaszewski.
*/
#include "variable.hpp"
#include <cassert>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <llvm/GlobalVariable.h>
#include <compiler/casting.hpp>
#include <compiler/code_generator.hpp>
#include <compiler/generic_value.hpp>
#include <compiler/tokens/expressions/expression.hpp>
namespace JoeLang
{
namespace Compiler
{
Variable::Variable( CompleteType type,
bool is_const,
bool is_global,
bool is_parameter,
GenericValue initializer,
std::string name )
:m_Type( std::move(type) )
,m_IsConst( is_const )
,m_IsGlobal( is_global )
,m_IsParameter( is_parameter )
,m_Initializer( std::move(initializer) )
,m_Name( std::move(name) )
{
// Assert that this has the correct initializer if this is const
// Or that if it has an initializer it's the correct type
assert( !m_Type.IsUnknown() &&
"Trying to construct a variable of unknown type" );
if( !m_IsParameter &&
( m_IsConst || !m_Initializer.GetType().IsUnknown() ) )
{
assert( !m_Initializer.GetType().IsUnknown() &&
"No initializer on a const variable" );
assert( m_Initializer.GetType() == m_Type &&
"Trying to initialize a variable with the wrong type" );
}
}
void Variable::CodeGen( CodeGenerator& code_gen )
{
// Don't generate storage for strings, they're determined at compile time
if( m_IsGlobal )
{
m_LLVMPointer = code_gen.CreateGlobalVariable( m_Type,
m_IsConst,
m_Initializer,
m_Name );
}
else
{
assert( false && "TODO: generate non global variables" );
}
}
llvm::Value* Variable::GetLLVMPointer() const
{
return m_LLVMPointer;
}
const CompleteType& Variable::GetType() const
{
return m_Type;
}
Type Variable::GetUnderlyingType() const
{
return m_Type.GetBaseType();
}
bool Variable::IsConst() const
{
return m_IsConst;
}
} // namespace Compiler
} // namespace JoeLang
<commit_msg>[+] merge<commit_after>/*
Copyright 2012 Joe Hermaszewski. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY JOE HERMASZEWSKI "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL JOE HERMASZEWSKI OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are
those of the authors and should not be interpreted as representing official
policies, either expressed or implied, of Joe Hermaszewski.
*/
#include "variable.hpp"
#include <cassert>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <llvm/GlobalVariable.h>
#include <compiler/casting.hpp>
#include <compiler/code_generator.hpp>
#include <compiler/generic_value.hpp>
#include <compiler/tokens/expressions/expression.hpp>
namespace JoeLang
{
namespace Compiler
{
Variable::Variable( CompleteType type,
bool is_const,
bool is_global,
bool is_parameter,
GenericValue initializer,
std::string name )
:m_Type( std::move(type) )
,m_IsConst( is_const )
,m_IsGlobal( is_global )
,m_IsParameter( is_parameter )
,m_Initializer( std::move(initializer) )
,m_Name( std::move(name) )
{
// Assert that this has the correct initializer if this is const
// Or that if it has an initializer it's the correct type
assert( !m_Type.IsUnknown() &&
"Trying to construct a variable of unknown type" );
assert( !(is_parameter && !m_Initializer.GetType().IsUnknown() ) &&
"Parameters can't have initializers" );
assert( ( !m_IsConst || m_IsParameter ||
!m_Initializer.GetType().IsUnknown() ) &&
"Const variables must have an initializer or be a parameter" );
assert( ( m_Initializer.GetType().IsUnknown() ||
m_Initializer.GetType() == type ) &&
"Trying to initialize a variable with the wrong type" );
}
void Variable::CodeGen( CodeGenerator& code_gen )
{
// Don't generate storage for strings, they're determined at compile time
if( m_IsGlobal )
{
m_LLVMPointer = code_gen.CreateGlobalVariable( m_Type,
m_IsConst,
m_Initializer,
m_Name );
}
else
{
assert( false && "TODO: generate non global variables" );
}
}
llvm::Value* Variable::GetLLVMPointer() const
{
return m_LLVMPointer;
}
const CompleteType& Variable::GetType() const
{
return m_Type;
}
Type Variable::GetUnderlyingType() const
{
return m_Type.GetBaseType();
}
bool Variable::IsConst() const
{
return m_IsConst;
}
} // namespace Compiler
} // namespace JoeLang
<|endoftext|>
|
<commit_before>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow_lite_support/metadata/cc/metadata_populator.h"
#include <cstdlib>
#include <cstring>
#include <functional>
#include "flatbuffers/flatbuffers.h" // from @flatbuffers
#include "contrib/minizip/ioapi.h"
#include "contrib/minizip/zip.h"
#include "tensorflow/lite/schema/schema_generated.h"
#include "tensorflow_lite_support/cc/common.h"
#include "tensorflow_lite_support/cc/port/status_macros.h"
#include "tensorflow_lite_support/cc/port/statusor.h"
#include "tensorflow_lite_support/metadata/cc/utils/zip_mem_file.h"
#include "tensorflow_lite_support/metadata/metadata_schema_generated.h"
namespace tflite {
namespace metadata {
namespace {
constexpr absl::string_view kMetadataBufferName = "TFLITE_METADATA";
using ::absl::StatusCode;
using ::tflite::support::CreateStatusWithPayload;
using ::tflite::support::TfLiteSupportStatus;
} // namespace
ModelMetadataPopulator::ModelMetadataPopulator(const tflite::Model& model) {
model.UnPackTo(&model_t_);
}
/* static */
tflite::support::StatusOr<std::unique_ptr<ModelMetadataPopulator>>
ModelMetadataPopulator::CreateFromModelBuffer(const char* buffer_data,
size_t buffer_size) {
// Rely on the simplest, base flatbuffers verifier. Here is not the place to
// e.g. use an OpResolver: we just want to make sure the buffer is valid to
// access the metadata.
flatbuffers::Verifier verifier = flatbuffers::Verifier(
reinterpret_cast<const uint8_t*>(buffer_data), buffer_size);
if (!tflite::VerifyModelBuffer(verifier)) {
return CreateStatusWithPayload(
StatusCode::kInvalidArgument,
"The model is not a valid FlatBuffer buffer.",
TfLiteSupportStatus::kInvalidFlatBufferError);
}
// Use absl::WrapUnique() to call private constructor:
// https://abseil.io/tips/126.
return absl::WrapUnique(
new ModelMetadataPopulator(*tflite::GetModel(buffer_data)));
}
void ModelMetadataPopulator::LoadMetadata(const char* metadata_buffer_data,
size_t metadata_buffer_size) {
// Pack the model metadata in a buffer.
auto model_metadata_buffer = std::make_unique<tflite::BufferT>();
model_metadata_buffer->data = {metadata_buffer_data,
metadata_buffer_data + metadata_buffer_size};
// Check if the model already has metadata. If so, just override the buffer
// and exit.
for (const auto& metadata_t : model_t_.metadata) {
if (metadata_t->name == kMetadataBufferName) {
model_t_.buffers[metadata_t->buffer] = std::move(model_metadata_buffer);
return;
}
}
// Model doesn't already have metadata: add metadata buffer and pointer to the
// buffer in the model metadata section.
model_t_.buffers.push_back(std::move(model_metadata_buffer));
auto metadata_t = std::make_unique<tflite::MetadataT>();
metadata_t->name = kMetadataBufferName;
metadata_t->buffer = model_t_.buffers.size() - 1;
model_t_.metadata.push_back(std::move(metadata_t));
}
void ModelMetadataPopulator::LoadAssociatedFiles(
const absl::flat_hash_map<std::string, std::string>& associated_files) {
associated_files_ = associated_files;
}
tflite::support::StatusOr<std::string>
ModelMetadataPopulator::AppendAssociatedFiles(const char* model_buffer_data,
size_t model_buffer_size) {
// Create in-memory zip file.
ZipMemFile mem_file = ZipMemFile(model_buffer_data, model_buffer_size);
// Open zip.
zipFile zf = zipOpen2(/*pathname=*/nullptr, APPEND_STATUS_CREATEAFTER,
/*globalcomment=*/nullptr, &mem_file.GetFileFuncDef());
if (zf == nullptr) {
return CreateStatusWithPayload(
StatusCode::kUnknown, "Unable to open zip archive",
TfLiteSupportStatus::kMetadataAssociatedFileZipError);
}
// Write associated files.
for (const auto& [name, contents] : associated_files_) {
if ((zipOpenNewFileInZip(zf, name.c_str(),
/*zipfi=*/nullptr,
/*extrafield_local=*/nullptr,
/*size_extrafield_local=*/0,
/*extrafield_global=*/nullptr,
/*size_extrafield_global=*/0,
/*comment=*/nullptr,
/*method=*/0,
/*level=*/Z_DEFAULT_COMPRESSION) != ZIP_OK) ||
(zipWriteInFileInZip(zf, contents.data(), contents.length()) !=
ZIP_OK) ||
(zipCloseFileInZip(zf) != ZIP_OK)) {
return CreateStatusWithPayload(
StatusCode::kUnknown, "Unable to write file to zip archive",
TfLiteSupportStatus::kMetadataAssociatedFileZipError);
}
}
// Close zip.
if (zipClose(zf, /*global_comment=*/nullptr) != ZIP_OK) {
return CreateStatusWithPayload(
StatusCode::kUnknown, "Unable to close zip archive",
TfLiteSupportStatus::kMetadataAssociatedFileZipError);
}
// Return as a string.
return std::string(mem_file.GetFileContent());
}
tflite::support::StatusOr<std::string> ModelMetadataPopulator::Populate() {
// Build model.
flatbuffers::FlatBufferBuilder model_fbb;
model_fbb.Finish(tflite::Model::Pack(model_fbb, &model_t_),
tflite::ModelIdentifier());
return AppendAssociatedFiles(
reinterpret_cast<char*>(model_fbb.GetBufferPointer()),
model_fbb.GetSize());
}
} // namespace metadata
} // namespace tflite
<commit_msg>Metadata Populator: use char[] instead of absl::string_view for metadata buffer name constant.<commit_after>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow_lite_support/metadata/cc/metadata_populator.h"
#include <cstdlib>
#include <cstring>
#include <functional>
#include "flatbuffers/flatbuffers.h" // from @flatbuffers
#include "contrib/minizip/ioapi.h"
#include "contrib/minizip/zip.h"
#include "tensorflow/lite/schema/schema_generated.h"
#include "tensorflow_lite_support/cc/common.h"
#include "tensorflow_lite_support/cc/port/status_macros.h"
#include "tensorflow_lite_support/cc/port/statusor.h"
#include "tensorflow_lite_support/metadata/cc/utils/zip_mem_file.h"
#include "tensorflow_lite_support/metadata/metadata_schema_generated.h"
namespace tflite {
namespace metadata {
namespace {
constexpr char kMetadataBufferName[] = "TFLITE_METADATA";
using ::absl::StatusCode;
using ::tflite::support::CreateStatusWithPayload;
using ::tflite::support::TfLiteSupportStatus;
} // namespace
ModelMetadataPopulator::ModelMetadataPopulator(const tflite::Model& model) {
model.UnPackTo(&model_t_);
}
/* static */
tflite::support::StatusOr<std::unique_ptr<ModelMetadataPopulator>>
ModelMetadataPopulator::CreateFromModelBuffer(const char* buffer_data,
size_t buffer_size) {
// Rely on the simplest, base flatbuffers verifier. Here is not the place to
// e.g. use an OpResolver: we just want to make sure the buffer is valid to
// access the metadata.
flatbuffers::Verifier verifier = flatbuffers::Verifier(
reinterpret_cast<const uint8_t*>(buffer_data), buffer_size);
if (!tflite::VerifyModelBuffer(verifier)) {
return CreateStatusWithPayload(
StatusCode::kInvalidArgument,
"The model is not a valid FlatBuffer buffer.",
TfLiteSupportStatus::kInvalidFlatBufferError);
}
// Use absl::WrapUnique() to call private constructor:
// https://abseil.io/tips/126.
return absl::WrapUnique(
new ModelMetadataPopulator(*tflite::GetModel(buffer_data)));
}
void ModelMetadataPopulator::LoadMetadata(const char* metadata_buffer_data,
size_t metadata_buffer_size) {
// Pack the model metadata in a buffer.
auto model_metadata_buffer = std::make_unique<tflite::BufferT>();
model_metadata_buffer->data = {metadata_buffer_data,
metadata_buffer_data + metadata_buffer_size};
// Check if the model already has metadata. If so, just override the buffer
// and exit.
for (const auto& metadata_t : model_t_.metadata) {
if (metadata_t->name == kMetadataBufferName) {
model_t_.buffers[metadata_t->buffer] = std::move(model_metadata_buffer);
return;
}
}
// Model doesn't already have metadata: add metadata buffer and pointer to the
// buffer in the model metadata section.
model_t_.buffers.push_back(std::move(model_metadata_buffer));
auto metadata_t = std::make_unique<tflite::MetadataT>();
metadata_t->name = kMetadataBufferName;
metadata_t->buffer = model_t_.buffers.size() - 1;
model_t_.metadata.push_back(std::move(metadata_t));
}
void ModelMetadataPopulator::LoadAssociatedFiles(
const absl::flat_hash_map<std::string, std::string>& associated_files) {
associated_files_ = associated_files;
}
tflite::support::StatusOr<std::string>
ModelMetadataPopulator::AppendAssociatedFiles(const char* model_buffer_data,
size_t model_buffer_size) {
// Create in-memory zip file.
ZipMemFile mem_file = ZipMemFile(model_buffer_data, model_buffer_size);
// Open zip.
zipFile zf = zipOpen2(/*pathname=*/nullptr, APPEND_STATUS_CREATEAFTER,
/*globalcomment=*/nullptr, &mem_file.GetFileFuncDef());
if (zf == nullptr) {
return CreateStatusWithPayload(
StatusCode::kUnknown, "Unable to open zip archive",
TfLiteSupportStatus::kMetadataAssociatedFileZipError);
}
// Write associated files.
for (const auto& [name, contents] : associated_files_) {
if ((zipOpenNewFileInZip(zf, name.c_str(),
/*zipfi=*/nullptr,
/*extrafield_local=*/nullptr,
/*size_extrafield_local=*/0,
/*extrafield_global=*/nullptr,
/*size_extrafield_global=*/0,
/*comment=*/nullptr,
/*method=*/0,
/*level=*/Z_DEFAULT_COMPRESSION) != ZIP_OK) ||
(zipWriteInFileInZip(zf, contents.data(), contents.length()) !=
ZIP_OK) ||
(zipCloseFileInZip(zf) != ZIP_OK)) {
return CreateStatusWithPayload(
StatusCode::kUnknown, "Unable to write file to zip archive",
TfLiteSupportStatus::kMetadataAssociatedFileZipError);
}
}
// Close zip.
if (zipClose(zf, /*global_comment=*/nullptr) != ZIP_OK) {
return CreateStatusWithPayload(
StatusCode::kUnknown, "Unable to close zip archive",
TfLiteSupportStatus::kMetadataAssociatedFileZipError);
}
// Return as a string.
return std::string(mem_file.GetFileContent());
}
tflite::support::StatusOr<std::string> ModelMetadataPopulator::Populate() {
// Build model.
flatbuffers::FlatBufferBuilder model_fbb;
model_fbb.Finish(tflite::Model::Pack(model_fbb, &model_t_),
tflite::ModelIdentifier());
return AppendAssociatedFiles(
reinterpret_cast<char*>(model_fbb.GetBufferPointer()),
model_fbb.GetSize());
}
} // namespace metadata
} // namespace tflite
<|endoftext|>
|
<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved.
#ifndef CONTAINERS_SCOPED_HPP_
#define CONTAINERS_SCOPED_HPP_
#include <string.h>
#include <utility>
#include "config/args.hpp"
#include "errors.hpp"
#include "utils.hpp"
// Like boost::scoped_ptr only with release, init, no bool conversion, no boost headers!
template <class T>
class scoped_ptr_t {
public:
template <class U>
friend class scoped_ptr_t;
scoped_ptr_t() : ptr_(NULL) { }
explicit scoped_ptr_t(T *p) : ptr_(p) { }
// (These noexcepts don't actually do anything w.r.t. STL containers, since the
// type's not copyable. There is no specific reason why these are many other
// functions need be marked noexcept with any degree of urgency.)
scoped_ptr_t(scoped_ptr_t &&movee) noexcept : ptr_(movee.ptr_) {
movee.ptr_ = NULL;
}
template <class U>
scoped_ptr_t(scoped_ptr_t<U> &&movee) noexcept : ptr_(movee.ptr_) {
movee.ptr_ = NULL;
}
~scoped_ptr_t() {
reset();
}
scoped_ptr_t &operator=(scoped_ptr_t &&movee) noexcept {
scoped_ptr_t tmp(std::move(movee));
swap(tmp);
return *this;
}
template <class U>
scoped_ptr_t &operator=(scoped_ptr_t<U> &&movee) noexcept {
scoped_ptr_t tmp(std::move(movee));
swap(tmp);
return *this;
}
// These 'init' functions are largely obsolete, because move semantics are a
// better thing to use.
template <class U>
void init(scoped_ptr_t<U> &&movee) {
rassert(ptr_ == NULL);
operator=(std::move(movee));
}
// includes a sanity-check for first-time use.
void init(T *value) {
rassert(ptr_ == NULL);
// This is like reset with an assert.
T *tmp = ptr_;
ptr_ = value;
delete tmp;
}
void reset() {
T *tmp = ptr_;
ptr_ = NULL;
delete tmp;
}
MUST_USE T *release() {
T *tmp = ptr_;
ptr_ = NULL;
return tmp;
}
void swap(scoped_ptr_t &other) noexcept {
T *tmp = ptr_;
ptr_ = other.ptr_;
other.ptr_ = tmp;
}
T &operator*() const {
rassert(ptr_);
return *ptr_;
}
T *get() const {
rassert(ptr_);
return ptr_;
}
T *get_or_null() const {
return ptr_;
}
T *operator->() const {
rassert(ptr_);
return ptr_;
}
bool has() const {
return ptr_ != NULL;
}
explicit operator bool() const {
return ptr_ != NULL;
}
private:
T *ptr_;
DISABLE_COPYING(scoped_ptr_t);
};
template <class T, class... Args>
scoped_ptr_t<T> make_scoped(Args&&... args) {
return scoped_ptr_t<T>(new T(std::forward<Args>(args)...));
}
// Not really like boost::scoped_array. A fascist array.
template <class T>
class scoped_array_t {
public:
scoped_array_t() : ptr_(NULL), size_(0) { }
explicit scoped_array_t(size_t n) : ptr_(NULL), size_(0) {
init(n);
}
scoped_array_t(T *ptr, size_t _size) : ptr_(NULL), size_(0) {
init(ptr, _size);
}
// (These noexcepts don't actually do anything w.r.t. STL containers, since the
// type's not copyable. There is no specific reason why these are many other
// functions need be marked noexcept with any degree of urgency.)
scoped_array_t(scoped_array_t &&movee) noexcept
: ptr_(movee.ptr_), size_(movee.size_) {
movee.ptr_ = NULL;
movee.size_ = 0;
}
~scoped_array_t() {
reset();
}
scoped_array_t &operator=(scoped_array_t &&movee) noexcept {
scoped_array_t tmp(std::move(movee));
swap(tmp);
return *this;
}
void init(size_t n) {
rassert(ptr_ == NULL);
ptr_ = new T[n];
size_ = n;
}
// The opposite of release.
void init(T *ptr, size_t _size) {
rassert(ptr != NULL);
rassert(ptr_ == NULL);
ptr_ = ptr;
size_ = _size;
}
void reset() {
T *tmp = ptr_;
ptr_ = NULL;
size_ = 0;
delete[] tmp;
}
MUST_USE T *release(size_t *size_out) {
*size_out = size_;
T *tmp = ptr_;
ptr_ = NULL;
size_ = 0;
return tmp;
}
void swap(scoped_array_t &other) noexcept {
T *tmp = ptr_;
size_t tmpsize = size_;
ptr_ = other.ptr_;
size_ = other.size_;
other.ptr_ = tmp;
other.size_ = tmpsize;
}
T &operator[](size_t i) const {
rassert(ptr_);
rassert(i < size_);
return ptr_[i];
}
T *data() const {
rassert(ptr_);
return ptr_;
}
size_t size() const {
rassert(ptr_);
return size_;
}
bool has() const {
return ptr_ != NULL;
}
private:
T *ptr_;
size_t size_;
DISABLE_COPYING(scoped_array_t);
};
// This class has move semantics in its copy constructor.
// It is meant to be used instead of C++14 generalized lambda capture,
// to capture a variable using move smeantics,
// which GCC 4.6 doesn't support.
template<class T>
class copyable_unique_t {
public:
copyable_unique_t(T&& x)
: it(std::move(x)) { }
copyable_unique_t(const copyable_unique_t<T> &other)
: it(std::move(other.it)) { }
T release() const {
T x(std::move(it));
return x;
}
private:
mutable T it;
};
#if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 7)
#define CAN_ALIAS_TEMPLATES 0
#else
#define CAN_ALIAS_TEMPLATES 1
#endif
/*
* For pointers with custom allocators and deallocators
*/
template <class T, void*(*alloc)(size_t), void(*dealloc)(void*)>
class scoped_alloc_t {
static_assert(std::is_pod<T>::value || std::is_same<T, void>::value,
"refusing to malloc non-POD, non-void type");
public:
template <class U, void*(*alloc_)(size_t), void(*dealloc_)(void*)>
friend class scoped_alloc_t;
scoped_alloc_t() : ptr_(NULL) { }
explicit scoped_alloc_t(size_t n) : ptr_(static_cast<T *>(alloc(n))) { }
scoped_alloc_t(const char *beg, const char *end) {
rassert(beg <= end);
size_t n = end - beg;
ptr_ = static_cast<T *>(alloc(n));
memcpy(ptr_, beg, n);
}
// (These noexcepts don't actually do anything w.r.t. STL containers, since the
// type's not copyable. There is no specific reason why these are many other
// functions need be marked noexcept with any degree of urgency.)
scoped_alloc_t(scoped_alloc_t &&movee) noexcept
: ptr_(movee.ptr_) {
movee.ptr_ = NULL;
}
template <class U>
scoped_alloc_t(scoped_alloc_t<U, alloc, dealloc> &&movee) noexcept
: ptr_(movee.ptr_) {
movee.ptr_ = NULL;
}
template <class U>
scoped_alloc_t(copyable_unique_t<U> other) noexcept {
scoped_alloc_t tmp(other.release());
swap(tmp);
}
void operator=(scoped_alloc_t &&movee) noexcept {
scoped_alloc_t tmp(std::move(movee));
swap(tmp);
}
T *get() const { return ptr_; }
T *operator->() const { return ptr_; }
bool has() const {
return ptr_ != NULL;
}
void reset() {
scoped_alloc_t tmp;
swap(tmp);
}
#if !CAN_ALIAS_TEMPLATES
protected:
#endif
~scoped_alloc_t() {
dealloc(ptr_);
}
private:
friend class released_t;
scoped_alloc_t(void*) = delete;
void swap(scoped_alloc_t &other) noexcept {
T *tmp = ptr_;
ptr_ = other.ptr_;
other.ptr_ = tmp;
}
T *ptr_;
DISABLE_COPYING(scoped_alloc_t);
};
template <int alignment>
void *raw_malloc_aligned(size_t size) {
return raw_malloc_aligned(size, alignment);
}
#if !CAN_ALIAS_TEMPLATES
// GCC 4.6 doesn't support template aliases
#define TEMPLATE_ALIAS(type_t, ...) \
struct type_t : public __VA_ARGS__ { \
template <class ... arg_ts> \
type_t(arg_ts&&... args) : \
__VA_ARGS__(std::forward<arg_ts>(args)...) { } \
}
#else
#define TEMPLATE_ALIAS(type_t, ...) using type_t = __VA_ARGS__;
#endif
// A type for pointers using rmalloc/free
template <class T>
TEMPLATE_ALIAS(scoped_malloc_t, scoped_alloc_t<T, rmalloc, free>);
// A type for aligned pointers
// Needed because, on Windows, raw_free_aligned doesn't call free
template <class T, int alignment>
TEMPLATE_ALIAS(scoped_aligned_ptr_t, scoped_alloc_t<T, raw_malloc_aligned<alignment>, raw_free_aligned>);
// A type for page-aligned pointers
template <class T>
TEMPLATE_ALIAS(scoped_page_aligned_ptr_t, scoped_alloc_t<T, raw_malloc_page_aligned, raw_free_aligned>);
// A type for device-block-aligned pointers
template <class T>
TEMPLATE_ALIAS(scoped_device_block_aligned_ptr_t, scoped_alloc_t<T, raw_malloc_aligned<DEVICE_BLOCK_SIZE>, raw_free_aligned>);
#endif // CONTAINERS_SCOPED_HPP_
<commit_msg>align: fix typo<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved.
#ifndef CONTAINERS_SCOPED_HPP_
#define CONTAINERS_SCOPED_HPP_
#include <string.h>
#include <utility>
#include "config/args.hpp"
#include "errors.hpp"
#include "utils.hpp"
// Like boost::scoped_ptr only with release, init, no bool conversion, no boost headers!
template <class T>
class scoped_ptr_t {
public:
template <class U>
friend class scoped_ptr_t;
scoped_ptr_t() : ptr_(NULL) { }
explicit scoped_ptr_t(T *p) : ptr_(p) { }
// (These noexcepts don't actually do anything w.r.t. STL containers, since the
// type's not copyable. There is no specific reason why these are many other
// functions need be marked noexcept with any degree of urgency.)
scoped_ptr_t(scoped_ptr_t &&movee) noexcept : ptr_(movee.ptr_) {
movee.ptr_ = NULL;
}
template <class U>
scoped_ptr_t(scoped_ptr_t<U> &&movee) noexcept : ptr_(movee.ptr_) {
movee.ptr_ = NULL;
}
~scoped_ptr_t() {
reset();
}
scoped_ptr_t &operator=(scoped_ptr_t &&movee) noexcept {
scoped_ptr_t tmp(std::move(movee));
swap(tmp);
return *this;
}
template <class U>
scoped_ptr_t &operator=(scoped_ptr_t<U> &&movee) noexcept {
scoped_ptr_t tmp(std::move(movee));
swap(tmp);
return *this;
}
// These 'init' functions are largely obsolete, because move semantics are a
// better thing to use.
template <class U>
void init(scoped_ptr_t<U> &&movee) {
rassert(ptr_ == NULL);
operator=(std::move(movee));
}
// includes a sanity-check for first-time use.
void init(T *value) {
rassert(ptr_ == NULL);
// This is like reset with an assert.
T *tmp = ptr_;
ptr_ = value;
delete tmp;
}
void reset() {
T *tmp = ptr_;
ptr_ = NULL;
delete tmp;
}
MUST_USE T *release() {
T *tmp = ptr_;
ptr_ = NULL;
return tmp;
}
void swap(scoped_ptr_t &other) noexcept {
T *tmp = ptr_;
ptr_ = other.ptr_;
other.ptr_ = tmp;
}
T &operator*() const {
rassert(ptr_);
return *ptr_;
}
T *get() const {
rassert(ptr_);
return ptr_;
}
T *get_or_null() const {
return ptr_;
}
T *operator->() const {
rassert(ptr_);
return ptr_;
}
bool has() const {
return ptr_ != NULL;
}
explicit operator bool() const {
return ptr_ != NULL;
}
private:
T *ptr_;
DISABLE_COPYING(scoped_ptr_t);
};
template <class T, class... Args>
scoped_ptr_t<T> make_scoped(Args&&... args) {
return scoped_ptr_t<T>(new T(std::forward<Args>(args)...));
}
// Not really like boost::scoped_array. A fascist array.
template <class T>
class scoped_array_t {
public:
scoped_array_t() : ptr_(NULL), size_(0) { }
explicit scoped_array_t(size_t n) : ptr_(NULL), size_(0) {
init(n);
}
scoped_array_t(T *ptr, size_t _size) : ptr_(NULL), size_(0) {
init(ptr, _size);
}
// (These noexcepts don't actually do anything w.r.t. STL containers, since the
// type's not copyable. There is no specific reason why these are many other
// functions need be marked noexcept with any degree of urgency.)
scoped_array_t(scoped_array_t &&movee) noexcept
: ptr_(movee.ptr_), size_(movee.size_) {
movee.ptr_ = NULL;
movee.size_ = 0;
}
~scoped_array_t() {
reset();
}
scoped_array_t &operator=(scoped_array_t &&movee) noexcept {
scoped_array_t tmp(std::move(movee));
swap(tmp);
return *this;
}
void init(size_t n) {
rassert(ptr_ == NULL);
ptr_ = new T[n];
size_ = n;
}
// The opposite of release.
void init(T *ptr, size_t _size) {
rassert(ptr != NULL);
rassert(ptr_ == NULL);
ptr_ = ptr;
size_ = _size;
}
void reset() {
T *tmp = ptr_;
ptr_ = NULL;
size_ = 0;
delete[] tmp;
}
MUST_USE T *release(size_t *size_out) {
*size_out = size_;
T *tmp = ptr_;
ptr_ = NULL;
size_ = 0;
return tmp;
}
void swap(scoped_array_t &other) noexcept {
T *tmp = ptr_;
size_t tmpsize = size_;
ptr_ = other.ptr_;
size_ = other.size_;
other.ptr_ = tmp;
other.size_ = tmpsize;
}
T &operator[](size_t i) const {
rassert(ptr_);
rassert(i < size_);
return ptr_[i];
}
T *data() const {
rassert(ptr_);
return ptr_;
}
size_t size() const {
rassert(ptr_);
return size_;
}
bool has() const {
return ptr_ != NULL;
}
private:
T *ptr_;
size_t size_;
DISABLE_COPYING(scoped_array_t);
};
// This class has move semantics in its copy constructor.
// It is meant to be used instead of C++14 generalized lambda capture,
// to capture a variable using move semantics,
// which GCC 4.6 doesn't support.
template<class T>
class copyable_unique_t {
public:
copyable_unique_t(T&& x)
: it(std::move(x)) { }
copyable_unique_t(const copyable_unique_t<T> &other)
: it(std::move(other.it)) { }
T release() const {
T x(std::move(it));
return x;
}
private:
mutable T it;
};
#if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 7)
#define CAN_ALIAS_TEMPLATES 0
#else
#define CAN_ALIAS_TEMPLATES 1
#endif
/*
* For pointers with custom allocators and deallocators
*/
template <class T, void*(*alloc)(size_t), void(*dealloc)(void*)>
class scoped_alloc_t {
static_assert(std::is_pod<T>::value || std::is_same<T, void>::value,
"refusing to malloc non-POD, non-void type");
public:
template <class U, void*(*alloc_)(size_t), void(*dealloc_)(void*)>
friend class scoped_alloc_t;
scoped_alloc_t() : ptr_(NULL) { }
explicit scoped_alloc_t(size_t n) : ptr_(static_cast<T *>(alloc(n))) { }
scoped_alloc_t(const char *beg, const char *end) {
rassert(beg <= end);
size_t n = end - beg;
ptr_ = static_cast<T *>(alloc(n));
memcpy(ptr_, beg, n);
}
// (These noexcepts don't actually do anything w.r.t. STL containers, since the
// type's not copyable. There is no specific reason why these are many other
// functions need be marked noexcept with any degree of urgency.)
scoped_alloc_t(scoped_alloc_t &&movee) noexcept
: ptr_(movee.ptr_) {
movee.ptr_ = NULL;
}
template <class U>
scoped_alloc_t(scoped_alloc_t<U, alloc, dealloc> &&movee) noexcept
: ptr_(movee.ptr_) {
movee.ptr_ = NULL;
}
template <class U>
scoped_alloc_t(copyable_unique_t<U> other) noexcept {
scoped_alloc_t tmp(other.release());
swap(tmp);
}
void operator=(scoped_alloc_t &&movee) noexcept {
scoped_alloc_t tmp(std::move(movee));
swap(tmp);
}
T *get() const { return ptr_; }
T *operator->() const { return ptr_; }
bool has() const {
return ptr_ != NULL;
}
void reset() {
scoped_alloc_t tmp;
swap(tmp);
}
#if !CAN_ALIAS_TEMPLATES
protected:
#endif
~scoped_alloc_t() {
dealloc(ptr_);
}
private:
friend class released_t;
scoped_alloc_t(void*) = delete;
void swap(scoped_alloc_t &other) noexcept {
T *tmp = ptr_;
ptr_ = other.ptr_;
other.ptr_ = tmp;
}
T *ptr_;
DISABLE_COPYING(scoped_alloc_t);
};
template <int alignment>
void *raw_malloc_aligned(size_t size) {
return raw_malloc_aligned(size, alignment);
}
#if !CAN_ALIAS_TEMPLATES
// GCC 4.6 doesn't support template aliases
#define TEMPLATE_ALIAS(type_t, ...) \
struct type_t : public __VA_ARGS__ { \
template <class ... arg_ts> \
type_t(arg_ts&&... args) : \
__VA_ARGS__(std::forward<arg_ts>(args)...) { } \
}
#else
#define TEMPLATE_ALIAS(type_t, ...) using type_t = __VA_ARGS__;
#endif
// A type for pointers using rmalloc/free
template <class T>
TEMPLATE_ALIAS(scoped_malloc_t, scoped_alloc_t<T, rmalloc, free>);
// A type for aligned pointers
// Needed because, on Windows, raw_free_aligned doesn't call free
template <class T, int alignment>
TEMPLATE_ALIAS(scoped_aligned_ptr_t, scoped_alloc_t<T, raw_malloc_aligned<alignment>, raw_free_aligned>);
// A type for page-aligned pointers
template <class T>
TEMPLATE_ALIAS(scoped_page_aligned_ptr_t, scoped_alloc_t<T, raw_malloc_page_aligned, raw_free_aligned>);
// A type for device-block-aligned pointers
template <class T>
TEMPLATE_ALIAS(scoped_device_block_aligned_ptr_t, scoped_alloc_t<T, raw_malloc_aligned<DEVICE_BLOCK_SIZE>, raw_free_aligned>);
#endif // CONTAINERS_SCOPED_HPP_
<|endoftext|>
|
<commit_before>#include "corrector.h"
#include "debug.h"
#include "manager.h"
#include "task.h"
Corrector::Corrector(Manager &manager)
: manager_(manager)
{
}
void Corrector::correct(const TaskPtr &task)
{
SOFT_ASSERT(task, return );
SOFT_ASSERT(task->isValid(), return );
if (!userSubstitutions_.empty())
task->recognized = substituteUser(task->recognized, task->sourceLanguage);
manager_.corrected(task);
}
void Corrector::updateSettings(const Settings &settings)
{
userSubstitutions_ = settings.userSubstitutions;
}
QString Corrector::substituteUser(const QString &source,
const LanguageId &language) const
{
auto result = source;
const auto range = userSubstitutions_.equal_range(language);
if (range.first == userSubstitutions_.cend())
return result;
while (true) {
auto bestMatch = range.first;
auto bestMatchLen = 0;
for (auto it = range.first; it != range.second; ++it) {
const auto &sub = it->second;
const auto len = sub.source.length();
if (len > bestMatchLen) {
bestMatchLen = len;
bestMatch = it;
}
}
if (bestMatchLen < 1)
break;
result.replace(bestMatch->second.source, bestMatch->second.target);
}
return result;
}
<commit_msg>Fix correction infinite loop<commit_after>#include "corrector.h"
#include "debug.h"
#include "manager.h"
#include "task.h"
Corrector::Corrector(Manager &manager)
: manager_(manager)
{
}
void Corrector::correct(const TaskPtr &task)
{
SOFT_ASSERT(task, return );
SOFT_ASSERT(task->isValid(), return );
if (!userSubstitutions_.empty())
task->recognized = substituteUser(task->recognized, task->sourceLanguage);
manager_.corrected(task);
}
void Corrector::updateSettings(const Settings &settings)
{
userSubstitutions_ = settings.userSubstitutions;
}
QString Corrector::substituteUser(const QString &source,
const LanguageId &language) const
{
auto result = source;
const auto range = userSubstitutions_.equal_range(language);
if (range.first == userSubstitutions_.cend())
return result;
while (true) {
auto bestMatch = range.first;
auto bestMatchLen = 0;
for (auto it = range.first; it != range.second; ++it) {
const auto &sub = it->second;
if (!result.contains(sub.source))
continue;
const auto len = sub.source.length();
if (len > bestMatchLen) {
bestMatchLen = len;
bestMatch = it;
}
}
if (bestMatchLen < 1)
break;
result.replace(bestMatch->second.source, bestMatch->second.target);
}
return result;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2013 The Chromium Embedded Framework 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 "libcef/browser/scheme_handler.h"
#include <string>
#include "libcef/browser/chrome_scheme_handler.h"
#include "libcef/browser/devtools_scheme_handler.h"
#include "libcef/common/scheme_registration.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/url_constants.h"
#include "net/url_request/data_protocol_handler.h"
#include "net/url_request/file_protocol_handler.h"
#include "net/url_request/ftp_protocol_handler.h"
#include "net/url_request/url_request_job_factory_impl.h"
namespace scheme {
void InstallInternalProtectedHandlers(
net::URLRequestJobFactoryImpl* job_factory,
content::ProtocolHandlerMap* protocol_handlers,
net::FtpTransactionFactory* ftp_transaction_factory) {
protocol_handlers->insert(
std::make_pair(chrome::kDataScheme, new net::DataProtocolHandler));
protocol_handlers->insert(
std::make_pair(chrome::kFileScheme, new net::FileProtocolHandler(
content::BrowserThread::GetBlockingPool()->
GetTaskRunnerWithShutdownBehavior(
base::SequencedWorkerPool::SKIP_ON_SHUTDOWN))));
#if !defined(DISABLE_FTP_SUPPORT)
protocol_handlers->insert(
std::make_pair(chrome::kFtpScheme,
new net::FtpProtocolHandler(ftp_transaction_factory)));
#endif
for (content::ProtocolHandlerMap::iterator it =
protocol_handlers->begin();
it != protocol_handlers->end();
++it) {
const std::string& scheme = it->first;
scoped_ptr<net::URLRequestJobFactory::ProtocolHandler> protocol_handler;
if (scheme == chrome::kChromeDevToolsScheme) {
// Don't use the default "chrome-devtools" handler.
continue;
} else if (scheme == chrome::kChromeUIScheme) {
// Filter the URLs that are passed to the default "chrome" handler so as
// not to interfere with CEF's "chrome" handler.
protocol_handler.reset(
scheme::WrapChromeProtocolHandler(
make_scoped_ptr(it->second.release())).release());
} else {
protocol_handler.reset(it->second.release());
}
// Make sure IsInternalProtectedScheme() stays synchronized with what
// Chromium is actually giving us.
DCHECK(IsInternalProtectedScheme(scheme));
bool set_protocol = job_factory->SetProtocolHandler(
scheme, protocol_handler.release());
DCHECK(set_protocol);
}
}
void RegisterInternalHandlers() {
scheme::RegisterChromeHandler();
scheme::RegisterChromeDevToolsHandler();
}
void DidFinishLoad(CefRefPtr<CefFrame> frame, const GURL& validated_url) {
if (validated_url.scheme() == chrome::kChromeUIScheme)
scheme::DidFinishChromeLoad(frame, validated_url);
}
} // namespace scheme
<commit_msg>Fix compile error (issue #1064).<commit_after>// Copyright (c) 2013 The Chromium Embedded Framework 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 "libcef/browser/scheme_handler.h"
#include <string>
#include "libcef/browser/chrome_scheme_handler.h"
#include "libcef/browser/devtools_scheme_handler.h"
#include "libcef/common/scheme_registration.h"
#include "base/threading/sequenced_worker_pool.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/url_constants.h"
#include "net/url_request/data_protocol_handler.h"
#include "net/url_request/file_protocol_handler.h"
#include "net/url_request/ftp_protocol_handler.h"
#include "net/url_request/url_request_job_factory_impl.h"
namespace scheme {
void InstallInternalProtectedHandlers(
net::URLRequestJobFactoryImpl* job_factory,
content::ProtocolHandlerMap* protocol_handlers,
net::FtpTransactionFactory* ftp_transaction_factory) {
protocol_handlers->insert(
std::make_pair(chrome::kDataScheme, new net::DataProtocolHandler));
protocol_handlers->insert(
std::make_pair(chrome::kFileScheme, new net::FileProtocolHandler(
content::BrowserThread::GetBlockingPool()->
GetTaskRunnerWithShutdownBehavior(
base::SequencedWorkerPool::SKIP_ON_SHUTDOWN))));
#if !defined(DISABLE_FTP_SUPPORT)
protocol_handlers->insert(
std::make_pair(chrome::kFtpScheme,
new net::FtpProtocolHandler(ftp_transaction_factory)));
#endif
for (content::ProtocolHandlerMap::iterator it =
protocol_handlers->begin();
it != protocol_handlers->end();
++it) {
const std::string& scheme = it->first;
scoped_ptr<net::URLRequestJobFactory::ProtocolHandler> protocol_handler;
if (scheme == chrome::kChromeDevToolsScheme) {
// Don't use the default "chrome-devtools" handler.
continue;
} else if (scheme == chrome::kChromeUIScheme) {
// Filter the URLs that are passed to the default "chrome" handler so as
// not to interfere with CEF's "chrome" handler.
protocol_handler.reset(
scheme::WrapChromeProtocolHandler(
make_scoped_ptr(it->second.release())).release());
} else {
protocol_handler.reset(it->second.release());
}
// Make sure IsInternalProtectedScheme() stays synchronized with what
// Chromium is actually giving us.
DCHECK(IsInternalProtectedScheme(scheme));
bool set_protocol = job_factory->SetProtocolHandler(
scheme, protocol_handler.release());
DCHECK(set_protocol);
}
}
void RegisterInternalHandlers() {
scheme::RegisterChromeHandler();
scheme::RegisterChromeDevToolsHandler();
}
void DidFinishLoad(CefRefPtr<CefFrame> frame, const GURL& validated_url) {
if (validated_url.scheme() == chrome::kChromeUIScheme)
scheme::DidFinishChromeLoad(frame, validated_url);
}
} // namespace scheme
<|endoftext|>
|
<commit_before>/*-------------------------------------------------------------------------
*
* FILE
* transaction_base.cxx
*
* DESCRIPTION
* common code and definitions for the transaction classes
* pqxx::transaction_base defines the interface for any abstract class that
* represents a database transaction
*
* Copyright (c) 2001-2004, Jeroen T. Vermeulen <jtv@xs4all.nl>
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this mistake,
* or contact the author.
*
*-------------------------------------------------------------------------
*/
#include "pqxx/compiler.h"
#include <stdexcept>
#include "pqxx/connection_base"
#include "pqxx/result"
#include "pqxx/tablestream"
#include "pqxx/transaction_base"
using namespace PGSTD;
using namespace pqxx::internal;
pqxx::transaction_base::transaction_base(connection_base &C,
const string &TName,
const string &CName) :
namedclass(TName, CName),
m_Conn(C),
m_UniqueCursorNum(1),
m_Focus(),
m_Status(st_nascent),
m_Registered(false),
m_PendingError()
{
m_Conn.RegisterTransaction(this);
m_Registered = true;
}
pqxx::transaction_base::~transaction_base()
{
try
{
if (!m_PendingError.empty())
process_notice("UNPROCESSED ERROR: " + m_PendingError + "\n");
if (m_Registered)
{
m_Conn.process_notice(description() + " was never closed properly!\n");
m_Conn.UnregisterTransaction(this);
}
}
catch (const exception &e)
{
try
{
process_notice(string(e.what()) + "\n");
}
catch (const exception &)
{
process_notice(e.what());
}
}
}
void pqxx::transaction_base::commit()
{
CheckPendingError();
// Check previous status code. Caller should only call this function if
// we're in "implicit" state, but multiple commits are silently accepted.
switch (m_Status)
{
case st_nascent: // Empty transaction. No skin off our nose.
return;
case st_active: // Just fine. This is what we expect.
break;
case st_aborted:
throw logic_error("Attempt to commit previously aborted " + description());
case st_committed:
// Transaction has been committed already. This is not exactly proper
// behaviour, but throwing an exception here would only give the impression
// that an abort is needed--which would only confuse things further at this
// stage.
// Therefore, multiple commits are accepted, though under protest.
m_Conn.process_notice(description() + " committed more than once\n");
return;
case st_in_doubt:
// Transaction may or may not have been committed. Report the problem but
// don't compound our troubles by throwing.
throw logic_error(description() +
"committed again while in an undetermined state\n");
default:
throw logic_error("libpqxx internal error: pqxx::transaction: invalid status code");
}
// Tricky one. If stream is nested in transaction but inside the same scope,
// the Commit() will come before the stream is closed. Which means the
// commit is premature. Punish this swiftly and without fail to discourage
// the habit from forming.
if (m_Focus.get())
throw runtime_error("Attempt to commit " + description() + " "
"with " + m_Focus.get()->description() + " "
"still open");
try
{
do_commit();
m_Status = st_committed;
}
catch (const in_doubt_error &)
{
m_Status = st_in_doubt;
throw;
}
catch (const exception &)
{
m_Status = st_aborted;
throw;
}
m_Conn.AddVariables(m_Vars);
End();
}
void pqxx::transaction_base::abort()
{
// Check previous status code. Quietly accept multiple aborts to
// simplify emergency bailout code.
switch (m_Status)
{
case st_nascent: // Never began transaction. No need to issue rollback.
break;
case st_active:
try { do_abort(); } catch (const exception &) { }
break;
case st_aborted:
return;
case st_committed:
throw logic_error("Attempt to abort previously committed " + description());
case st_in_doubt:
// Aborting an in-doubt transaction is probably a reasonably sane response
// to an insane situation. Log it, but do not complain.
m_Conn.process_notice("Warning: " + description() + " "
"aborted after going into indeterminate state; "
"it may have been executed anyway.\n");
return;
default:
throw logic_error("libpqxx internal error: invalid transaction status");
}
m_Status = st_aborted;
End();
}
pqxx::result pqxx::transaction_base::exec(const char Query[],
const string &Desc)
{
CheckPendingError();
const string N = (Desc.empty() ? "" : "'" + Desc + "' ");
if (m_Focus.get())
throw logic_error("Attempt to execute query " + N +
"on " + description() + " "
"with " + m_Focus.get()->description() + " "
"still open");
switch (m_Status)
{
case st_nascent:
// Make sure transaction has begun before executing anything
Begin();
break;
case st_active:
break;
case st_committed:
throw logic_error("Attempt to execute query " + N +
"in committed " + description());
case st_aborted:
throw logic_error("Attempt to execute query " + N +
"in aborted " + description());
case st_in_doubt:
throw logic_error("Attempt to execute query " + N + "in " +
description() + ", "
"which is in indeterminate state");
default:
throw logic_error("libpqxx internal error: pqxx::transaction: "
"invalid status code");
}
// TODO: Pass Desc to do_exec(), and from there on down
return do_exec(Query);
}
void pqxx::transaction_base::set_variable(const string &Var,
const string &Value)
{
// Before committing to this new value, see what the backend thinks about it
m_Conn.RawSetVar(Var, Value);
m_Vars[Var] = Value;
}
string pqxx::transaction_base::get_variable(const string &Var) const
{
const map<string,string>::const_iterator i = m_Vars.find(Var);
if (i != m_Vars.end()) return i->second;
return m_Conn.RawGetVar(Var);
}
void pqxx::transaction_base::Begin()
{
if (m_Status != st_nascent)
throw logic_error("libpqxx internal error: pqxx::transaction: "
"Begin() called while not in nascent state");
try
{
// Better handle any pending notifications before we begin
m_Conn.get_notifs();
do_begin();
m_Status = st_active;
}
catch (const exception &)
{
End();
throw;
}
}
void pqxx::transaction_base::End() throw ()
{
if (!m_Registered) return;
try
{
m_Conn.UnregisterTransaction(this);
m_Registered = false;
CheckPendingError();
if (m_Focus.get())
m_Conn.process_notice("Closing " + description() + " "
" with " + m_Focus.get()->description() + " "
"still open\n");
if (m_Status == st_active) abort();
}
catch (const exception &e)
{
try
{
m_Conn.process_notice(string(e.what()) + "\n");
}
catch (const exception &)
{
m_Conn.process_notice(e.what());
}
}
}
void pqxx::transaction_base::RegisterFocus(transactionfocus *S)
{
m_Focus.Register(S);
}
void pqxx::transaction_base::UnregisterFocus(transactionfocus *S) throw ()
{
try
{
m_Focus.Unregister(S);
}
catch (const exception &e)
{
m_Conn.process_notice(string(e.what()) + "\n");
}
}
pqxx::result pqxx::transaction_base::DirectExec(const char C[], int Retries)
{
CheckPendingError();
return m_Conn.Exec(C, Retries);
}
void pqxx::transaction_base::RegisterPendingError(const string &Err) throw ()
{
if (m_PendingError.empty() && !Err.empty())
{
try
{
m_PendingError = Err;
}
catch (const exception &e)
{
try
{
process_notice("UNABLE TO PROCESS ERROR\n");
process_notice(e.what());
process_notice("ERROR WAS:");
process_notice(Err);
}
catch (...)
{
}
}
}
}
void pqxx::transaction_base::CheckPendingError()
{
if (!m_PendingError.empty())
{
const string Err(m_PendingError);
#ifdef PQXX_HAVE_STRING_CLEAR
m_PendingError.clear();
#else
m_PendingError.resize(0);
#endif
throw runtime_error(m_PendingError);
}
}
namespace
{
string MakeCopyString(const string &Table, const string &Columns)
{
string Q = "COPY " + Table + " ";
if (!Columns.empty()) Q += "(" + Columns + ") ";
return Q;
}
} // namespace
void pqxx::transaction_base::BeginCopyRead(const string &Table,
const string &Columns)
{
exec(MakeCopyString(Table, Columns) + "TO STDOUT");
}
void pqxx::transaction_base::BeginCopyWrite(const string &Table,
const string &Columns)
{
exec(MakeCopyString(Table, Columns) + "FROM STDIN");
}
void pqxx::internal::transactionfocus::register_me()
{
m_Trans.RegisterFocus(this);
m_registered = true;
}
void pqxx::internal::transactionfocus::unregister_me() throw ()
{
m_Trans.UnregisterFocus(this);
m_registered = false;
}
void
pqxx::internal::transactionfocus::reg_pending_error(const string &err) throw ()
{
m_Trans.RegisterPendingError(err);
}
<commit_msg>Qualified RegisterFocus()/UnregisterFocus() args to help Doxygen<commit_after>/*-------------------------------------------------------------------------
*
* FILE
* transaction_base.cxx
*
* DESCRIPTION
* common code and definitions for the transaction classes
* pqxx::transaction_base defines the interface for any abstract class that
* represents a database transaction
*
* Copyright (c) 2001-2004, Jeroen T. Vermeulen <jtv@xs4all.nl>
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this mistake,
* or contact the author.
*
*-------------------------------------------------------------------------
*/
#include "pqxx/compiler.h"
#include <stdexcept>
#include "pqxx/connection_base"
#include "pqxx/result"
#include "pqxx/tablestream"
#include "pqxx/transaction_base"
using namespace PGSTD;
using namespace pqxx::internal;
pqxx::transaction_base::transaction_base(connection_base &C,
const string &TName,
const string &CName) :
namedclass(TName, CName),
m_Conn(C),
m_UniqueCursorNum(1),
m_Focus(),
m_Status(st_nascent),
m_Registered(false),
m_PendingError()
{
m_Conn.RegisterTransaction(this);
m_Registered = true;
}
pqxx::transaction_base::~transaction_base()
{
try
{
if (!m_PendingError.empty())
process_notice("UNPROCESSED ERROR: " + m_PendingError + "\n");
if (m_Registered)
{
m_Conn.process_notice(description() + " was never closed properly!\n");
m_Conn.UnregisterTransaction(this);
}
}
catch (const exception &e)
{
try
{
process_notice(string(e.what()) + "\n");
}
catch (const exception &)
{
process_notice(e.what());
}
}
}
void pqxx::transaction_base::commit()
{
CheckPendingError();
// Check previous status code. Caller should only call this function if
// we're in "implicit" state, but multiple commits are silently accepted.
switch (m_Status)
{
case st_nascent: // Empty transaction. No skin off our nose.
return;
case st_active: // Just fine. This is what we expect.
break;
case st_aborted:
throw logic_error("Attempt to commit previously aborted " + description());
case st_committed:
// Transaction has been committed already. This is not exactly proper
// behaviour, but throwing an exception here would only give the impression
// that an abort is needed--which would only confuse things further at this
// stage.
// Therefore, multiple commits are accepted, though under protest.
m_Conn.process_notice(description() + " committed more than once\n");
return;
case st_in_doubt:
// Transaction may or may not have been committed. Report the problem but
// don't compound our troubles by throwing.
throw logic_error(description() +
"committed again while in an undetermined state\n");
default:
throw logic_error("libpqxx internal error: pqxx::transaction: invalid status code");
}
// Tricky one. If stream is nested in transaction but inside the same scope,
// the Commit() will come before the stream is closed. Which means the
// commit is premature. Punish this swiftly and without fail to discourage
// the habit from forming.
if (m_Focus.get())
throw runtime_error("Attempt to commit " + description() + " "
"with " + m_Focus.get()->description() + " "
"still open");
try
{
do_commit();
m_Status = st_committed;
}
catch (const in_doubt_error &)
{
m_Status = st_in_doubt;
throw;
}
catch (const exception &)
{
m_Status = st_aborted;
throw;
}
m_Conn.AddVariables(m_Vars);
End();
}
void pqxx::transaction_base::abort()
{
// Check previous status code. Quietly accept multiple aborts to
// simplify emergency bailout code.
switch (m_Status)
{
case st_nascent: // Never began transaction. No need to issue rollback.
break;
case st_active:
try { do_abort(); } catch (const exception &) { }
break;
case st_aborted:
return;
case st_committed:
throw logic_error("Attempt to abort previously committed " + description());
case st_in_doubt:
// Aborting an in-doubt transaction is probably a reasonably sane response
// to an insane situation. Log it, but do not complain.
m_Conn.process_notice("Warning: " + description() + " "
"aborted after going into indeterminate state; "
"it may have been executed anyway.\n");
return;
default:
throw logic_error("libpqxx internal error: invalid transaction status");
}
m_Status = st_aborted;
End();
}
pqxx::result pqxx::transaction_base::exec(const char Query[],
const string &Desc)
{
CheckPendingError();
const string N = (Desc.empty() ? "" : "'" + Desc + "' ");
if (m_Focus.get())
throw logic_error("Attempt to execute query " + N +
"on " + description() + " "
"with " + m_Focus.get()->description() + " "
"still open");
switch (m_Status)
{
case st_nascent:
// Make sure transaction has begun before executing anything
Begin();
break;
case st_active:
break;
case st_committed:
throw logic_error("Attempt to execute query " + N +
"in committed " + description());
case st_aborted:
throw logic_error("Attempt to execute query " + N +
"in aborted " + description());
case st_in_doubt:
throw logic_error("Attempt to execute query " + N + "in " +
description() + ", "
"which is in indeterminate state");
default:
throw logic_error("libpqxx internal error: pqxx::transaction: "
"invalid status code");
}
// TODO: Pass Desc to do_exec(), and from there on down
return do_exec(Query);
}
void pqxx::transaction_base::set_variable(const string &Var,
const string &Value)
{
// Before committing to this new value, see what the backend thinks about it
m_Conn.RawSetVar(Var, Value);
m_Vars[Var] = Value;
}
string pqxx::transaction_base::get_variable(const string &Var) const
{
const map<string,string>::const_iterator i = m_Vars.find(Var);
if (i != m_Vars.end()) return i->second;
return m_Conn.RawGetVar(Var);
}
void pqxx::transaction_base::Begin()
{
if (m_Status != st_nascent)
throw logic_error("libpqxx internal error: pqxx::transaction: "
"Begin() called while not in nascent state");
try
{
// Better handle any pending notifications before we begin
m_Conn.get_notifs();
do_begin();
m_Status = st_active;
}
catch (const exception &)
{
End();
throw;
}
}
void pqxx::transaction_base::End() throw ()
{
if (!m_Registered) return;
try
{
m_Conn.UnregisterTransaction(this);
m_Registered = false;
CheckPendingError();
if (m_Focus.get())
m_Conn.process_notice("Closing " + description() + " "
" with " + m_Focus.get()->description() + " "
"still open\n");
if (m_Status == st_active) abort();
}
catch (const exception &e)
{
try
{
m_Conn.process_notice(string(e.what()) + "\n");
}
catch (const exception &)
{
m_Conn.process_notice(e.what());
}
}
}
void pqxx::transaction_base::RegisterFocus(internal::transactionfocus *S)
{
m_Focus.Register(S);
}
void pqxx::transaction_base::UnregisterFocus(internal::transactionfocus *S)
throw ()
{
try
{
m_Focus.Unregister(S);
}
catch (const exception &e)
{
m_Conn.process_notice(string(e.what()) + "\n");
}
}
pqxx::result pqxx::transaction_base::DirectExec(const char C[], int Retries)
{
CheckPendingError();
return m_Conn.Exec(C, Retries);
}
void pqxx::transaction_base::RegisterPendingError(const string &Err) throw ()
{
if (m_PendingError.empty() && !Err.empty())
{
try
{
m_PendingError = Err;
}
catch (const exception &e)
{
try
{
process_notice("UNABLE TO PROCESS ERROR\n");
process_notice(e.what());
process_notice("ERROR WAS:");
process_notice(Err);
}
catch (...)
{
}
}
}
}
void pqxx::transaction_base::CheckPendingError()
{
if (!m_PendingError.empty())
{
const string Err(m_PendingError);
#ifdef PQXX_HAVE_STRING_CLEAR
m_PendingError.clear();
#else
m_PendingError.resize(0);
#endif
throw runtime_error(m_PendingError);
}
}
namespace
{
string MakeCopyString(const string &Table, const string &Columns)
{
string Q = "COPY " + Table + " ";
if (!Columns.empty()) Q += "(" + Columns + ") ";
return Q;
}
} // namespace
void pqxx::transaction_base::BeginCopyRead(const string &Table,
const string &Columns)
{
exec(MakeCopyString(Table, Columns) + "TO STDOUT");
}
void pqxx::transaction_base::BeginCopyWrite(const string &Table,
const string &Columns)
{
exec(MakeCopyString(Table, Columns) + "FROM STDIN");
}
void pqxx::internal::transactionfocus::register_me()
{
m_Trans.RegisterFocus(this);
m_registered = true;
}
void pqxx::internal::transactionfocus::unregister_me() throw ()
{
m_Trans.UnregisterFocus(this);
m_registered = false;
}
void
pqxx::internal::transactionfocus::reg_pending_error(const string &err) throw ()
{
m_Trans.RegisterPendingError(err);
}
<|endoftext|>
|
<commit_before>/*
Copyright (C) 1998 by Jorrit Tyberghein and Dan Ogles.
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; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <stdio.h>
#include <stdarg.h>
#include "cssysdef.h"
#include "cssys/system.h"
#define WIN32_USECONSOLE
static bool console_ok = false;
// to be called before all printf() calls
void csSystemDriver::console_open ()
{
#ifdef WIN32_USECONSOLE
AllocConsole();
freopen("CONOUT$", "a", stderr); // Redirect stderr to console
freopen("CONOUT$", "a", stdout); // Redirect stdout to console
#endif
console_ok = true;
}
// to be called before shutdown
void csSystemDriver::console_close ()
{
console_ok = false;
#ifdef WIN32_USECONSOLE
FreeConsole();
#endif
}
// to be called instead of printf
void csSystemDriver::console_out (const char *str)
{
if (console_ok)
fputs (str, stdout);
}
<commit_msg>made compileable again. (where has open_console and close_console gone?)<commit_after>/*
Copyright (C) 1998 by Jorrit Tyberghein and Dan Ogles.
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; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <stdio.h>
#include <stdarg.h>
#include "cssysdef.h"
#include "cssys/system.h"
#define WIN32_USECONSOLE
static bool console_ok = false;
/*
//Thomas Hieber, 2000-07-12: It looks like console_open and
//console_close have been removed. I don't know why, or how
//to do things now. So I just uncommented the following.
// to be called before all printf() calls
void csSystemDriver::console_open ()
{
#ifdef WIN32_USECONSOLE
AllocConsole();
freopen("CONOUT$", "a", stderr); // Redirect stderr to console
freopen("CONOUT$", "a", stdout); // Redirect stdout to console
#endif
console_ok = true;
}
// to be called before shutdown
void csSystemDriver::console_close ()
{
console_ok = false;
#ifdef WIN32_USECONSOLE
FreeConsole();
#endif
}
*/
// to be called instead of printf
void csSystemDriver::console_out (const char *str)
{
//if (console_ok)
fputs (str, stdout);
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include "fixtures/events.hpp"
#include "vast/const_table_slice_handle.hpp"
#include "vast/default_table_slice.hpp"
#include "vast/format/bgpdump.hpp"
#include "vast/format/bro.hpp"
#include "vast/format/test.hpp"
#include "vast/table_slice_builder.hpp"
#include "vast/table_slice_handle.hpp"
#include "vast/type.hpp"
#include "vast/concept/printable/to_string.hpp"
#include "vast/concept/printable/vast/data.hpp"
#include "vast/concept/printable/vast/event.hpp"
namespace fixtures {
namespace {
timestamp epoch;
std::vector<event> make_ascending_integers(size_t count) {
std::vector<event> result;
type layout = type{record_type{{"value", integer_type{}}}}.name("test::int");
for (size_t i = 0; i < count; ++i) {
result.emplace_back(event::make(vector{static_cast<integer>(i)}, layout));
result.back().timestamp(epoch + std::chrono::seconds(i));
}
return result;
}
std::vector<event> make_alternating_integers(size_t count) {
std::vector<event> result;
type layout = type{record_type{{"value", integer_type{}}}}.name("test::int");
for (size_t i = 0; i < count; ++i) {
result.emplace_back(event::make(vector{static_cast<integer>(i % 2)},
layout));
result.back().timestamp(epoch + std::chrono::seconds(i));
}
return result;
}
/// insert item into a sorted vector
/// @precondition is_sorted(vec)
/// @postcondition is_sorted(vec)
template <typename T, typename Pred>
auto insert_sorted(std::vector<T>& vec, T const& item, Pred pred) {
return vec.insert(std::upper_bound(vec.begin(), vec.end(), item, pred), item);
}
} // namespace <anonymous>
size_t events::slice_size = 100;
std::vector<event> events::bro_conn_log;
std::vector<event> events::bro_dns_log;
std::vector<event> events::bro_http_log;
std::vector<event> events::bgpdump_txt;
std::vector<event> events::random;
std::vector<table_slice_handle> events::bro_conn_log_slices;
std::vector<table_slice_handle> events::bro_dns_log_slices;
std::vector<table_slice_handle> events::bro_http_log_slices;
std::vector<table_slice_handle> events::bgpdump_txt_slices;
// std::vector<table_slice_handle> events::random_slices;
std::vector<const_table_slice_handle> events::const_bro_conn_log_slices;
std::vector<const_table_slice_handle> events::const_bro_http_log_slices;
std::vector<const_table_slice_handle> events::const_bro_dns_log_slices;
std::vector<const_table_slice_handle> events::const_bgpdump_txt_slices;
// std::vector<const_table_slice_handle> events::const_random_slices;
std::vector<event> events::ascending_integers;
std::vector<table_slice_handle> events::ascending_integers_slices;
std::vector<const_table_slice_handle> events::const_ascending_integers_slices;
std::vector<event> events::alternating_integers;
std::vector<table_slice_handle> events::alternating_integers_slices;
std::vector<const_table_slice_handle> events::const_alternating_integers_slices;
record_type events::bro_conn_log_layout() {
return const_bro_conn_log_slices[0]->layout();
}
std::vector<table_slice_handle>
events::copy(std::vector<table_slice_handle> xs) {
std::vector<table_slice_handle> result;
result.reserve(xs.size());
for (auto& x : xs)
result.emplace_back(x->clone());
return result;
}
/// A wrapper around a table_slice_builder_ptr that assigns ids to each
/// added event.
class id_assigning_builder {
public:
explicit id_assigning_builder(table_slice_builder_ptr b) : inner_{b} {
// nop
}
/// Adds an event to the table slice and assigns an id.
bool add(event& e) {
if (!inner_->add(e.timestamp()))
FAIL("builder->add() failed");
if (!inner_->recursive_add(e.data(), e.type()))
FAIL("builder->recursive_add() failed");
e.id(id_++);
return true;
}
auto rows() const {
return inner_->rows();
}
bool start_slice(size_t offset) {
if (rows() != 0)
return false;
offset_ = offset;
id_ = offset;
return true;
}
/// Finish the slice and set its offset.
table_slice_handle finish() {
auto slice = inner_->finish();
slice->offset(offset_);
return slice;
}
private:
table_slice_builder_ptr inner_;
size_t offset_ = 0;
size_t id_ = 0;
};
/// Tries to access the builder for `layout`.
class builders {
public:
using Map = std::map<std::string, id_assigning_builder>;
id_assigning_builder* get(const type& layout) {
auto i = builders_.find(layout.name());
if (i != builders_.end())
return &i->second;
return caf::visit(
detail::overload(
[&](const record_type& rt) -> id_assigning_builder* {
// We always add a timestamp as first column to the layout.
auto internal = rt;
record_field tstamp_field{"timestamp", timestamp_type{}};
internal.fields.insert(internal.fields.begin(),
std::move(tstamp_field));
id_assigning_builder tmp{
default_table_slice::make_builder(std::move(internal))};
return &(
builders_.emplace(layout.name(), std::move(tmp)).first->second);
},
[&](const auto&) -> id_assigning_builder* {
FAIL("layout is not a record type");
return nullptr;
}),
layout);
}
Map& all() {
return builders_;
}
private:
Map builders_;
};
events::events() {
static bool initialized = false;
if (initialized)
return;
initialized = true;
MESSAGE("inhaling unit test suite events");
bro_conn_log = inhale<format::bro::reader>(bro::conn);
bro_dns_log = inhale<format::bro::reader>(bro::dns);
bro_http_log = inhale<format::bro::reader>(bro::http);
bgpdump_txt = inhale<format::bgpdump::reader>(bgpdump::updates20140821);
random = extract(vast::format::test::reader{42, 1000});
ascending_integers = make_ascending_integers(10000);
alternating_integers = make_alternating_integers(10000);
auto allocate_id_block = [i = id{0}](size_t size) mutable {
auto first = i;
i += size;
return first;
};
MESSAGE("building slices of " << slice_size << " events each");
auto assign_ids_and_slice_up = [&](std::vector<event>& src) {
VAST_ASSERT(src.size() > 0);
VAST_ASSERT(caf::holds_alternative<record_type>(src[0].type()));
std::vector<table_slice_handle> slices;
builders bs;
auto finish_slice = [&](auto& builder) {
insert_sorted(slices, builder.finish(),
[](const auto& lhs, const auto& rhs) {
return lhs->offset() < rhs->offset();
});
};
for (auto& e : src) {
auto bptr = bs.get(e.type());
if (bptr->rows() == 0)
bptr->start_slice(allocate_id_block(slice_size));
bptr->add(e);
if (bptr->rows() == slice_size)
finish_slice(*bptr);
}
for (auto& i : bs.all()) {
auto builder = i.second;
if (builder.rows() > 0)
finish_slice(builder);
}
return slices;
};
bro_conn_log_slices = assign_ids_and_slice_up(bro_conn_log);
bro_dns_log_slices = assign_ids_and_slice_up(bro_dns_log);
allocate_id_block(1000); // cause an artificial gap in the ID sequence
bro_http_log_slices = assign_ids_and_slice_up(bro_http_log);
bgpdump_txt_slices = assign_ids_and_slice_up(bgpdump_txt);
//random_slices = slice_up(random);
ascending_integers_slices = assign_ids_and_slice_up(ascending_integers);
alternating_integers_slices = assign_ids_and_slice_up(alternating_integers);
auto to_const_vector = [](const auto& xs) {
std::vector<const_table_slice_handle> result;
result.reserve(xs.size());
result.insert(result.end(), xs.begin(), xs.end());
return result;
};
const_bro_conn_log_slices = to_const_vector(bro_conn_log_slices);
const_bro_dns_log_slices = to_const_vector(bro_dns_log_slices);
const_bro_http_log_slices = to_const_vector(bro_http_log_slices);
const_bgpdump_txt_slices = to_const_vector(bgpdump_txt_slices);
// const_random_slices = to_const_vector(random_slices);
const_ascending_integers_slices = to_const_vector(ascending_integers_slices);
const_alternating_integers_slices
= to_const_vector(alternating_integers_slices);
auto sort_by_id = [](std::vector<event>& v) {
std::sort(
v.begin(), v.end(),
[](const auto& lhs, const auto& rhs) { return lhs.id() < rhs.id(); });
};
auto to_events = [&](const auto& slices) {
std::vector<event> result;
for (auto& slice : slices) {
auto xs = slice->rows_to_events();
std::move(xs.begin(), xs.end(), std::back_inserter(result));
}
return result;
};
#define SANITY_CHECK(event_vec, slice_vec) \
{ \
auto flat_log = to_events(slice_vec); \
auto sorted_event_vec = event_vec; \
sort_by_id(sorted_event_vec); \
REQUIRE_EQUAL(sorted_event_vec.size(), flat_log.size()); \
for (size_t i = 0; i < sorted_event_vec.size(); ++i) { \
if (flatten(sorted_event_vec[i]) != flat_log[i]) { \
FAIL(#event_vec << " != " << #slice_vec << "\ni: " << i << '\n' \
<< to_string(sorted_event_vec[i]) \
<< " != " << to_string(flat_log[i])); \
} \
} \
}
SANITY_CHECK(bro_conn_log, const_bro_conn_log_slices);
SANITY_CHECK(bro_dns_log, const_bro_dns_log_slices);
SANITY_CHECK(bro_http_log, const_bro_http_log_slices);
SANITY_CHECK(bgpdump_txt, const_bgpdump_txt_slices);
//SANITY_CHECK(random, const_random_slices);
}
} // namespace fixtures
<commit_msg>Fix coding style<commit_after>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include "fixtures/events.hpp"
#include "vast/const_table_slice_handle.hpp"
#include "vast/default_table_slice.hpp"
#include "vast/format/bgpdump.hpp"
#include "vast/format/bro.hpp"
#include "vast/format/test.hpp"
#include "vast/table_slice_builder.hpp"
#include "vast/table_slice_handle.hpp"
#include "vast/type.hpp"
#include "vast/concept/printable/to_string.hpp"
#include "vast/concept/printable/vast/data.hpp"
#include "vast/concept/printable/vast/event.hpp"
namespace fixtures {
namespace {
timestamp epoch;
std::vector<event> make_ascending_integers(size_t count) {
std::vector<event> result;
type layout = type{record_type{{"value", integer_type{}}}}.name("test::int");
for (size_t i = 0; i < count; ++i) {
result.emplace_back(event::make(vector{static_cast<integer>(i)}, layout));
result.back().timestamp(epoch + std::chrono::seconds(i));
}
return result;
}
std::vector<event> make_alternating_integers(size_t count) {
std::vector<event> result;
type layout = type{record_type{{"value", integer_type{}}}}.name("test::int");
for (size_t i = 0; i < count; ++i) {
result.emplace_back(event::make(vector{static_cast<integer>(i % 2)},
layout));
result.back().timestamp(epoch + std::chrono::seconds(i));
}
return result;
}
/// insert item into a sorted vector
/// @precondition is_sorted(vec)
/// @postcondition is_sorted(vec)
template <typename T, typename Pred>
auto insert_sorted(std::vector<T>& vec, const T& item, Pred pred) {
return vec.insert(std::upper_bound(vec.begin(), vec.end(), item, pred), item);
}
} // namespace <anonymous>
size_t events::slice_size = 100;
std::vector<event> events::bro_conn_log;
std::vector<event> events::bro_dns_log;
std::vector<event> events::bro_http_log;
std::vector<event> events::bgpdump_txt;
std::vector<event> events::random;
std::vector<table_slice_handle> events::bro_conn_log_slices;
std::vector<table_slice_handle> events::bro_dns_log_slices;
std::vector<table_slice_handle> events::bro_http_log_slices;
std::vector<table_slice_handle> events::bgpdump_txt_slices;
// std::vector<table_slice_handle> events::random_slices;
std::vector<const_table_slice_handle> events::const_bro_conn_log_slices;
std::vector<const_table_slice_handle> events::const_bro_http_log_slices;
std::vector<const_table_slice_handle> events::const_bro_dns_log_slices;
std::vector<const_table_slice_handle> events::const_bgpdump_txt_slices;
// std::vector<const_table_slice_handle> events::const_random_slices;
std::vector<event> events::ascending_integers;
std::vector<table_slice_handle> events::ascending_integers_slices;
std::vector<const_table_slice_handle> events::const_ascending_integers_slices;
std::vector<event> events::alternating_integers;
std::vector<table_slice_handle> events::alternating_integers_slices;
std::vector<const_table_slice_handle> events::const_alternating_integers_slices;
record_type events::bro_conn_log_layout() {
return const_bro_conn_log_slices[0]->layout();
}
std::vector<table_slice_handle>
events::copy(std::vector<table_slice_handle> xs) {
std::vector<table_slice_handle> result;
result.reserve(xs.size());
for (auto& x : xs)
result.emplace_back(x->clone());
return result;
}
/// A wrapper around a table_slice_builder_ptr that assigns ids to each
/// added event.
class id_assigning_builder {
public:
explicit id_assigning_builder(table_slice_builder_ptr b) : inner_{b} {
// nop
}
/// Adds an event to the table slice and assigns an id.
bool add(event& e) {
if (!inner_->add(e.timestamp()))
FAIL("builder->add() failed");
if (!inner_->recursive_add(e.data(), e.type()))
FAIL("builder->recursive_add() failed");
e.id(id_++);
return true;
}
auto rows() const {
return inner_->rows();
}
bool start_slice(size_t offset) {
if (rows() != 0)
return false;
offset_ = offset;
id_ = offset;
return true;
}
/// Finish the slice and set its offset.
table_slice_handle finish() {
auto slice = inner_->finish();
slice->offset(offset_);
return slice;
}
private:
table_slice_builder_ptr inner_;
size_t offset_ = 0;
size_t id_ = 0;
};
/// Tries to access the builder for `layout`.
class builders {
public:
using map_type = std::map<std::string, id_assigning_builder>;
id_assigning_builder* get(const type& layout) {
auto i = builders_.find(layout.name());
if (i != builders_.end())
return &i->second;
return caf::visit(
detail::overload(
[&](const record_type& rt) -> id_assigning_builder* {
// We always add a timestamp as first column to the layout.
auto internal = rt;
record_field tstamp_field{"timestamp", timestamp_type{}};
internal.fields.insert(internal.fields.begin(),
std::move(tstamp_field));
id_assigning_builder tmp{
default_table_slice::make_builder(std::move(internal))};
return &(
builders_.emplace(layout.name(), std::move(tmp)).first->second);
},
[&](const auto&) -> id_assigning_builder* {
FAIL("layout is not a record type");
return nullptr;
}),
layout);
}
map_type& all() {
return builders_;
}
private:
map_type builders_;
};
events::events() {
static bool initialized = false;
if (initialized)
return;
initialized = true;
MESSAGE("inhaling unit test suite events");
bro_conn_log = inhale<format::bro::reader>(bro::conn);
bro_dns_log = inhale<format::bro::reader>(bro::dns);
bro_http_log = inhale<format::bro::reader>(bro::http);
bgpdump_txt = inhale<format::bgpdump::reader>(bgpdump::updates20140821);
random = extract(vast::format::test::reader{42, 1000});
ascending_integers = make_ascending_integers(10000);
alternating_integers = make_alternating_integers(10000);
auto allocate_id_block = [i = id{0}](size_t size) mutable {
auto first = i;
i += size;
return first;
};
MESSAGE("building slices of " << slice_size << " events each");
auto assign_ids_and_slice_up = [&](std::vector<event>& src) {
VAST_ASSERT(src.size() > 0);
VAST_ASSERT(caf::holds_alternative<record_type>(src[0].type()));
std::vector<table_slice_handle> slices;
builders bs;
auto finish_slice = [&](auto& builder) {
insert_sorted(slices, builder.finish(),
[](const auto& lhs, const auto& rhs) {
return lhs->offset() < rhs->offset();
});
};
for (auto& e : src) {
auto bptr = bs.get(e.type());
if (bptr->rows() == 0)
bptr->start_slice(allocate_id_block(slice_size));
bptr->add(e);
if (bptr->rows() == slice_size)
finish_slice(*bptr);
}
for (auto& i : bs.all()) {
auto builder = i.second;
if (builder.rows() > 0)
finish_slice(builder);
}
return slices;
};
bro_conn_log_slices = assign_ids_and_slice_up(bro_conn_log);
bro_dns_log_slices = assign_ids_and_slice_up(bro_dns_log);
allocate_id_block(1000); // cause an artificial gap in the ID sequence
bro_http_log_slices = assign_ids_and_slice_up(bro_http_log);
bgpdump_txt_slices = assign_ids_and_slice_up(bgpdump_txt);
//random_slices = slice_up(random);
ascending_integers_slices = assign_ids_and_slice_up(ascending_integers);
alternating_integers_slices = assign_ids_and_slice_up(alternating_integers);
auto to_const_vector = [](const auto& xs) {
std::vector<const_table_slice_handle> result;
result.reserve(xs.size());
result.insert(result.end(), xs.begin(), xs.end());
return result;
};
const_bro_conn_log_slices = to_const_vector(bro_conn_log_slices);
const_bro_dns_log_slices = to_const_vector(bro_dns_log_slices);
const_bro_http_log_slices = to_const_vector(bro_http_log_slices);
const_bgpdump_txt_slices = to_const_vector(bgpdump_txt_slices);
// const_random_slices = to_const_vector(random_slices);
const_ascending_integers_slices = to_const_vector(ascending_integers_slices);
const_alternating_integers_slices
= to_const_vector(alternating_integers_slices);
auto sort_by_id = [](std::vector<event>& v) {
std::sort(
v.begin(), v.end(),
[](const auto& lhs, const auto& rhs) { return lhs.id() < rhs.id(); });
};
auto to_events = [&](const auto& slices) {
std::vector<event> result;
for (auto& slice : slices) {
auto xs = slice->rows_to_events();
std::move(xs.begin(), xs.end(), std::back_inserter(result));
}
return result;
};
#define SANITY_CHECK(event_vec, slice_vec) \
{ \
auto flat_log = to_events(slice_vec); \
auto sorted_event_vec = event_vec; \
sort_by_id(sorted_event_vec); \
REQUIRE_EQUAL(sorted_event_vec.size(), flat_log.size()); \
for (size_t i = 0; i < sorted_event_vec.size(); ++i) { \
if (flatten(sorted_event_vec[i]) != flat_log[i]) { \
FAIL(#event_vec << " != " << #slice_vec << "\ni: " << i << '\n' \
<< to_string(sorted_event_vec[i]) \
<< " != " << to_string(flat_log[i])); \
} \
} \
}
SANITY_CHECK(bro_conn_log, const_bro_conn_log_slices);
SANITY_CHECK(bro_dns_log, const_bro_dns_log_slices);
SANITY_CHECK(bro_http_log, const_bro_http_log_slices);
SANITY_CHECK(bgpdump_txt, const_bgpdump_txt_slices);
//SANITY_CHECK(random, const_random_slices);
}
} // namespace fixtures
<|endoftext|>
|
<commit_before>/*
* Copyright 2013 Matthew Harvey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "gui/decimal_text_ctrl.hpp"
#include "finformat.hpp"
#include "dcm_exceptions.hpp"
#include "gui/decimal_validator.hpp"
#include "gui/locale.hpp"
#include "gui/text_ctrl.hpp"
#include <jewel/assert.hpp>
#include <jewel/log.hpp>
#include <jewel/decimal.hpp>
#include <wx/event.h>
#include <wx/gdicmn.h>
#include <wx/window.h>
#include <iostream>
using jewel::Decimal;
using std::endl;
namespace dcm
{
namespace gui
{
BEGIN_EVENT_TABLE(DecimalTextCtrl, TextCtrl)
EVT_KILL_FOCUS(DecimalTextCtrl::on_kill_focus)
EVT_SET_FOCUS(DecimalTextCtrl::on_set_focus)
END_EVENT_TABLE()
DecimalTextCtrl::DecimalTextCtrl
( wxWindow* p_parent,
unsigned int p_id,
wxSize const& p_size,
Decimal::places_type p_precision,
bool p_print_dash_for_zero // TODO LOW PRIORITY Would be cleaner with a FlagSet here.
):
TextCtrl
( p_parent,
p_id,
finformat_wx
( Decimal(0, p_precision),
locale(),
( p_print_dash_for_zero?
DecimalFormatFlags():
DecimalFormatFlags().clear(string_flags::dash_for_zero)
)
),
wxDefaultPosition,
p_size,
wxALIGN_RIGHT,
DecimalValidator
( Decimal(0, p_precision),
p_precision,
p_print_dash_for_zero
)
),
m_print_dash_for_zero(p_print_dash_for_zero),
m_precision(p_precision)
{
}
DecimalTextCtrl::~DecimalTextCtrl()
{
}
void
DecimalTextCtrl::set_amount(Decimal const& p_amount)
{
Decimal::places_type const prec = p_amount.places();
if (prec != m_precision)
{
DecimalValidator* const validator =
dynamic_cast<DecimalValidator*>(GetValidator());
JEWEL_ASSERT (validator);
m_precision = prec;
validator->set_precision(prec);
}
JEWEL_ASSERT (p_amount.places() == m_precision);
DecimalFormatFlags flags;
if (!m_print_dash_for_zero) flags.clear(string_flags::dash_for_zero);
SetValue(finformat_wx(p_amount, locale(), flags));
// TODO LOW PRIORITY This really sucks. We are validating the entire
// parent window as a side-effect of setting the value of just one
// of its children. But if we call Validate() on DecimalTextCtrl directly
// it doesn't have any effect (for some reason).
GetParent()->Validate();
return;
}
Decimal
DecimalTextCtrl::amount()
{
DecimalValidator const* const validator =
dynamic_cast<DecimalValidator const*>(GetValidator());
JEWEL_ASSERT (validator);
return validator->decimal();
}
void
DecimalTextCtrl::on_kill_focus(wxFocusEvent& event)
{
// NOTE BudgetPanel and MultiAccountPanel rely on the call
// to GetParent()->TransferDataToWindow().
//
// TODO LOW PRIORITY BudgetPanel and MultiAccountPanel rely on the call to
// GetParent()->TransferDataToWindow() here. This coupling seems ugly
// and fragile. Improve this.
event.Skip();
auto const orig = amount();
auto* const validator = GetValidator();
auto* const parent = GetParent();
JEWEL_ASSERT (parent);
JEWEL_ASSERT (validator);
if
( !validator->Validate(static_cast<wxWindow*>(this)) ||
!parent->TransferDataToWindow()
)
{
set_amount(orig);
}
return;
}
void
DecimalTextCtrl::on_set_focus(wxFocusEvent& event)
{
event.Skip();
SelectAll();
return;
}
} // namespace gui
} // namespace dcm
<commit_msg>Fixed bug (present on Fedora, but not Windows) with DecimalTextCtrl.<commit_after>/*
* Copyright 2013 Matthew Harvey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "gui/decimal_text_ctrl.hpp"
#include "finformat.hpp"
#include "dcm_exceptions.hpp"
#include "gui/budget_panel.hpp"
#include "gui/decimal_validator.hpp"
#include "gui/locale.hpp"
#include "gui/multi_account_panel.hpp"
#include "gui/text_ctrl.hpp"
#include <jewel/assert.hpp>
#include <jewel/log.hpp>
#include <jewel/decimal.hpp>
#include <wx/event.h>
#include <wx/gdicmn.h>
#include <wx/window.h>
#include <iostream>
using jewel::Decimal;
using std::endl;
namespace dcm
{
namespace gui
{
BEGIN_EVENT_TABLE(DecimalTextCtrl, TextCtrl)
EVT_KILL_FOCUS(DecimalTextCtrl::on_kill_focus)
EVT_SET_FOCUS(DecimalTextCtrl::on_set_focus)
END_EVENT_TABLE()
DecimalTextCtrl::DecimalTextCtrl
( wxWindow* p_parent,
unsigned int p_id,
wxSize const& p_size,
Decimal::places_type p_precision,
bool p_print_dash_for_zero // TODO LOW PRIORITY Would be cleaner with a FlagSet here.
):
TextCtrl
( p_parent,
p_id,
finformat_wx
( Decimal(0, p_precision),
locale(),
( p_print_dash_for_zero?
DecimalFormatFlags():
DecimalFormatFlags().clear(string_flags::dash_for_zero)
)
),
wxDefaultPosition,
p_size,
wxALIGN_RIGHT,
DecimalValidator
( Decimal(0, p_precision),
p_precision,
p_print_dash_for_zero
)
),
m_print_dash_for_zero(p_print_dash_for_zero),
m_precision(p_precision)
{
}
DecimalTextCtrl::~DecimalTextCtrl()
{
}
void
DecimalTextCtrl::set_amount(Decimal const& p_amount)
{
Decimal::places_type const prec = p_amount.places();
if (prec != m_precision)
{
DecimalValidator* const validator =
dynamic_cast<DecimalValidator*>(GetValidator());
JEWEL_ASSERT (validator);
m_precision = prec;
validator->set_precision(prec);
}
JEWEL_ASSERT (p_amount.places() == m_precision);
DecimalFormatFlags flags;
if (!m_print_dash_for_zero) flags.clear(string_flags::dash_for_zero);
SetValue(finformat_wx(p_amount, locale(), flags));
// TODO LOW PRIORITY This really sucks. We are validating the entire
// parent window as a side-effect of setting the value of just one
// of its children. But if we call Validate() on DecimalTextCtrl directly
// it doesn't have any effect (for some reason).
GetParent()->Validate();
return;
}
Decimal
DecimalTextCtrl::amount()
{
DecimalValidator const* const validator =
dynamic_cast<DecimalValidator const*>(GetValidator());
JEWEL_ASSERT (validator);
return validator->decimal();
}
void
DecimalTextCtrl::on_kill_focus(wxFocusEvent& event)
{
// TODO LOW PRIORITY BudgetPanel and MultiAccountPanel rely on the call to
// GetParent()->TransferDataToWindow() here. This coupling is ugly
// and fragile. Improve this.
event.Skip();
auto const orig = amount();
auto* const validator = GetValidator();
auto* const parent = GetParent();
JEWEL_ASSERT (parent);
JEWEL_ASSERT (validator);
bool ok = validator->Validate(static_cast<wxWindow*>(this));
if (ok)
{
if
( dynamic_cast<gui::BudgetPanel*>(parent) ||
dynamic_cast<gui::MultiAccountPanel*>(parent)
)
{
ok = parent->TransferDataToWindow();
}
else
{
ok = validator->TransferToWindow();
}
}
if (!ok) set_amount(orig);
return;
}
void
DecimalTextCtrl::on_set_focus(wxFocusEvent& event)
{
event.Skip();
SelectAll();
return;
}
} // namespace gui
} // namespace dcm
<|endoftext|>
|
<commit_before>#include <efsw/WatcherWin32.hpp>
#include <efsw/String.hpp>
#if EFSW_PLATFORM == EFSW_PLATFORM_WIN32
namespace efsw
{
/// Unpacks events and passes them to a user defined callback.
void CALLBACK WatchCallback(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped)
{
char szFile[MAX_PATH];
PFILE_NOTIFY_INFORMATION pNotify;
WatcherStructWin32 * tWatch = (WatcherStructWin32*) lpOverlapped;
WatcherWin32 * pWatch = tWatch->Watch;
size_t offset = 0;
if (dwNumberOfBytesTransfered == 0)
{
RefreshWatch(tWatch); // If dwNumberOfBytesTransfered == 0, it means the buffer overflowed (too many changes between GetOverlappedResults calls). Those events are lost, but at least we can refresh so subsequent changes are seen again.
return;
}
if (dwErrorCode == ERROR_SUCCESS)
{
do
{
bool skip = false;
pNotify = (PFILE_NOTIFY_INFORMATION) &pWatch->mBuffer[offset];
offset += pNotify->NextEntryOffset;
int count = WideCharToMultiByte(CP_UTF8, 0, pNotify->FileName,
pNotify->FileNameLength / sizeof(WCHAR),
szFile, MAX_PATH - 1, NULL, NULL);
szFile[count] = TEXT('\0');
std::string nfile( szFile );
if ( FILE_ACTION_MODIFIED == pNotify->Action )
{
FileInfo fifile( std::string( pWatch->DirName ) + nfile );
if ( pWatch->LastModifiedEvent.file.ModificationTime == fifile.ModificationTime && pWatch->LastModifiedEvent.fileName == nfile )
{
skip = true;
}
pWatch->LastModifiedEvent.fileName = nfile;
pWatch->LastModifiedEvent.file = fifile;
}
if ( !skip )
{
pWatch->Watch->handleAction(pWatch, nfile, pNotify->Action);
}
} while (pNotify->NextEntryOffset != 0);
}
if (!pWatch->StopNow)
{
RefreshWatch(tWatch);
}
}
/// Refreshes the directory monitoring.
bool RefreshWatch(WatcherStructWin32* pWatch)
{
return ReadDirectoryChangesW(
pWatch->Watch->DirHandle,
pWatch->Watch->mBuffer,
sizeof(pWatch->Watch->mBuffer),
pWatch->Watch->Recursive,
pWatch->Watch->NotifyFilter,
NULL,
&pWatch->Overlapped,
NULL
) != 0;
}
/// Stops monitoring a directory.
void DestroyWatch(WatcherStructWin32* pWatch)
{
if (pWatch)
{
WatcherWin32 * tWatch = pWatch->Watch;
tWatch->StopNow = true;
CancelIo(tWatch->DirHandle);
RefreshWatch(pWatch);
if (!HasOverlappedIoCompleted(&pWatch->Overlapped))
{
SleepEx(5, TRUE);
}
CloseHandle(pWatch->Overlapped.hEvent);
CloseHandle(pWatch->Watch->DirHandle);
efSAFE_DELETE_ARRAY( pWatch->Watch->DirName );
efSAFE_DELETE( pWatch->Watch );
HeapFree(GetProcessHeap(), 0, pWatch);
}
}
/// Starts monitoring a directory.
WatcherStructWin32* CreateWatch(LPCWSTR szDirectory, bool recursive, DWORD NotifyFilter)
{
WatcherStructWin32 * tWatch;
size_t ptrsize = sizeof(*tWatch);
tWatch = static_cast<WatcherStructWin32*>(HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, ptrsize));
WatcherWin32 * pWatch = new WatcherWin32();
tWatch->Watch = pWatch;
pWatch->DirHandle = CreateFileW(
szDirectory,
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
NULL
);
if (pWatch->DirHandle != INVALID_HANDLE_VALUE)
{
tWatch->Overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
pWatch->NotifyFilter = NotifyFilter;
pWatch->Recursive = recursive;
if (RefreshWatch(tWatch))
{
return tWatch;
}
else
{
CloseHandle(tWatch->Overlapped.hEvent);
CloseHandle(pWatch->DirHandle);
}
}
HeapFree(GetProcessHeap(), 0, tWatch);
return NULL;
}
}
#endif
<commit_msg>minor fix to avoid incorrect filtering of duplicated events on windows<commit_after>#include <efsw/WatcherWin32.hpp>
#include <efsw/String.hpp>
#if EFSW_PLATFORM == EFSW_PLATFORM_WIN32
namespace efsw
{
/// Unpacks events and passes them to a user defined callback.
void CALLBACK WatchCallback(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, LPOVERLAPPED lpOverlapped)
{
char szFile[MAX_PATH];
PFILE_NOTIFY_INFORMATION pNotify;
WatcherStructWin32 * tWatch = (WatcherStructWin32*) lpOverlapped;
WatcherWin32 * pWatch = tWatch->Watch;
size_t offset = 0;
if (dwNumberOfBytesTransfered == 0)
{
RefreshWatch(tWatch); // If dwNumberOfBytesTransfered == 0, it means the buffer overflowed (too many changes between GetOverlappedResults calls). Those events are lost, but at least we can refresh so subsequent changes are seen again.
return;
}
if (dwErrorCode == ERROR_SUCCESS)
{
do
{
bool skip = false;
pNotify = (PFILE_NOTIFY_INFORMATION) &pWatch->mBuffer[offset];
offset += pNotify->NextEntryOffset;
int count = WideCharToMultiByte(CP_UTF8, 0, pNotify->FileName,
pNotify->FileNameLength / sizeof(WCHAR),
szFile, MAX_PATH - 1, NULL, NULL);
szFile[count] = TEXT('\0');
std::string nfile( szFile );
if ( FILE_ACTION_MODIFIED == pNotify->Action )
{
FileInfo fifile( std::string( pWatch->DirName ) + nfile );
if ( pWatch->LastModifiedEvent.file.ModificationTime == fifile.ModificationTime && pWatch->LastModifiedEvent.file.Size == fifile.Size && pWatch->LastModifiedEvent.fileName == nfile )
{
skip = true;
}
pWatch->LastModifiedEvent.fileName = nfile;
pWatch->LastModifiedEvent.file = fifile;
}
if ( !skip )
{
pWatch->Watch->handleAction(pWatch, nfile, pNotify->Action);
}
} while (pNotify->NextEntryOffset != 0);
}
if (!pWatch->StopNow)
{
RefreshWatch(tWatch);
}
}
/// Refreshes the directory monitoring.
bool RefreshWatch(WatcherStructWin32* pWatch)
{
return ReadDirectoryChangesW(
pWatch->Watch->DirHandle,
pWatch->Watch->mBuffer,
sizeof(pWatch->Watch->mBuffer),
pWatch->Watch->Recursive,
pWatch->Watch->NotifyFilter,
NULL,
&pWatch->Overlapped,
NULL
) != 0;
}
/// Stops monitoring a directory.
void DestroyWatch(WatcherStructWin32* pWatch)
{
if (pWatch)
{
WatcherWin32 * tWatch = pWatch->Watch;
tWatch->StopNow = true;
CancelIo(tWatch->DirHandle);
RefreshWatch(pWatch);
if (!HasOverlappedIoCompleted(&pWatch->Overlapped))
{
SleepEx(5, TRUE);
}
CloseHandle(pWatch->Overlapped.hEvent);
CloseHandle(pWatch->Watch->DirHandle);
efSAFE_DELETE_ARRAY( pWatch->Watch->DirName );
efSAFE_DELETE( pWatch->Watch );
HeapFree(GetProcessHeap(), 0, pWatch);
}
}
/// Starts monitoring a directory.
WatcherStructWin32* CreateWatch(LPCWSTR szDirectory, bool recursive, DWORD NotifyFilter)
{
WatcherStructWin32 * tWatch;
size_t ptrsize = sizeof(*tWatch);
tWatch = static_cast<WatcherStructWin32*>(HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, ptrsize));
WatcherWin32 * pWatch = new WatcherWin32();
tWatch->Watch = pWatch;
pWatch->DirHandle = CreateFileW(
szDirectory,
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
NULL
);
if (pWatch->DirHandle != INVALID_HANDLE_VALUE)
{
tWatch->Overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
pWatch->NotifyFilter = NotifyFilter;
pWatch->Recursive = recursive;
if (RefreshWatch(tWatch))
{
return tWatch;
}
else
{
CloseHandle(tWatch->Overlapped.hEvent);
CloseHandle(pWatch->DirHandle);
}
}
HeapFree(GetProcessHeap(), 0, tWatch);
return NULL;
}
}
#endif
<|endoftext|>
|
<commit_before>// Copyright (c) 2019 The Syscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <uint256.h>
#include <arith_uint256.h>
#include <ethereum/ethereum.h>
#include <ethereum/sha3.h>
#include <logging.h>
#include <util/strencodings.h>
int nibblesToTraverse(const std::string &encodedPartialPath, const std::string &path, int pathPtr) {
std::string partialPath;
char pathPtrInt[2] = {encodedPartialPath[0], '\0'};
int partialPathInt = strtol(pathPtrInt, NULL, 10);
if(partialPathInt == 0 || partialPathInt == 2){
partialPath = encodedPartialPath.substr(2);
}else{
partialPath = encodedPartialPath.substr(1);
}
if(partialPath == path.substr(pathPtr, partialPath.size())){
return partialPath.size();
}else{
return -1;
}
}
bool VerifyProof(dev::bytesConstRef path, const dev::RLP& value, const dev::RLP& parentNodes, const dev::RLP& root) {
try{
dev::RLP currentNode;
const int len = parentNodes.itemCount();
dev::RLP nodeKey = root;
int pathPtr = 0;
const std::string pathString = dev::toHex(path);
int nibbles;
char pathPtrInt[2];
for (int i = 0 ; i < len ; i++) {
currentNode = parentNodes[i];
if(!nodeKey.payload().contentsEqual(sha3(currentNode.data()).ref().toVector())){
return false;
}
if(pathPtr > (int)pathString.size()){
return false;
}
switch(currentNode.itemCount()){
case 17://branch node
if(pathPtr == (int)pathString.size()){
if(currentNode[16].payload().contentsEqual(value.data().toVector())){
return true;
}else{
return false;
}
}
pathPtrInt[0] = pathString[pathPtr];
pathPtrInt[1] = '\0';
nodeKey = currentNode[strtol(pathPtrInt, NULL, 16)]; //must == sha3(rlp.encode(currentNode[path[pathptr]]))
pathPtr += 1;
break;
case 2:
nibbles = nibblesToTraverse(toHex(currentNode[0].payload()), pathString, pathPtr);
if(nibbles <= -1)
return false;
pathPtr += nibbles;
if(pathPtr == (int)pathString.size()) { //leaf node
if(currentNode[1].payload().contentsEqual(value.data().toVector())){
return true;
} else {
return false;
}
} else {//extension node
nodeKey = currentNode[1];
}
break;
default:
return false;
}
}
}
catch(...){
return false;
}
return false;
}
/**
* Parse eth input string expected to contain smart contract method call data. If the method call is not what we
* expected, or the length of the expected string is not what we expect then return false.
*
* @param vchInputExpectedMethodHash The expected method hash
* @param nERC20Precision The erc20 precision to know how to convert ethereum's uint256 to a uint64 with truncation of insignifficant bits
* @param nLocalPrecision The local precision to know how to convert ethereum's uint256 to a uint64 with truncation of insignifficant bits
* @param vchInputData The input to parse
* @param outputAmount The amount burned
* @param nAsset The asset burned
* @param witnessAddress The destination witness address for the minting
* @return true if everything is valid
*/
bool parseEthMethodInputData(const std::vector<unsigned char>& vchInputExpectedMethodHash, const uint8_t &nERC20Precision, const uint8_t& nLocalPrecision, const std::vector<unsigned char>& vchInputData, uint64_t& outputAmount, uint32_t& nAsset, CTxDestination& witnessAddress) {
// total 5 or 6 fields are expected @ 32 bytes each field, 6 fields if witness > 32 bytes + 4 byte method hash
if(vchInputData.size() < 164 || vchInputData.size() > 196) {
return false;
}
// method hash is 4 bytes
std::vector<unsigned char>::const_iterator firstMethod = vchInputData.begin();
std::vector<unsigned char>::const_iterator lastMethod = firstMethod + 4;
const std::vector<unsigned char> vchMethodHash(firstMethod,lastMethod);
// if the method hash doesn't match the expected method hash then return false
if(vchMethodHash != vchInputExpectedMethodHash) {
return false;
}
std::vector<unsigned char> vchAmount(lastMethod,lastMethod + 32);
// reverse endian
std::reverse(vchAmount.begin(), vchAmount.end());
arith_uint256 outputAmountArith = UintToArith256(uint256(vchAmount));
// local precision can range between 0 and 8 decimal places, so it should fit within a CAmount
// we pad zero's if erc20's precision is less than ours so we can accurately get the whole value of the amount transferred
if(nLocalPrecision > nERC20Precision){
outputAmountArith *= pow(10, nLocalPrecision-nERC20Precision);
// ensure we truncate decimals to fit within int64 if erc20's precision is more than our asset precision
} else if(nLocalPrecision < nERC20Precision){
outputAmountArith /= pow(10, nERC20Precision-nLocalPrecision);
}
outputAmount = outputAmountArith.GetLow64();
// convert the vch into a uint32_t (nAsset)
// should be in position 68 walking backwards
nAsset = static_cast<uint32_t>(vchInputData[67]);
nAsset |= static_cast<uint32_t>(vchInputData[66]) << 8;
nAsset |= static_cast<uint32_t>(vchInputData[65]) << 16;
nAsset |= static_cast<uint32_t>(vchInputData[64]) << 24;
// skip data field marker (32 bytes) + 31 bytes offset to the varint _byte
const unsigned char &dataLength = vchInputData[131];
// bech32 addresses to 45 bytes, min length is 9 for min witness address https://en.bitcoin.it/wiki/BIP_0173
if(dataLength > 45 || dataLength < 9) {
return false;
}
// witness address information starting at position 132 till the end
std::vector<unsigned char>::const_iterator firstWitness = vchInputData.begin()+132;
std::vector<unsigned char>::const_iterator lastWitness = firstWitness + dataLength;
//witnessAddress = CWitnessAddress(nVersion, std::vector<unsigned char>(firstWitness,lastWitness));
//return witnessAddress.IsValid();
return true;
}<commit_msg>save witness address<commit_after>// Copyright (c) 2019 The Syscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <uint256.h>
#include <arith_uint256.h>
#include <ethereum/ethereum.h>
#include <ethereum/sha3.h>
#include <logging.h>
#include <util/strencodings.h>
int nibblesToTraverse(const std::string &encodedPartialPath, const std::string &path, int pathPtr) {
std::string partialPath;
char pathPtrInt[2] = {encodedPartialPath[0], '\0'};
int partialPathInt = strtol(pathPtrInt, NULL, 10);
if(partialPathInt == 0 || partialPathInt == 2){
partialPath = encodedPartialPath.substr(2);
}else{
partialPath = encodedPartialPath.substr(1);
}
if(partialPath == path.substr(pathPtr, partialPath.size())){
return partialPath.size();
}else{
return -1;
}
}
bool VerifyProof(dev::bytesConstRef path, const dev::RLP& value, const dev::RLP& parentNodes, const dev::RLP& root) {
try{
dev::RLP currentNode;
const int len = parentNodes.itemCount();
dev::RLP nodeKey = root;
int pathPtr = 0;
const std::string pathString = dev::toHex(path);
int nibbles;
char pathPtrInt[2];
for (int i = 0 ; i < len ; i++) {
currentNode = parentNodes[i];
if(!nodeKey.payload().contentsEqual(sha3(currentNode.data()).ref().toVector())){
return false;
}
if(pathPtr > (int)pathString.size()){
return false;
}
switch(currentNode.itemCount()){
case 17://branch node
if(pathPtr == (int)pathString.size()){
if(currentNode[16].payload().contentsEqual(value.data().toVector())){
return true;
}else{
return false;
}
}
pathPtrInt[0] = pathString[pathPtr];
pathPtrInt[1] = '\0';
nodeKey = currentNode[strtol(pathPtrInt, NULL, 16)]; //must == sha3(rlp.encode(currentNode[path[pathptr]]))
pathPtr += 1;
break;
case 2:
nibbles = nibblesToTraverse(toHex(currentNode[0].payload()), pathString, pathPtr);
if(nibbles <= -1)
return false;
pathPtr += nibbles;
if(pathPtr == (int)pathString.size()) { //leaf node
if(currentNode[1].payload().contentsEqual(value.data().toVector())){
return true;
} else {
return false;
}
} else {//extension node
nodeKey = currentNode[1];
}
break;
default:
return false;
}
}
}
catch(...){
return false;
}
return false;
}
/**
* Parse eth input string expected to contain smart contract method call data. If the method call is not what we
* expected, or the length of the expected string is not what we expect then return false.
*
* @param vchInputExpectedMethodHash The expected method hash
* @param nERC20Precision The erc20 precision to know how to convert ethereum's uint256 to a uint64 with truncation of insignifficant bits
* @param nLocalPrecision The local precision to know how to convert ethereum's uint256 to a uint64 with truncation of insignifficant bits
* @param vchInputData The input to parse
* @param outputAmount The amount burned
* @param nAsset The asset burned
* @param witnessAddress The destination witness address for the minting
* @return true if everything is valid
*/
bool parseEthMethodInputData(const std::vector<unsigned char>& vchInputExpectedMethodHash, const uint8_t &nERC20Precision, const uint8_t& nLocalPrecision, const std::vector<unsigned char>& vchInputData, uint64_t& outputAmount, uint32_t& nAsset, CTxDestination& witnessAddress) {
// total 5 or 6 fields are expected @ 32 bytes each field, 6 fields if witness > 32 bytes + 4 byte method hash
if(vchInputData.size() < 164 || vchInputData.size() > 196) {
return false;
}
// method hash is 4 bytes
std::vector<unsigned char>::const_iterator firstMethod = vchInputData.begin();
std::vector<unsigned char>::const_iterator lastMethod = firstMethod + 4;
const std::vector<unsigned char> vchMethodHash(firstMethod,lastMethod);
// if the method hash doesn't match the expected method hash then return false
if(vchMethodHash != vchInputExpectedMethodHash) {
return false;
}
std::vector<unsigned char> vchAmount(lastMethod,lastMethod + 32);
// reverse endian
std::reverse(vchAmount.begin(), vchAmount.end());
arith_uint256 outputAmountArith = UintToArith256(uint256(vchAmount));
// local precision can range between 0 and 8 decimal places, so it should fit within a CAmount
// we pad zero's if erc20's precision is less than ours so we can accurately get the whole value of the amount transferred
if(nLocalPrecision > nERC20Precision){
outputAmountArith *= pow(10, nLocalPrecision-nERC20Precision);
// ensure we truncate decimals to fit within int64 if erc20's precision is more than our asset precision
} else if(nLocalPrecision < nERC20Precision){
outputAmountArith /= pow(10, nERC20Precision-nLocalPrecision);
}
outputAmount = outputAmountArith.GetLow64();
// convert the vch into a uint32_t (nAsset)
// should be in position 68 walking backwards
nAsset = static_cast<uint32_t>(vchInputData[67]);
nAsset |= static_cast<uint32_t>(vchInputData[66]) << 8;
nAsset |= static_cast<uint32_t>(vchInputData[65]) << 16;
nAsset |= static_cast<uint32_t>(vchInputData[64]) << 24;
// skip data field marker (32 bytes) + 31 bytes offset to the varint _byte
const unsigned char &dataLength = vchInputData[131];
// bech32 addresses to 45 bytes, min length is 9 for min witness address https://en.bitcoin.it/wiki/BIP_0173
if(dataLength > 45 || dataLength < 9) {
return false;
}
// witness address information starting at position 132 till the end
witnessAddress = DecodeDestination(std::to_string(vchInputData.begin()+132, firstWitness + dataLength));
return true;
}<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2009 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#include <mapnik/expression_string.hpp>
#include <boost/variant.hpp>
#include <unicode/uversion.h>
namespace mapnik
{
struct expression_string : boost::static_visitor<void>
{
explicit expression_string(std::string & str)
: str_(str) {}
void operator() (value_type const& x) const
{
str_ += x.to_expression_string() ;
}
void operator() (attribute const& attr) const
{
str_ += "[";
str_ += attr.name();
str_ += "]";
}
template <typename Tag>
void operator() (binary_node<Tag> const& x) const
{
if (x.type() != tags::mult::str() && x.type() != tags::div::str())
{
str_ += "(";
}
boost::apply_visitor(expression_string(str_),x.left);
str_ += x.type();
boost::apply_visitor(expression_string(str_),x.right);
if (x.type() != tags::mult::str() && x.type() != tags::div::str())
{
str_ += ")";
}
}
template <typename Tag>
void operator() (unary_node<Tag> const& x) const
{
str_ += Tag::str();
str_ += "(";
boost::apply_visitor(expression_string(str_),x.expr);
str_ += ")";
}
void operator() (regex_match_node const & x) const
{
// TODO - replace with pre ICU 4.2 compatible fromUTF32()
#if (U_ICU_VERSION_MAJOR_NUM >= 4) && (U_ICU_VERSION_MINOR_NUM >=2)
boost::apply_visitor(expression_string(str_),x.expr);
str_ +=".match(";
std::string utf8;
UnicodeString ustr = UnicodeString::fromUTF32( &x.pattern.str()[0] ,x.pattern.str().length());
to_utf8(ustr,utf8);
str_ += utf8;
str_ +=")";
#endif
}
void operator() (regex_replace_node const & x) const
{
// TODO - replace with pre ICU 4.2 compatible fromUTF32()
#if (U_ICU_VERSION_MAJOR_NUM >= 4) && (U_ICU_VERSION_MINOR_NUM >=2)
boost::apply_visitor(expression_string(str_),x.expr);
str_ +=".replace(";
std::string utf8;
UnicodeString ustr = UnicodeString::fromUTF32( &x.pattern.str()[0] ,x.pattern.str().length());
to_utf8(ustr,utf8);
str_ += "'";
str_ += utf8;
str_ +="','";
to_utf8(x.format ,utf8);
str_ += utf8;
str_ +="')";
#endif
}
private:
mutable std::string & str_;
};
std::string to_expression_string(expr_node const& node)
{
std::string str;
expression_string functor(str);
boost::apply_visitor(functor,node);
return str;
}
}
<commit_msg>fix formatting<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2009 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#include <mapnik/expression_string.hpp>
#include <boost/variant.hpp>
#include <unicode/uversion.h>
namespace mapnik
{
struct expression_string : boost::static_visitor<void>
{
explicit expression_string(std::string & str)
: str_(str) {}
void operator() (value_type const& x) const
{
str_ += x.to_expression_string() ;
}
void operator() (attribute const& attr) const
{
str_ += "[";
str_ += attr.name();
str_ += "]";
}
template <typename Tag>
void operator() (binary_node<Tag> const& x) const
{
if (x.type() != tags::mult::str() && x.type() != tags::div::str())
{
str_ += "(";
}
boost::apply_visitor(expression_string(str_),x.left);
str_ += x.type();
boost::apply_visitor(expression_string(str_),x.right);
if (x.type() != tags::mult::str() && x.type() != tags::div::str())
{
str_ += ")";
}
}
template <typename Tag>
void operator() (unary_node<Tag> const& x) const
{
str_ += Tag::str();
str_ += "(";
boost::apply_visitor(expression_string(str_),x.expr);
str_ += ")";
}
void operator() (regex_match_node const & x) const
{
// TODO - replace with pre ICU 4.2 compatible fromUTF32()
#if (U_ICU_VERSION_MAJOR_NUM >= 4) && (U_ICU_VERSION_MINOR_NUM >=2)
boost::apply_visitor(expression_string(str_),x.expr);
str_ +=".match(";
std::string utf8;
UnicodeString ustr = UnicodeString::fromUTF32( &x.pattern.str()[0] ,x.pattern.str().length());
to_utf8(ustr,utf8);
str_ += utf8;
str_ +=")";
#endif
}
void operator() (regex_replace_node const & x) const
{
// TODO - replace with pre ICU 4.2 compatible fromUTF32()
#if (U_ICU_VERSION_MAJOR_NUM >= 4) && (U_ICU_VERSION_MINOR_NUM >=2)
boost::apply_visitor(expression_string(str_),x.expr);
str_ +=".replace(";
std::string utf8;
UnicodeString ustr = UnicodeString::fromUTF32( &x.pattern.str()[0] ,x.pattern.str().length());
to_utf8(ustr,utf8);
str_ += "'";
str_ += utf8;
str_ +="','";
to_utf8(x.format ,utf8);
str_ += utf8;
str_ +="')";
#endif
}
private:
mutable std::string & str_;
};
std::string to_expression_string(expr_node const& node)
{
std::string str;
expression_string functor(str);
boost::apply_visitor(functor,node);
return str;
}
}
<|endoftext|>
|
<commit_before>/*
* SinglePlayer.cpp
* OpenLieroX
*
* Created by Albert Zeyer on 15.01.10.
* code under LGPL
*
*/
#include "SinglePlayer.h"
#include "Options.h"
#include "ConfigHandler.h"
#include "game/Mod.h"
#include "game/Level.h"
#include "GfxPrimitives.h"
#include "DeprecatedGUI/Menu.h"
#include "CClient.h"
#include "CServer.h"
#include "ProfileSystem.h"
#include "CWormHuman.h"
#include "OLXCommand.h"
#include "util/macros.h"
SinglePlayerGame singlePlayerGame;
int SinglePlayerGame::maxAllowedLevelForCurrentGame() {
int level = 1;
std::map<std::string,int>::iterator f = tLXOptions->localplayLevels.find(currentGame);
if(f != tLXOptions->localplayLevels.end())
level = MAX(f->second, 1);
return level;
}
void SinglePlayerGame::setGame(const std::string& game) {
if(!stringcaseequal(currentGame, game)) {
currentGame = game;
setLevel(maxAllowedLevelForCurrentGame());
}
}
static bool gameLevelExists(const std::string& game, int levelNr) {
std::string level;
if(!ReadString("games/games.cfg", game, "Level" + itoa(levelNr), level, "") || Trimmed(level) == "")
return false;
else
return true;
}
static bool gameExists(const std::string& game) {
return gameLevelExists(game, 1);
}
bool SinglePlayerGame::setLevel(int levelNr) {
currentGameValid = false;
image = NULL;
levelInfo = LevelInfo();
modInfo = ModInfo();
description = "";
if(!gameExists(currentGame)) {
description = "<font color=red>Game <b>" + currentGame + "</b> is invalid</font>";
errors << "SinglePlayerGame::setLevel: game " << currentGame << " unknown" << endl;
return false;
}
currentLevel = levelNr;
if(currentLevel <= 0) currentLevel = 1;
if(!gameLevelExists(currentGame, currentLevel)) {
warnings << "SinglePlayerGame::setLevel: game " << currentGame << " doesnt have level " << currentLevel << endl;
do { currentLevel--; }
while(currentLevel > 0 && !gameLevelExists(currentGame, currentLevel));
if(currentLevel <= 0) {
errors << "SinglePlayerGame::setLevel: woot" << endl;
return false;
}
}
std::string level, mod, img;
ReadString("games/games.cfg", currentGame, "Level" + itoa(currentLevel), level, ""); TrimSpaces(level);
ReadString("games/games.cfg", currentGame, "Mod" + itoa(currentLevel), mod, "Classic"); TrimSpaces(mod);
ReadString("games/games.cfg", currentGame, "Image" + itoa(currentLevel), img, ""); TrimSpaces(img);
ReadString("games/games.cfg", currentGame, "Desc" + itoa(currentLevel), description, ""); TrimSpaces(description);
level = "../games/" + currentGame + "/" + level; // it's relative to levels
levelInfo = infoForLevel(level);
if(!levelInfo.valid) {
description = "<font color=red>Problem while loading level " + level + "</font>";
errors << "SinglePlayerGame::setLevel: cannot find map " << level << " for game " << currentGame << ":" << currentLevel << endl;
return false;
}
levelInfo.path = level; // to force this uncommon filename
modInfo = infoForMod(mod);
if(!modInfo.valid) {
description = "<font color=red>Problem while loading mod " + mod + "</font>";
errors << "SinglePlayerGame::setLevel: cannot find mod " << mod << " for game " << currentGame << ":" << currentLevel << endl;
return false;
}
if(description == "")
description = "Undescribed level <b>" + itoa(currentLevel) + "</b> of game <b>" + currentGame + "</b>";
image = LoadGameImage("games/" + currentGame + "/" + img);
if(image.get() == NULL) {
warnings << "SinglePlayerGame::setLevel: cannot load preview image '" << img << "' for game " << currentGame << ":" << currentLevel << endl;
image = gfxCreateSurfaceAlpha(200, 50);
DrawCross(image.get(), 0, 0, 200, 50, Color(255,0,0));
}
currentGameValid = true;
return true;
}
static bool addPlayerToClient() {
// Initialize has cleaned up all worms, so this is not necessarily needed
cClient->setNumWorms(0);
std::string player = tLXOptions->sLastSelectedPlayer;
profile_t *ply = (player == "") ? FindProfile(player) : NULL;
if(ply == NULL) {
for(ply = GetProfiles(); ply; ply = ply->tNext) {
if(ply->iType == PRF_HUMAN->toInt())
// ok
break;
}
}
if(ply == NULL) {
// there is no single human player
AddDefaultPlayers();
// try again
for(ply = GetProfiles(); ply; ply = ply->tNext) {
if(ply->iType == PRF_HUMAN->toInt())
// ok
break;
}
}
if(ply == NULL) {
errors << "addPlayerToClient: this really should never happen, something very messed up happend" << endl;
return false;
}
// this is the current (ugly) way to tell CClient to create a local worm later on with that profile
// that is done in CClientNetEngine::ParseConnected or updateAddedWorms
cClient->getLocalWormProfiles()[0] = ply;
cClient->setNumWorms(1);
return true;
}
static SmartPointer<GameOptions::GameInfo> oldSettings;
bool SinglePlayerGame::startGame() {
if(!currentGameValid) {
errors << "SinglePlayerGame::startGame: cannot start game: current game/level is invalid" << endl;
return false;
}
if(bDedicated) {
errors << "SinglePlayerGame::startGame: cannot do that in dedicated mode" << endl;
// actually, we could but I really dont see a reason why we would want
return false;
}
oldSettings = new GameOptions::GameInfo(tLXOptions->tGameInfo);
tLX->iGameType = GME_LOCAL;
if(! cClient->Initialize() )
{
errors << "Could not initialize client" << endl;
return false;
}
if(!addPlayerToClient()) {
errors << "SinglePlayerGame::startGame: didn't found human worm" << endl;
return false;
}
if(!cServer->StartServer()) {
errors << "Could not start server" << endl;
return false;
}
standardGameMode = NULL;
// don't have any wpn restrictions
cServer->setWeaponRestFile("");
// first set the standards
for( CScriptableVars::const_iterator it = CScriptableVars::begin(); it != CScriptableVars::end(); it++) {
if( strStartsWith(it->first, "GameOptions.GameInfo.") )
it->second.var.setDefault();
}
tLXOptions->tGameInfo.sMapFile = levelInfo.path;
tLXOptions->tGameInfo.sMapName = levelInfo.name;
tLXOptions->tGameInfo.sModDir = modInfo.path;
tLXOptions->tGameInfo.sModName = modInfo.name;
tLXOptions->tGameInfo.features[FT_NewNetEngine] = false;
tLXOptions->tGameInfo.iLives = -2;
tLXOptions->tGameInfo.iKillLimit = -1;
tLXOptions->tGameInfo.fTimeLimit = -1;
tLXOptions->tGameInfo.gameMode = this;
{
std::string extraConfig;
ReadString("games/games.cfg", currentGame, "Config" + itoa(currentLevel), extraConfig, ""); TrimSpaces(extraConfig);
if(extraConfig != "") {
notes << "SinglePlayerGame: config: " << extraConfig << endl;
tLXOptions->LoadFromDisc("games/" + currentGame + "/" + extraConfig);
}
}
{
std::string extraCmdStr;
std::vector<std::string> extraCmds;
ReadString("games/games.cfg", currentGame, "Exec" + itoa(currentLevel), extraCmdStr, ""); TrimSpaces(extraCmdStr);
extraCmds = explode(extraCmdStr, ";");
foreach(c, extraCmds) {
notes << "SinglePlayerGame: exec: " << *c << endl;
Execute( CmdLineIntf::Command(&stdoutCLI(), *c) );
}
}
// this can happen if the config has overwritten it
if(tLXOptions->tGameInfo.gameMode != this) {
// we set the fallback gamemode
standardGameMode = tLXOptions->tGameInfo.gameMode;
tLXOptions->tGameInfo.gameMode = this;
}
levelSucceeded = false;
return true;
}
void SinglePlayerGame::setLevelSucceeded() {
if(levelSucceeded) return;
notes << "SinglePlayerGame: level was succeeded" << endl;
levelSucceeded = true;
tLXOptions->localplayLevels[currentGame] = MAX((int)tLXOptions->localplayLevels[currentGame], (int)currentLevel + 1);
if(gameLevelExists(currentGame, currentLevel + 1))
setLevel(currentLevel + 1);
}
void SinglePlayerGame::Simulate() {
if(standardGameMode)
standardGameMode->Simulate();
if(levelSucceeded)
cServer->RecheckGame();
}
static CWorm* ourLocalHumanWorm() {
for(int i = 0; i < cClient->getNumWorms(); ++i)
if(dynamic_cast<CWormHumanInputHandler*>( cClient->getWorm(i)->getOwner() ) != NULL)
return cClient->getWorm(i);
return NULL;
}
bool SinglePlayerGame::CheckGameOver() {
if(standardGameMode && standardGameMode->CheckGameOver()) {
CWorm* w = ourLocalHumanWorm();
if(w && standardGameMode->Winner() == w->getID())
setLevelSucceeded();
else if(w && standardGameMode->isTeamGame() && standardGameMode->WinnerTeam() == w->getTeam())
setLevelSucceeded();
return true;
}
return levelSucceeded;
}
int SinglePlayerGame::Winner() {
if(!levelSucceeded) {
if(standardGameMode) return standardGameMode->Winner();
return -1;
}
CWorm* w = ourLocalHumanWorm();
if(w) return w->getID();
return -1;
}
void SinglePlayerGame::GameOver() {
if(standardGameMode) standardGameMode->GameOver();
if(oldSettings.get()) {
tLXOptions->tGameInfo = *oldSettings.get();
oldSettings = NULL;
}
// this is kind of a hack; we need it because in CClient::Draw for example,
// we check for it to draw the congratulation msg
tLXOptions->tGameInfo.gameMode = this;
}
<commit_msg>singleplayer: dont set the maxvalue of the levelslider in localmenu to the maxallowedgame but instead to the min(maxallowed,maxexisting)<commit_after>/*
* SinglePlayer.cpp
* OpenLieroX
*
* Created by Albert Zeyer on 15.01.10.
* code under LGPL
*
*/
#include "SinglePlayer.h"
#include "Options.h"
#include "ConfigHandler.h"
#include "game/Mod.h"
#include "game/Level.h"
#include "GfxPrimitives.h"
#include "DeprecatedGUI/Menu.h"
#include "CClient.h"
#include "CServer.h"
#include "ProfileSystem.h"
#include "CWormHuman.h"
#include "OLXCommand.h"
#include "util/macros.h"
SinglePlayerGame singlePlayerGame;
static bool gameLevelExists(const std::string& game, int levelNr) {
std::string level;
if(!ReadString("games/games.cfg", game, "Level" + itoa(levelNr), level, "") || Trimmed(level) == "")
return false;
else
return true;
}
static bool gameExists(const std::string& game) {
return gameLevelExists(game, 1);
}
int SinglePlayerGame::maxAllowedLevelForCurrentGame() {
int level = 1;
std::map<std::string,int>::iterator f = tLXOptions->localplayLevels.find(currentGame);
if(f != tLXOptions->localplayLevels.end())
level = MAX(f->second, 1);
while(level > 1 && !gameLevelExists(currentGame, level))
--level;
return level;
}
void SinglePlayerGame::setGame(const std::string& game) {
if(!stringcaseequal(currentGame, game)) {
currentGame = game;
setLevel(maxAllowedLevelForCurrentGame());
}
}
bool SinglePlayerGame::setLevel(int levelNr) {
currentGameValid = false;
image = NULL;
levelInfo = LevelInfo();
modInfo = ModInfo();
description = "";
if(!gameExists(currentGame)) {
description = "<font color=red>Game <b>" + currentGame + "</b> is invalid</font>";
errors << "SinglePlayerGame::setLevel: game " << currentGame << " unknown" << endl;
return false;
}
currentLevel = levelNr;
if(currentLevel <= 0) currentLevel = 1;
if(!gameLevelExists(currentGame, currentLevel)) {
warnings << "SinglePlayerGame::setLevel: game " << currentGame << " doesnt have level " << currentLevel << endl;
do { currentLevel--; }
while(currentLevel > 0 && !gameLevelExists(currentGame, currentLevel));
if(currentLevel <= 0) {
errors << "SinglePlayerGame::setLevel: woot" << endl;
return false;
}
}
std::string level, mod, img;
ReadString("games/games.cfg", currentGame, "Level" + itoa(currentLevel), level, ""); TrimSpaces(level);
ReadString("games/games.cfg", currentGame, "Mod" + itoa(currentLevel), mod, "Classic"); TrimSpaces(mod);
ReadString("games/games.cfg", currentGame, "Image" + itoa(currentLevel), img, ""); TrimSpaces(img);
ReadString("games/games.cfg", currentGame, "Desc" + itoa(currentLevel), description, ""); TrimSpaces(description);
level = "../games/" + currentGame + "/" + level; // it's relative to levels
levelInfo = infoForLevel(level);
if(!levelInfo.valid) {
description = "<font color=red>Problem while loading level " + level + "</font>";
errors << "SinglePlayerGame::setLevel: cannot find map " << level << " for game " << currentGame << ":" << currentLevel << endl;
return false;
}
levelInfo.path = level; // to force this uncommon filename
modInfo = infoForMod(mod);
if(!modInfo.valid) {
description = "<font color=red>Problem while loading mod " + mod + "</font>";
errors << "SinglePlayerGame::setLevel: cannot find mod " << mod << " for game " << currentGame << ":" << currentLevel << endl;
return false;
}
if(description == "")
description = "Undescribed level <b>" + itoa(currentLevel) + "</b> of game <b>" + currentGame + "</b>";
image = LoadGameImage("games/" + currentGame + "/" + img);
if(image.get() == NULL) {
warnings << "SinglePlayerGame::setLevel: cannot load preview image '" << img << "' for game " << currentGame << ":" << currentLevel << endl;
image = gfxCreateSurfaceAlpha(200, 50);
DrawCross(image.get(), 0, 0, 200, 50, Color(255,0,0));
}
currentGameValid = true;
return true;
}
static bool addPlayerToClient() {
// Initialize has cleaned up all worms, so this is not necessarily needed
cClient->setNumWorms(0);
std::string player = tLXOptions->sLastSelectedPlayer;
profile_t *ply = (player == "") ? FindProfile(player) : NULL;
if(ply == NULL) {
for(ply = GetProfiles(); ply; ply = ply->tNext) {
if(ply->iType == PRF_HUMAN->toInt())
// ok
break;
}
}
if(ply == NULL) {
// there is no single human player
AddDefaultPlayers();
// try again
for(ply = GetProfiles(); ply; ply = ply->tNext) {
if(ply->iType == PRF_HUMAN->toInt())
// ok
break;
}
}
if(ply == NULL) {
errors << "addPlayerToClient: this really should never happen, something very messed up happend" << endl;
return false;
}
// this is the current (ugly) way to tell CClient to create a local worm later on with that profile
// that is done in CClientNetEngine::ParseConnected or updateAddedWorms
cClient->getLocalWormProfiles()[0] = ply;
cClient->setNumWorms(1);
return true;
}
static SmartPointer<GameOptions::GameInfo> oldSettings;
bool SinglePlayerGame::startGame() {
if(!currentGameValid) {
errors << "SinglePlayerGame::startGame: cannot start game: current game/level is invalid" << endl;
return false;
}
if(bDedicated) {
errors << "SinglePlayerGame::startGame: cannot do that in dedicated mode" << endl;
// actually, we could but I really dont see a reason why we would want
return false;
}
oldSettings = new GameOptions::GameInfo(tLXOptions->tGameInfo);
tLX->iGameType = GME_LOCAL;
if(! cClient->Initialize() )
{
errors << "Could not initialize client" << endl;
return false;
}
if(!addPlayerToClient()) {
errors << "SinglePlayerGame::startGame: didn't found human worm" << endl;
return false;
}
if(!cServer->StartServer()) {
errors << "Could not start server" << endl;
return false;
}
standardGameMode = NULL;
// don't have any wpn restrictions
cServer->setWeaponRestFile("");
// first set the standards
for( CScriptableVars::const_iterator it = CScriptableVars::begin(); it != CScriptableVars::end(); it++) {
if( strStartsWith(it->first, "GameOptions.GameInfo.") )
it->second.var.setDefault();
}
tLXOptions->tGameInfo.sMapFile = levelInfo.path;
tLXOptions->tGameInfo.sMapName = levelInfo.name;
tLXOptions->tGameInfo.sModDir = modInfo.path;
tLXOptions->tGameInfo.sModName = modInfo.name;
tLXOptions->tGameInfo.features[FT_NewNetEngine] = false;
tLXOptions->tGameInfo.iLives = -2;
tLXOptions->tGameInfo.iKillLimit = -1;
tLXOptions->tGameInfo.fTimeLimit = -1;
tLXOptions->tGameInfo.gameMode = this;
{
std::string extraConfig;
ReadString("games/games.cfg", currentGame, "Config" + itoa(currentLevel), extraConfig, ""); TrimSpaces(extraConfig);
if(extraConfig != "") {
notes << "SinglePlayerGame: config: " << extraConfig << endl;
tLXOptions->LoadFromDisc("games/" + currentGame + "/" + extraConfig);
}
}
{
std::string extraCmdStr;
std::vector<std::string> extraCmds;
ReadString("games/games.cfg", currentGame, "Exec" + itoa(currentLevel), extraCmdStr, ""); TrimSpaces(extraCmdStr);
extraCmds = explode(extraCmdStr, ";");
foreach(c, extraCmds) {
notes << "SinglePlayerGame: exec: " << *c << endl;
Execute( CmdLineIntf::Command(&stdoutCLI(), *c) );
}
}
// this can happen if the config has overwritten it
if(tLXOptions->tGameInfo.gameMode != this) {
// we set the fallback gamemode
standardGameMode = tLXOptions->tGameInfo.gameMode;
tLXOptions->tGameInfo.gameMode = this;
}
levelSucceeded = false;
return true;
}
void SinglePlayerGame::setLevelSucceeded() {
if(levelSucceeded) return;
notes << "SinglePlayerGame: level was succeeded" << endl;
levelSucceeded = true;
tLXOptions->localplayLevels[currentGame] = MAX((int)tLXOptions->localplayLevels[currentGame], (int)currentLevel + 1);
if(gameLevelExists(currentGame, currentLevel + 1))
setLevel(currentLevel + 1);
}
void SinglePlayerGame::Simulate() {
if(standardGameMode)
standardGameMode->Simulate();
if(levelSucceeded)
cServer->RecheckGame();
}
static CWorm* ourLocalHumanWorm() {
for(int i = 0; i < cClient->getNumWorms(); ++i)
if(dynamic_cast<CWormHumanInputHandler*>( cClient->getWorm(i)->getOwner() ) != NULL)
return cClient->getWorm(i);
return NULL;
}
bool SinglePlayerGame::CheckGameOver() {
if(standardGameMode && standardGameMode->CheckGameOver()) {
CWorm* w = ourLocalHumanWorm();
if(w && standardGameMode->Winner() == w->getID())
setLevelSucceeded();
else if(w && standardGameMode->isTeamGame() && standardGameMode->WinnerTeam() == w->getTeam())
setLevelSucceeded();
return true;
}
return levelSucceeded;
}
int SinglePlayerGame::Winner() {
if(!levelSucceeded) {
if(standardGameMode) return standardGameMode->Winner();
return -1;
}
CWorm* w = ourLocalHumanWorm();
if(w) return w->getID();
return -1;
}
void SinglePlayerGame::GameOver() {
if(standardGameMode) standardGameMode->GameOver();
if(oldSettings.get()) {
tLXOptions->tGameInfo = *oldSettings.get();
oldSettings = NULL;
}
// this is kind of a hack; we need it because in CClient::Draw for example,
// we check for it to draw the congratulation msg
tLXOptions->tGameInfo.gameMode = this;
}
<|endoftext|>
|
<commit_before>/* This file is part of Ingen.
* Copyright 2007-2011 David Robillard <http://drobilla.net>
*
* Ingen is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* Ingen is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "Configuration.hpp"
#include <cstdlib>
#include <cassert>
#include <fstream>
#include <map>
#include "raul/log.hpp"
#include "ingen/client/PortModel.hpp"
#include "ingen/client/PluginModel.hpp"
#include "ingen/serialisation/Parser.hpp"
#include "ingen/shared/LV2URIMap.hpp"
#include "ganv/Port.hpp"
#include "App.hpp"
#include "Port.hpp"
using namespace std;
using namespace Raul;
namespace Ingen {
namespace GUI {
using namespace Ingen::Client;
Configuration::Configuration(App& app)
// Colours from the Tango palette with modified V and alpha
: _app(app)
, _name_style(HUMAN)
, _audio_port_color( 0x4A8A0EC0) // Green
, _control_port_color(0x244678C0) // Blue
, _event_port_color( 0x960909C0) // Red
, _string_port_color( 0x5C3566C0) // Plum
, _value_port_color( 0xBABDB6C0) // Aluminum
{
}
Configuration::~Configuration()
{
}
/** Loads settings from the rc file. Passing no parameter will load from
* the default location.
*/
void
Configuration::load_settings(string filename)
{
/* ... */
}
/** Saves settings to rc file. Passing no parameter will save to the
* default location.
*/
void
Configuration::save_settings(string filename)
{
/* ... */
}
/** Applies the current loaded settings to whichever parts of the app
* need updating.
*/
void
Configuration::apply_settings()
{
/* ... */
}
uint32_t
Configuration::get_port_color(const PortModel* p)
{
assert(p != NULL);
const Shared::URIs& uris = _app.uris();
if (p->is_a(uris.lv2_AudioPort)) {
return _audio_port_color;
} else if (p->supports(uris.atom_String)) {
return _string_port_color;
} else if (_app.can_control(p)) {
return _control_port_color;
} else if (p->is_a(uris.ev_EventPort) || p->is_a(uris.atom_MessagePort)) {
return _event_port_color;
}
warn << "[Configuration] No known port type for " << p->path() << endl;
return 0x666666FF;
}
} // namespace GUI
} // namespace Ingen
<commit_msg>Use opaque port colours.<commit_after>/* This file is part of Ingen.
* Copyright 2007-2011 David Robillard <http://drobilla.net>
*
* Ingen is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* Ingen is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "Configuration.hpp"
#include <cstdlib>
#include <cassert>
#include <fstream>
#include <map>
#include "raul/log.hpp"
#include "ingen/client/PortModel.hpp"
#include "ingen/client/PluginModel.hpp"
#include "ingen/serialisation/Parser.hpp"
#include "ingen/shared/LV2URIMap.hpp"
#include "ganv/Port.hpp"
#include "App.hpp"
#include "Port.hpp"
using namespace std;
using namespace Raul;
namespace Ingen {
namespace GUI {
using namespace Ingen::Client;
Configuration::Configuration(App& app)
// Colours from the Tango palette with modified V
: _app(app)
, _name_style(HUMAN)
, _audio_port_color( 0x4A8A0EFF) // Green
, _control_port_color(0x244678FF) // Blue
, _event_port_color( 0x960909FF) // Red
, _string_port_color( 0x5C3566FF) // Plum
, _value_port_color( 0xBABDB6FF) // Aluminum
{
}
Configuration::~Configuration()
{
}
/** Loads settings from the rc file. Passing no parameter will load from
* the default location.
*/
void
Configuration::load_settings(string filename)
{
/* ... */
}
/** Saves settings to rc file. Passing no parameter will save to the
* default location.
*/
void
Configuration::save_settings(string filename)
{
/* ... */
}
/** Applies the current loaded settings to whichever parts of the app
* need updating.
*/
void
Configuration::apply_settings()
{
/* ... */
}
uint32_t
Configuration::get_port_color(const PortModel* p)
{
assert(p != NULL);
const Shared::URIs& uris = _app.uris();
if (p->is_a(uris.lv2_AudioPort)) {
return _audio_port_color;
} else if (p->supports(uris.atom_String)) {
return _string_port_color;
} else if (_app.can_control(p)) {
return _control_port_color;
} else if (p->is_a(uris.ev_EventPort) || p->is_a(uris.atom_MessagePort)) {
return _event_port_color;
}
warn << "[Configuration] No known port type for " << p->path() << endl;
return 0x666666FF;
}
} // namespace GUI
} // namespace Ingen
<|endoftext|>
|
<commit_before>/*
* Copyright (c)2015 Oasis LMF Limited
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the original author of this software nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#if defined(_MSC_VER)
#include "../wingetopt/wingetopt.h"
#else
#include <getopt.h>
#endif
#ifdef __unix
#include <unistd.h>
#endif
using namespace std;
#include "../include/oasis.hpp"
bool skipheader = false;
bool fullprecision = false;
void doit()
{
int gulstream_type = 0;
int i = fread(&gulstream_type, sizeof(gulstream_type), 1, stdin);
int stream_type = gulstream_type & gulstream_id ;
if (stream_type != gulstream_id) {
std::cerr << "Not a gul stream type\n";
exit(-1);
}
stream_type = streamno_mask &gulstream_type;
if (stream_type == 1 || stream_type == 2){
if (skipheader == false && stream_type==1) printf ("\"event_id\", \"item_id\", \"sidx\", \"loss\"\n");
if (skipheader == false && stream_type==2) printf ("\"event_id\", \"coverage_id\", \"sidx\", \"loss\"\n");
int samplesize=0;
fread(&samplesize, sizeof(samplesize), 1, stdin);
while (i != 0){
gulSampleslevelHeader gh;
i = fread(&gh, sizeof(gh), 1, stdin);
while (i != 0){
gulSampleslevelRec gr;
i = fread(&gr, sizeof(gr), 1, stdin);
if (i == 0) break;
if (gr.sidx == 0) break;
if(fullprecision) printf("%d, %d, %d, %f\n", gh.event_id, gh.item_id, gr.sidx, gr.loss);
else printf("%d, %d, %d, %.2f\n", gh.event_id, gh.item_id, gr.sidx, gr.loss);
}
}
return;
}
std::cerr << "Unsupported gul stream type\n";
}
void help()
{
cerr << "-I inputfilename\n"
<< "-O outputfielname\n"
<< "-s skip header\n"
<< "-f full precision\n"
;
}
int main(int argc, char* argv[])
{
int opt;
std::string inFile;
std::string outFile;
while ((opt = getopt(argc, argv, "hsI:O:")) != -1) {
switch (opt) {
case 'I':
inFile = optarg;
break;
case 'O':
outFile = optarg;
break;
case 's':
skipheader = true;
break;
case 'f':
fullprecision = true;
break;
case 'h':
help();
exit(EXIT_FAILURE);
}
}
initstreams(inFile, outFile);
doit();
return 0;
}
<commit_msg>add -f to command line<commit_after>/*
* Copyright (c)2015 Oasis LMF Limited
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the original author of this software nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#if defined(_MSC_VER)
#include "../wingetopt/wingetopt.h"
#else
#include <getopt.h>
#endif
#ifdef __unix
#include <unistd.h>
#endif
using namespace std;
#include "../include/oasis.hpp"
bool skipheader = false;
bool fullprecision = false;
void doit()
{
int gulstream_type = 0;
int i = fread(&gulstream_type, sizeof(gulstream_type), 1, stdin);
int stream_type = gulstream_type & gulstream_id ;
if (stream_type != gulstream_id) {
std::cerr << "Not a gul stream type\n";
exit(-1);
}
stream_type = streamno_mask &gulstream_type;
if (stream_type == 1 || stream_type == 2){
if (skipheader == false && stream_type==1) printf ("\"event_id\", \"item_id\", \"sidx\", \"loss\"\n");
if (skipheader == false && stream_type==2) printf ("\"event_id\", \"coverage_id\", \"sidx\", \"loss\"\n");
int samplesize=0;
fread(&samplesize, sizeof(samplesize), 1, stdin);
while (i != 0){
gulSampleslevelHeader gh;
i = fread(&gh, sizeof(gh), 1, stdin);
while (i != 0){
gulSampleslevelRec gr;
i = fread(&gr, sizeof(gr), 1, stdin);
if (i == 0) break;
if (gr.sidx == 0) break;
if(fullprecision) printf("%d, %d, %d, %f\n", gh.event_id, gh.item_id, gr.sidx, gr.loss);
else printf("%d, %d, %d, %.2f\n", gh.event_id, gh.item_id, gr.sidx, gr.loss);
}
}
return;
}
std::cerr << "Unsupported gul stream type\n";
}
void help()
{
cerr << "-I inputfilename\n"
<< "-O outputfielname\n"
<< "-s skip header\n"
<< "-f full precision\n"
;
}
int main(int argc, char* argv[])
{
int opt;
std::string inFile;
std::string outFile;
while ((opt = getopt(argc, argv, "hfsI:O:")) != -1) {
switch (opt) {
case 'I':
inFile = optarg;
break;
case 'O':
outFile = optarg;
break;
case 's':
skipheader = true;
break;
case 'f':
fullprecision = true;
break;
case 'h':
help();
exit(EXIT_FAILURE);
}
}
initstreams(inFile, outFile);
doit();
return 0;
}
<|endoftext|>
|
<commit_before>#include "heuristic_minerror.hh"
#include "alg_bdfs.hh"
#include "model.hh"
#include <stdio.h>
#include <glib.h>
#include <sstream>
#include <vector>
#include <string.h>
#define debugprint(args ...) fprintf(stderr, args)
Heuristic_minerror::Heuristic_minerror(Log& l,const std::string& params):
Heuristic::Heuristic(l, params),
m_search_depth(6),
m_key_action(-1)
{
m_logfilename = params;
}
void Heuristic_minerror::set_model(Model* _model)
{
Heuristic::set_model(_model);
gchar* _stdout=NULL;
gchar* _stderr=NULL;
gint exit_status=0;
GError *ger=NULL;
std::string cmd("fmbt-log -f $sn$tv:$as ");
cmd += m_logfilename;
g_spawn_command_line_sync(cmd.c_str(),&_stdout,&_stderr,
&exit_status,&ger);
if (!_stdout) {
errormsg = std::string("Heuristic_minerror cannot execute \"") + cmd + "\"";
status = false;
} else {
parse_traces(_stdout);
g_free(_stdout);
g_free(_stderr);
g_free(ger);
}
}
void Heuristic_minerror::parse_traces(char* log_contents)
{
std::stringstream ss(log_contents);
std::vector<int> trace;
char parsed_action_name[1024];
char parsed_step[16];
while (!ss.eof())
{
ss.getline(parsed_step, 16, ':');
ss.getline(parsed_action_name, 1024);
if (strncmp(parsed_step, "fail", 4) == 0) {
parsed_trace(trace, true);
trace.resize(0);
} else if (strncmp(parsed_step, "pass", 4) == 0) {
parsed_trace(trace, false);
trace.resize(0);
} else {
std::string name(parsed_action_name);
int n = model->action_number(name);
if (n == -1) {
debugprint("Action \"%s\" not found in the model.\n", parsed_action_name);
errormsg = std::string("Action \"") + parsed_action_name + "\" in "
+ m_logfilename + "not found in the model.";
status = -1;
} else {
trace.push_back(n);
}
}
}
}
void Heuristic_minerror::parsed_trace(std::vector<int>& trace, bool is_error_trace)
{
if (is_error_trace && trace.size() > 0)
{
int key_action_position = trace.size() - 1;
int key_action = trace[key_action_position];
if (m_key_action == -1) m_key_action = key_action;
/* This prototype works efficiently with only one key_action,
something to be enhanced later. */
if (m_key_action == key_action) {
add_arming_subtrace(trace, 0, key_action_position - 1);
} else {
debugprint("WARNING: different key actions: old: \"%s\", new: \"%s\"\n",
getActionName(m_key_action).c_str(),
getActionName(key_action).c_str());
key_action = m_key_action; // look for more info related to the old key_action
}
for (int i = 0; i < key_action_position; i++)
{
if (trace[i] == key_action)
add_not_arming_subtrace(trace, 0, i-1);
}
}
else if (!is_error_trace)
{
if (m_key_action == -1) {
debugprint("WARNING: key action not defined, skipping a passing trace.");
}
for (unsigned int i = 0; i < trace.size(); i++)
{
if (trace[i] == m_key_action)
add_not_arming_subtrace(trace, 0, i-1);
}
}
}
void Heuristic_minerror::add_not_arming_subtrace(std::vector<int>& trace, int trace_begin, int trace_end)
{
for (int i = trace_end; i >= trace_begin; i--)
{
std::vector<int> subtrace;
std::map<std::vector<int>, double>::iterator it;
subtrace.assign(trace.begin() + i, trace.begin() + trace_end);
it = m_subtrace2prob.find(subtrace);
if (it == m_subtrace2prob.end()) {
m_subtrace2prob[subtrace] = 0;
debugprint("added: 0 == "); for (unsigned int j = 0; j < subtrace.size(); j++) debugprint("%d ", subtrace[j]); debugprint("\n");
}
else
{
debugprint("subtrace already exists");
}
}
}
void Heuristic_minerror::add_arming_subtrace(std::vector<int>& trace, int trace_begin, int trace_end)
{
debugprint("arming trace: "); for (int j = 0; j <= trace_end; j++) debugprint("%d ", trace[j]); debugprint("\n");
const int max_key_actions = 2;
std::vector<int> candidate_indexes;
for (int num_of_key_actions = 1; // don't include zero-length - though it should be there!
num_of_key_actions <= max_key_actions; num_of_key_actions++)
{
if (trace_begin > trace_end - num_of_key_actions) break;
candidate_indexes.resize(num_of_key_actions);
for (int i = 0; i < num_of_key_actions; i++)
candidate_indexes[i] = trace_end - i;
while (1) {
std::vector<int> candidates;
candidates.resize(num_of_key_actions);
for (unsigned int i = 0; i < candidate_indexes.size(); i++)
candidates[num_of_key_actions-i-1] = trace[candidate_indexes[i]];
if (m_key_action_candidates.find(candidates) == m_key_action_candidates.end())
{
m_key_action_candidates.insert(candidates);
debugprint("candidates: "); for (unsigned int j = 0; j < candidates.size(); j++) debugprint("%d ", candidates[j]); debugprint("\n");
}
// pick next candidate_indexes
int dec_this_index = num_of_key_actions - 1;
while (dec_this_index >= 0) {
if (candidate_indexes[dec_this_index] >= trace_begin + num_of_key_actions - 1) {
candidate_indexes[dec_this_index]--;
for (int i = dec_this_index + 1; i < num_of_key_actions; i++)
candidate_indexes[i] = candidate_indexes[i-1] - 1;
break;
}
dec_this_index --;
}
if (dec_this_index < 0 || candidate_indexes[num_of_key_actions-1] < trace_begin)
break;
}
}
}
bool Heuristic_minerror::execute(int action)
{
return false;
}
float Heuristic_minerror::getCoverage()
{
return 0.0;
}
int Heuristic_minerror::getAction()
{
return 1;
}
int Heuristic_minerror::getIAction()
{
if (m_current_trace.empty())
{
suggest_new_path();
}
return 1;
}
void Heuristic_minerror::suggest_new_path()
{
/* clean up bad key action candidates */
for (std::set<std::vector<int> >::iterator cand_iter = m_key_action_candidates.begin();
cand_iter != m_key_action_candidates.end();
cand_iter++)
{
if ((*cand_iter).empty()) continue;
for (std::map<std::vector<int>, double>::iterator subtrace_iter = m_subtrace2prob.begin();
subtrace_iter != m_subtrace2prob.end();
subtrace_iter++)
{
// If all key action candidates exist in the same
// non-arming trace in the same order, remove they can't
// be key actions. (This assumption does not take into
// account possibility of disarming traces, so it might
// be removing key action candidates too eagerly.)
unsigned int cand_pos = 0;
for (unsigned int trace_pos = 0; trace_pos < subtrace_iter->first.size(); trace_pos++) {
if (subtrace_iter->first[trace_pos] == (*cand_iter)[cand_pos]) {
cand_pos++;
if (cand_pos >= (*cand_iter).size()) {
m_key_action_candidates.erase(cand_iter);
break;
}
}
}
}
}
// DEBUG print remaining candidates
for (std::set<std::vector<int> >::iterator cand_iter = m_key_action_candidates.begin();
cand_iter != m_key_action_candidates.end();
cand_iter++)
{
debugprint("remaining candidate: "); for (unsigned int j = 0; j < (*cand_iter).size(); j++) debugprint("%d ", (*cand_iter)[j]); debugprint("\n");
int step = 1;
model->push();
for (unsigned int actnum = 0; actnum < (*cand_iter).size(); actnum++) {
std::vector<int> path;
AlgPathToAction alg(4);
alg.search(*model, (*cand_iter)[actnum], path);
debugprint("path:\n");
for (unsigned int i=0; i < path.size(); i++) {
debugprint(" %d %s\n", step++, getActionName(path[i]).c_str());
model->execute(path[i]);
}
debugprint(" %d %s\n", step++, getActionName( (*cand_iter)[actnum]).c_str());
model->execute((*cand_iter)[actnum]);
}
model->pop();
}
if (m_key_action_candidates.empty()) return;
std::vector<int> chosen = *(++m_key_action_candidates.begin());
debugprint("chosen candidate: ");
for (unsigned int i=0; i < chosen.size(); i++)
debugprint("%s ", getActionName(chosen[i]).c_str());
debugprint("\n");
}
FACTORY_DEFAULT_CREATOR(Heuristic, Heuristic_minerror, "minerror")
<commit_msg>Added missing copyright comment<commit_after>/*
* fMBT, free Model Based Testing tool
* Copyright (c) 2012, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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 program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include "heuristic_minerror.hh"
#include "alg_bdfs.hh"
#include "model.hh"
#include <stdio.h>
#include <glib.h>
#include <sstream>
#include <vector>
#include <string.h>
#define debugprint(args ...) fprintf(stderr, args)
Heuristic_minerror::Heuristic_minerror(Log& l,const std::string& params):
Heuristic::Heuristic(l, params),
m_search_depth(6),
m_key_action(-1)
{
m_logfilename = params;
}
void Heuristic_minerror::set_model(Model* _model)
{
Heuristic::set_model(_model);
gchar* _stdout=NULL;
gchar* _stderr=NULL;
gint exit_status=0;
GError *ger=NULL;
std::string cmd("fmbt-log -f $sn$tv:$as ");
cmd += m_logfilename;
g_spawn_command_line_sync(cmd.c_str(),&_stdout,&_stderr,
&exit_status,&ger);
if (!_stdout) {
errormsg = std::string("Heuristic_minerror cannot execute \"") + cmd + "\"";
status = false;
} else {
parse_traces(_stdout);
g_free(_stdout);
g_free(_stderr);
g_free(ger);
}
}
void Heuristic_minerror::parse_traces(char* log_contents)
{
std::stringstream ss(log_contents);
std::vector<int> trace;
char parsed_action_name[1024];
char parsed_step[16];
while (!ss.eof())
{
ss.getline(parsed_step, 16, ':');
ss.getline(parsed_action_name, 1024);
if (strncmp(parsed_step, "fail", 4) == 0) {
parsed_trace(trace, true);
trace.resize(0);
} else if (strncmp(parsed_step, "pass", 4) == 0) {
parsed_trace(trace, false);
trace.resize(0);
} else {
std::string name(parsed_action_name);
int n = model->action_number(name);
if (n == -1) {
debugprint("Action \"%s\" not found in the model.\n", parsed_action_name);
errormsg = std::string("Action \"") + parsed_action_name + "\" in "
+ m_logfilename + "not found in the model.";
status = -1;
} else {
trace.push_back(n);
}
}
}
}
void Heuristic_minerror::parsed_trace(std::vector<int>& trace, bool is_error_trace)
{
if (is_error_trace && trace.size() > 0)
{
int key_action_position = trace.size() - 1;
int key_action = trace[key_action_position];
if (m_key_action == -1) m_key_action = key_action;
/* This prototype works efficiently with only one key_action,
something to be enhanced later. */
if (m_key_action == key_action) {
add_arming_subtrace(trace, 0, key_action_position - 1);
} else {
debugprint("WARNING: different key actions: old: \"%s\", new: \"%s\"\n",
getActionName(m_key_action).c_str(),
getActionName(key_action).c_str());
key_action = m_key_action; // look for more info related to the old key_action
}
for (int i = 0; i < key_action_position; i++)
{
if (trace[i] == key_action)
add_not_arming_subtrace(trace, 0, i-1);
}
}
else if (!is_error_trace)
{
if (m_key_action == -1) {
debugprint("WARNING: key action not defined, skipping a passing trace.");
}
for (unsigned int i = 0; i < trace.size(); i++)
{
if (trace[i] == m_key_action)
add_not_arming_subtrace(trace, 0, i-1);
}
}
}
void Heuristic_minerror::add_not_arming_subtrace(std::vector<int>& trace, int trace_begin, int trace_end)
{
for (int i = trace_end; i >= trace_begin; i--)
{
std::vector<int> subtrace;
std::map<std::vector<int>, double>::iterator it;
subtrace.assign(trace.begin() + i, trace.begin() + trace_end);
it = m_subtrace2prob.find(subtrace);
if (it == m_subtrace2prob.end()) {
m_subtrace2prob[subtrace] = 0;
debugprint("added: 0 == "); for (unsigned int j = 0; j < subtrace.size(); j++) debugprint("%d ", subtrace[j]); debugprint("\n");
}
else
{
debugprint("subtrace already exists");
}
}
}
void Heuristic_minerror::add_arming_subtrace(std::vector<int>& trace, int trace_begin, int trace_end)
{
debugprint("arming trace: "); for (int j = 0; j <= trace_end; j++) debugprint("%d ", trace[j]); debugprint("\n");
const int max_key_actions = 2;
std::vector<int> candidate_indexes;
for (int num_of_key_actions = 1; // don't include zero-length - though it should be there!
num_of_key_actions <= max_key_actions; num_of_key_actions++)
{
if (trace_begin > trace_end - num_of_key_actions) break;
candidate_indexes.resize(num_of_key_actions);
for (int i = 0; i < num_of_key_actions; i++)
candidate_indexes[i] = trace_end - i;
while (1) {
std::vector<int> candidates;
candidates.resize(num_of_key_actions);
for (unsigned int i = 0; i < candidate_indexes.size(); i++)
candidates[num_of_key_actions-i-1] = trace[candidate_indexes[i]];
if (m_key_action_candidates.find(candidates) == m_key_action_candidates.end())
{
m_key_action_candidates.insert(candidates);
debugprint("candidates: "); for (unsigned int j = 0; j < candidates.size(); j++) debugprint("%d ", candidates[j]); debugprint("\n");
}
// pick next candidate_indexes
int dec_this_index = num_of_key_actions - 1;
while (dec_this_index >= 0) {
if (candidate_indexes[dec_this_index] >= trace_begin + num_of_key_actions - 1) {
candidate_indexes[dec_this_index]--;
for (int i = dec_this_index + 1; i < num_of_key_actions; i++)
candidate_indexes[i] = candidate_indexes[i-1] - 1;
break;
}
dec_this_index --;
}
if (dec_this_index < 0 || candidate_indexes[num_of_key_actions-1] < trace_begin)
break;
}
}
}
bool Heuristic_minerror::execute(int action)
{
return false;
}
float Heuristic_minerror::getCoverage()
{
return 0.0;
}
int Heuristic_minerror::getAction()
{
return 1;
}
int Heuristic_minerror::getIAction()
{
if (m_current_trace.empty())
{
suggest_new_path();
}
return 1;
}
void Heuristic_minerror::suggest_new_path()
{
/* clean up bad key action candidates */
for (std::set<std::vector<int> >::iterator cand_iter = m_key_action_candidates.begin();
cand_iter != m_key_action_candidates.end();
cand_iter++)
{
if ((*cand_iter).empty()) continue;
for (std::map<std::vector<int>, double>::iterator subtrace_iter = m_subtrace2prob.begin();
subtrace_iter != m_subtrace2prob.end();
subtrace_iter++)
{
// If all key action candidates exist in the same
// non-arming trace in the same order, remove they can't
// be key actions. (This assumption does not take into
// account possibility of disarming traces, so it might
// be removing key action candidates too eagerly.)
unsigned int cand_pos = 0;
for (unsigned int trace_pos = 0; trace_pos < subtrace_iter->first.size(); trace_pos++) {
if (subtrace_iter->first[trace_pos] == (*cand_iter)[cand_pos]) {
cand_pos++;
if (cand_pos >= (*cand_iter).size()) {
m_key_action_candidates.erase(cand_iter);
break;
}
}
}
}
}
// DEBUG print remaining candidates
for (std::set<std::vector<int> >::iterator cand_iter = m_key_action_candidates.begin();
cand_iter != m_key_action_candidates.end();
cand_iter++)
{
debugprint("remaining candidate: "); for (unsigned int j = 0; j < (*cand_iter).size(); j++) debugprint("%d ", (*cand_iter)[j]); debugprint("\n");
int step = 1;
model->push();
for (unsigned int actnum = 0; actnum < (*cand_iter).size(); actnum++) {
std::vector<int> path;
AlgPathToAction alg(4);
alg.search(*model, (*cand_iter)[actnum], path);
debugprint("path:\n");
for (unsigned int i=0; i < path.size(); i++) {
debugprint(" %d %s\n", step++, getActionName(path[i]).c_str());
model->execute(path[i]);
}
debugprint(" %d %s\n", step++, getActionName( (*cand_iter)[actnum]).c_str());
model->execute((*cand_iter)[actnum]);
}
model->pop();
}
if (m_key_action_candidates.empty()) return;
std::vector<int> chosen = *(++m_key_action_candidates.begin());
debugprint("chosen candidate: ");
for (unsigned int i=0; i < chosen.size(); i++)
debugprint("%s ", getActionName(chosen[i]).c_str());
debugprint("\n");
}
FACTORY_DEFAULT_CREATOR(Heuristic, Heuristic_minerror, "minerror")
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of the Qt Build Suite
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used 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.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file.
** Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**************************************************************************/
#include "options.h"
#include <tools/error.h>
#include <tools/fileinfo.h>
#include <tools/logger.h>
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QCoreApplication>
#include <QtCore/QThread>
#include <tools/platform.h>
namespace qbs {
CommandLineOptions::CommandLineOptions()
: m_command(BuildCommand)
, m_dumpGraph(false)
, m_gephi (false)
, m_help (false)
, m_clean (false)
, m_keepGoing(false)
, m_jobs(QThread::idealThreadCount())
{
m_settings = Settings::create();
}
void CommandLineOptions::printHelp()
{
fputs("usage: qbs [command] [options]\n"
"\ncommands:\n"
" build [variant] [property:value]\n"
" build project (default command)\n"
" clean ........... remove all generated files\n"
" shell ........... open a shell\n"
" status [variant] [property:value]\n"
" list files that are (un)tracked by the project\n"
" run target [variant] [property:value] -- <args>\n"
" run the specified target\n"
" config\n"
" set, get, or get all project/global options\n"
"\ngeneral options:\n"
" -h -? --help .... this help\n"
" -d .............. dump graph\n"
" -f <file> ....... specify .qbp project file\n"
" -v .............. verbose (add up to 5 v to increase verbosity level)\n"
"\nbuild options:\n"
" -j <n> .......... use <n> jobs (default is nr of cores)\n"
" -k .............. keep going (ignore errors)\n"
" -n .............. dry run\n"
" --changed-files file [file 2] ... [file n]\n"
" .............. specify a list of out of date files\n"
" --products ProductName [product name 2] ... [product name n]\n"
" .............. specify a list of products to build\n"
"\ngraph options:\n"
" -g .............. show generation graph\n"
, stderr);
}
/**
* Finds automatically the project file (.qbs) in the search directory.
* If there's more than one project file found then this function returns false.
* A project file can explicitely be given by the -f option.
*/
bool CommandLineOptions::readCommandLineArguments(const QStringList &args)
{
m_projectFileName.clear();
m_dryRun = false;
bool firstPositionalEaten = false;
bool runArgMode = false;
int verbosity = 0;
const int argc = args.size();
for (int i = 0; i < argc; ++i) {
QString arg = args.at(i);
if (runArgMode) {
m_runArgs.append(arg);
continue;
}
if (arg == "--") {
runArgMode = true;
continue;
}
// --- no dash
if (arg.at(0) != '-' || arg.length() < 2) {
if (arg == QLatin1String("build")) {
m_command = BuildCommand;
} else if (arg == QLatin1String("config")) {
m_command = ConfigCommand;
m_configureArgs = args.mid(i + 1);
break;
} else if (arg == QLatin1String("clean")) {
m_command = CleanCommand;
} else if (arg == QLatin1String("shell")) {
m_command = StartShellCommand;
} else if (arg == QLatin1String("run")) {
m_command = RunCommand;
} else if (m_command == RunCommand && !firstPositionalEaten) {
m_runTargetName = arg;
firstPositionalEaten = true;
} else if (arg == QLatin1String("status")) {
m_command = StatusCommand;
} else {
m_positional.append(arg);
}
// --- two dashes
} else if (arg.at(1) == '-') {
arg = arg.remove(0, 2).toLower();
QString *targetString = 0;
QStringList *targetStringList = 0;
if (arg == QLatin1String("help")) {
m_help = true;
} else if (arg == "changed-files" && m_command == BuildCommand) {
QStringList changedFiles;
for (++i; i < argc && !args.at(i).startsWith('-'); ++i)
changedFiles += args.at(i);
if (changedFiles.isEmpty()) {
qbsError("--changed-files expects one or more file names.");
return false;
}
m_changedFiles = changedFiles;
--i;
continue;
} else if (arg == "products" && (m_command == BuildCommand || m_command == CleanCommand)) {
QStringList productNames;
for (++i; i < argc && !args.at(i).startsWith('-'); ++i)
productNames += args.at(i);
if (productNames.isEmpty()) {
qbsError("--products expects one or more product names.");
return false;
}
m_selectedProductNames = productNames;
--i;
continue;
} else {
QString err = QLatin1String("Parameter '%1' is unknown.");
qbsError(qPrintable(err.arg(QLatin1String("--") + arg)));
return false;
}
QString stringValue;
if (targetString || targetStringList) {
// string value expected
if (++i >= argc) {
QString err = QLatin1String("String value expected after parameter '%1'.");
qbsError(qPrintable(err.arg(QLatin1String("--") + arg)));
return false;
}
stringValue = args.at(i);
}
if (targetString)
*targetString = stringValue;
else if (targetStringList)
targetStringList->append(stringValue);
// --- one dash
} else {
int k = 1;
switch (arg.at(1).toLower().unicode()) {
case '?':
case 'h':
m_help = true;
break;
case 'j':
if (arg.length() > 2) {
const QByteArray str(arg.mid(2).toAscii());
char *endStr = 0;
m_jobs = strtoul(str.data(), &endStr, 10);
k += endStr - str.data();
} else if (++i < argc) {
m_jobs = args.at(i).toInt();
}
if (m_jobs < 1)
return false;
break;
case 'v':
verbosity = 1;
while (k < arg.length() - 1 && arg.at(k + 1).toLower().unicode() == 'v') {
verbosity++;
k++;
}
break;
case 'd':
m_dumpGraph = true;
break;
case 'f':
if (arg.length() > 2) {
m_projectFileName = arg.mid(2);
k += m_projectFileName.length();
} else if (++i < argc) {
m_projectFileName = args.at(i);
}
m_projectFileName = QDir::fromNativeSeparators(m_projectFileName);
break;
case 'g':
m_gephi = true;
break;
case 'k':
m_keepGoing = true;
break;
case 'n':
m_dryRun = true;
break;
default:
qbsError(qPrintable(QString("Unknown option '%1'.").arg(arg.at(1))));
return false;
}
if (k < arg.length() - 1) { // Trailing characters?
qbsError(qPrintable(QString("Invalid option '%1'.").arg(arg)));
return false;
}
}
}
if (verbosity)
Logger::instance().setLevel(verbosity);
// automatically detect the project file name
if (m_projectFileName.isEmpty())
m_projectFileName = guessProjectFileName();
// make the project file name absolute
if (!m_projectFileName.isEmpty() && !FileInfo::isAbsolute(m_projectFileName)) {
m_projectFileName = FileInfo::resolvePath(QDir::currentPath(), m_projectFileName);
}
// eventually load defaults from configs
#if defined(Q_OS_WIN)
const QChar configPathSeparator = QLatin1Char(';');
#else
const QChar configPathSeparator = QLatin1Char(':');
#endif
if (m_searchPaths.isEmpty())
m_searchPaths = configurationValue("paths/cubes", QVariant()).toString().split(configPathSeparator, QString::SkipEmptyParts);
m_pluginPaths = configurationValue("paths/plugins", QVariant()).toString().split(configPathSeparator, QString::SkipEmptyParts);
// fixup some defaults
if (m_searchPaths.isEmpty())
m_searchPaths.append(qbsRootPath() + "/share/qbs/");
if (m_pluginPaths.isEmpty())
m_pluginPaths.append(qbsRootPath() + "/plugins/");
return true;
}
static void showConfigUsage()
{
puts("usage: qbs config [options]\n"
"\n"
"Config file location:\n"
" --global choose global configuration file\n"
" --local choose local configuration file (default)\n"
"\n"
"Actions:\n"
" --list list all variables\n"
" --unset remove variable with given name\n");
}
void CommandLineOptions::loadLocalProjectSettings(bool throwExceptionOnFailure)
{
if (m_settings->hasProjectSettings())
return;
if (throwExceptionOnFailure && m_projectFileName.isEmpty())
throw Error("Can't find a project file in the current directory. Local configuration not available.");
m_settings->loadProjectSettings(m_projectFileName);
}
void CommandLineOptions::configure()
{
enum ConfigCommand { CfgSet, CfgUnset, CfgList };
ConfigCommand cmd = CfgSet;
Settings::Scope scope = Settings::Local;
bool scopeSet = false;
QStringList args = m_configureArgs;
m_configureArgs.clear();
if (args.isEmpty()) {
showConfigUsage();
return;
}
while (!args.isEmpty() && args.first().startsWith("--")) {
QString arg = args.takeFirst();
arg.remove(0, 2);
if (arg == "list") {
cmd = CfgList;
} else if (arg == "unset") {
cmd = CfgUnset;
} else if (arg == "global") {
scope = Settings::Global;
scopeSet = true;
} else if (arg == "local") {
scope = Settings::Local;
scopeSet = true;
} else {
throw Error("Unknown option for config command.");
}
}
switch (cmd) {
case CfgList:
if (scopeSet) {
if (scope == Settings::Local)
loadLocalProjectSettings(true);
printSettings(scope);
} else {
loadLocalProjectSettings(false);
printSettings(Settings::Local);
printSettings(Settings::Global);
}
break;
case CfgSet:
if (scope == Settings::Local)
loadLocalProjectSettings(true);
if (args.count() > 2)
throw Error("Too many arguments for setting a configuration value.");
if (args.count() == 0) {
showConfigUsage();
} else if (args.count() < 2) {
puts(qPrintable(m_settings->value(scope, args.at(0)).toString()));
} else {
m_settings->setValue(scope, args.at(0), args.at(1));
}
break;
case CfgUnset:
if (scope == Settings::Local)
loadLocalProjectSettings(true);
if (args.isEmpty())
throw Error("unset what?");
foreach (const QString &arg, args)
m_settings->remove(scope, arg);
break;
}
}
QVariant CommandLineOptions::configurationValue(const QString &key, const QVariant &defaultValue)
{
return m_settings->value(key, defaultValue);
}
template <typename S, typename T>
QMap<S,T> &inhaleValues(QMap<S,T> &dst, const QMap<S,T> &src)
{
for (typename QMap<S,T>::const_iterator it=src.constBegin();
it != src.constEnd(); ++it)
{
dst.insert(it.key(), it.value());
}
return dst;
}
QList<QVariantMap> CommandLineOptions::buildConfigurations() const
{
QList<QVariantMap> ret;
QVariantMap globalSet;
QVariantMap currentSet;
QString currentName;
foreach (const QString &arg, positional()) {
int idx = arg.indexOf(':');
if (idx < 0) {
if (currentName.isEmpty()) {
globalSet = currentSet;
} else {
QVariantMap map = globalSet;
inhaleValues(map, currentSet);
if (!map.contains("buildVariant"))
map["buildVariant"] = currentName;
ret.append(map);
}
currentSet.clear();
currentName = arg;
} else {
currentSet.insert(arg.left(idx), arg.mid(idx + 1));
}
}
if (currentName.isEmpty())
currentName = m_settings->value("defaults/buildvariant", "debug").toString();
QVariantMap map = globalSet;
inhaleValues(map, currentSet);
if (!map.contains("buildVariant"))
map["buildVariant"] = currentName;
ret.append(map);
return ret;
}
void CommandLineOptions::printSettings(Settings::Scope scope)
{
if (scope == Settings::Global)
printf("global variables:\n");
else
printf("local variables:\n");
foreach (const QString &key, m_settings->allKeys(scope))
printf("%s = %s\n", qPrintable(key),
qPrintable(m_settings->value(scope, key).toString()));
}
QString CommandLineOptions::guessProjectFileName()
{
QDir searchDir = QDir::current();
for (;;) {
QStringList projectFiles = searchDir.entryList(QStringList() << "*.qbp", QDir::Files);
if (projectFiles.count() == 1) {
QDir::setCurrent(searchDir.path());
return searchDir.absoluteFilePath(projectFiles.first());
} else if (projectFiles.count() > 1) {
QString str = QLatin1String("Multiple project files found in '%1'.\n"
"Please specify the correct project file using the -f option.");
qbsError(qPrintable(str.arg(QDir::toNativeSeparators(searchDir.absolutePath()))));
return QString();
}
if (!searchDir.cdUp())
break;
}
return QString();
}
} // namespace qbs
<commit_msg>make the default job count configurable<commit_after>/**************************************************************************
**
** This file is part of the Qt Build Suite
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used 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.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file.
** Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**************************************************************************/
#include "options.h"
#include <tools/error.h>
#include <tools/fileinfo.h>
#include <tools/logger.h>
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QCoreApplication>
#include <QtCore/QThread>
#include <tools/platform.h>
namespace qbs {
CommandLineOptions::CommandLineOptions()
: m_command(BuildCommand)
, m_dumpGraph(false)
, m_gephi (false)
, m_help (false)
, m_clean (false)
, m_keepGoing(false)
{
m_settings = Settings::create();
m_jobs = configurationValue("defaults/jobs", 0).toInt();
if (m_jobs <= 0)
m_jobs = QThread::idealThreadCount();
}
void CommandLineOptions::printHelp()
{
fputs("usage: qbs [command] [options]\n"
"\ncommands:\n"
" build [variant] [property:value]\n"
" build project (default command)\n"
" clean ........... remove all generated files\n"
" shell ........... open a shell\n"
" status [variant] [property:value]\n"
" list files that are (un)tracked by the project\n"
" run target [variant] [property:value] -- <args>\n"
" run the specified target\n"
" config\n"
" set, get, or get all project/global options\n"
"\ngeneral options:\n"
" -h -? --help .... this help\n"
" -d .............. dump graph\n"
" -f <file> ....... specify .qbp project file\n"
" -v .............. verbose (add up to 5 v to increase verbosity level)\n"
"\nbuild options:\n"
" -j <n> .......... use <n> jobs (default is nr of cores)\n"
" -k .............. keep going (ignore errors)\n"
" -n .............. dry run\n"
" --changed-files file [file 2] ... [file n]\n"
" .............. specify a list of out of date files\n"
" --products ProductName [product name 2] ... [product name n]\n"
" .............. specify a list of products to build\n"
"\ngraph options:\n"
" -g .............. show generation graph\n"
, stderr);
}
/**
* Finds automatically the project file (.qbs) in the search directory.
* If there's more than one project file found then this function returns false.
* A project file can explicitely be given by the -f option.
*/
bool CommandLineOptions::readCommandLineArguments(const QStringList &args)
{
m_projectFileName.clear();
m_dryRun = false;
bool firstPositionalEaten = false;
bool runArgMode = false;
int verbosity = 0;
const int argc = args.size();
for (int i = 0; i < argc; ++i) {
QString arg = args.at(i);
if (runArgMode) {
m_runArgs.append(arg);
continue;
}
if (arg == "--") {
runArgMode = true;
continue;
}
// --- no dash
if (arg.at(0) != '-' || arg.length() < 2) {
if (arg == QLatin1String("build")) {
m_command = BuildCommand;
} else if (arg == QLatin1String("config")) {
m_command = ConfigCommand;
m_configureArgs = args.mid(i + 1);
break;
} else if (arg == QLatin1String("clean")) {
m_command = CleanCommand;
} else if (arg == QLatin1String("shell")) {
m_command = StartShellCommand;
} else if (arg == QLatin1String("run")) {
m_command = RunCommand;
} else if (m_command == RunCommand && !firstPositionalEaten) {
m_runTargetName = arg;
firstPositionalEaten = true;
} else if (arg == QLatin1String("status")) {
m_command = StatusCommand;
} else {
m_positional.append(arg);
}
// --- two dashes
} else if (arg.at(1) == '-') {
arg = arg.remove(0, 2).toLower();
QString *targetString = 0;
QStringList *targetStringList = 0;
if (arg == QLatin1String("help")) {
m_help = true;
} else if (arg == "changed-files" && m_command == BuildCommand) {
QStringList changedFiles;
for (++i; i < argc && !args.at(i).startsWith('-'); ++i)
changedFiles += args.at(i);
if (changedFiles.isEmpty()) {
qbsError("--changed-files expects one or more file names.");
return false;
}
m_changedFiles = changedFiles;
--i;
continue;
} else if (arg == "products" && (m_command == BuildCommand || m_command == CleanCommand)) {
QStringList productNames;
for (++i; i < argc && !args.at(i).startsWith('-'); ++i)
productNames += args.at(i);
if (productNames.isEmpty()) {
qbsError("--products expects one or more product names.");
return false;
}
m_selectedProductNames = productNames;
--i;
continue;
} else {
QString err = QLatin1String("Parameter '%1' is unknown.");
qbsError(qPrintable(err.arg(QLatin1String("--") + arg)));
return false;
}
QString stringValue;
if (targetString || targetStringList) {
// string value expected
if (++i >= argc) {
QString err = QLatin1String("String value expected after parameter '%1'.");
qbsError(qPrintable(err.arg(QLatin1String("--") + arg)));
return false;
}
stringValue = args.at(i);
}
if (targetString)
*targetString = stringValue;
else if (targetStringList)
targetStringList->append(stringValue);
// --- one dash
} else {
int k = 1;
switch (arg.at(1).toLower().unicode()) {
case '?':
case 'h':
m_help = true;
break;
case 'j':
if (arg.length() > 2) {
const QByteArray str(arg.mid(2).toAscii());
char *endStr = 0;
m_jobs = strtoul(str.data(), &endStr, 10);
k += endStr - str.data();
} else if (++i < argc) {
m_jobs = args.at(i).toInt();
}
if (m_jobs < 1)
return false;
break;
case 'v':
verbosity = 1;
while (k < arg.length() - 1 && arg.at(k + 1).toLower().unicode() == 'v') {
verbosity++;
k++;
}
break;
case 'd':
m_dumpGraph = true;
break;
case 'f':
if (arg.length() > 2) {
m_projectFileName = arg.mid(2);
k += m_projectFileName.length();
} else if (++i < argc) {
m_projectFileName = args.at(i);
}
m_projectFileName = QDir::fromNativeSeparators(m_projectFileName);
break;
case 'g':
m_gephi = true;
break;
case 'k':
m_keepGoing = true;
break;
case 'n':
m_dryRun = true;
break;
default:
qbsError(qPrintable(QString("Unknown option '%1'.").arg(arg.at(1))));
return false;
}
if (k < arg.length() - 1) { // Trailing characters?
qbsError(qPrintable(QString("Invalid option '%1'.").arg(arg)));
return false;
}
}
}
if (verbosity)
Logger::instance().setLevel(verbosity);
// automatically detect the project file name
if (m_projectFileName.isEmpty())
m_projectFileName = guessProjectFileName();
// make the project file name absolute
if (!m_projectFileName.isEmpty() && !FileInfo::isAbsolute(m_projectFileName)) {
m_projectFileName = FileInfo::resolvePath(QDir::currentPath(), m_projectFileName);
}
// eventually load defaults from configs
#if defined(Q_OS_WIN)
const QChar configPathSeparator = QLatin1Char(';');
#else
const QChar configPathSeparator = QLatin1Char(':');
#endif
if (m_searchPaths.isEmpty())
m_searchPaths = configurationValue("paths/cubes", QVariant()).toString().split(configPathSeparator, QString::SkipEmptyParts);
m_pluginPaths = configurationValue("paths/plugins", QVariant()).toString().split(configPathSeparator, QString::SkipEmptyParts);
// fixup some defaults
if (m_searchPaths.isEmpty())
m_searchPaths.append(qbsRootPath() + "/share/qbs/");
if (m_pluginPaths.isEmpty())
m_pluginPaths.append(qbsRootPath() + "/plugins/");
return true;
}
static void showConfigUsage()
{
puts("usage: qbs config [options]\n"
"\n"
"Config file location:\n"
" --global choose global configuration file\n"
" --local choose local configuration file (default)\n"
"\n"
"Actions:\n"
" --list list all variables\n"
" --unset remove variable with given name\n");
}
void CommandLineOptions::loadLocalProjectSettings(bool throwExceptionOnFailure)
{
if (m_settings->hasProjectSettings())
return;
if (throwExceptionOnFailure && m_projectFileName.isEmpty())
throw Error("Can't find a project file in the current directory. Local configuration not available.");
m_settings->loadProjectSettings(m_projectFileName);
}
void CommandLineOptions::configure()
{
enum ConfigCommand { CfgSet, CfgUnset, CfgList };
ConfigCommand cmd = CfgSet;
Settings::Scope scope = Settings::Local;
bool scopeSet = false;
QStringList args = m_configureArgs;
m_configureArgs.clear();
if (args.isEmpty()) {
showConfigUsage();
return;
}
while (!args.isEmpty() && args.first().startsWith("--")) {
QString arg = args.takeFirst();
arg.remove(0, 2);
if (arg == "list") {
cmd = CfgList;
} else if (arg == "unset") {
cmd = CfgUnset;
} else if (arg == "global") {
scope = Settings::Global;
scopeSet = true;
} else if (arg == "local") {
scope = Settings::Local;
scopeSet = true;
} else {
throw Error("Unknown option for config command.");
}
}
switch (cmd) {
case CfgList:
if (scopeSet) {
if (scope == Settings::Local)
loadLocalProjectSettings(true);
printSettings(scope);
} else {
loadLocalProjectSettings(false);
printSettings(Settings::Local);
printSettings(Settings::Global);
}
break;
case CfgSet:
if (scope == Settings::Local)
loadLocalProjectSettings(true);
if (args.count() > 2)
throw Error("Too many arguments for setting a configuration value.");
if (args.count() == 0) {
showConfigUsage();
} else if (args.count() < 2) {
puts(qPrintable(m_settings->value(scope, args.at(0)).toString()));
} else {
m_settings->setValue(scope, args.at(0), args.at(1));
}
break;
case CfgUnset:
if (scope == Settings::Local)
loadLocalProjectSettings(true);
if (args.isEmpty())
throw Error("unset what?");
foreach (const QString &arg, args)
m_settings->remove(scope, arg);
break;
}
}
QVariant CommandLineOptions::configurationValue(const QString &key, const QVariant &defaultValue)
{
return m_settings->value(key, defaultValue);
}
template <typename S, typename T>
QMap<S,T> &inhaleValues(QMap<S,T> &dst, const QMap<S,T> &src)
{
for (typename QMap<S,T>::const_iterator it=src.constBegin();
it != src.constEnd(); ++it)
{
dst.insert(it.key(), it.value());
}
return dst;
}
QList<QVariantMap> CommandLineOptions::buildConfigurations() const
{
QList<QVariantMap> ret;
QVariantMap globalSet;
QVariantMap currentSet;
QString currentName;
foreach (const QString &arg, positional()) {
int idx = arg.indexOf(':');
if (idx < 0) {
if (currentName.isEmpty()) {
globalSet = currentSet;
} else {
QVariantMap map = globalSet;
inhaleValues(map, currentSet);
if (!map.contains("buildVariant"))
map["buildVariant"] = currentName;
ret.append(map);
}
currentSet.clear();
currentName = arg;
} else {
currentSet.insert(arg.left(idx), arg.mid(idx + 1));
}
}
if (currentName.isEmpty())
currentName = m_settings->value("defaults/buildvariant", "debug").toString();
QVariantMap map = globalSet;
inhaleValues(map, currentSet);
if (!map.contains("buildVariant"))
map["buildVariant"] = currentName;
ret.append(map);
return ret;
}
void CommandLineOptions::printSettings(Settings::Scope scope)
{
if (scope == Settings::Global)
printf("global variables:\n");
else
printf("local variables:\n");
foreach (const QString &key, m_settings->allKeys(scope))
printf("%s = %s\n", qPrintable(key),
qPrintable(m_settings->value(scope, key).toString()));
}
QString CommandLineOptions::guessProjectFileName()
{
QDir searchDir = QDir::current();
for (;;) {
QStringList projectFiles = searchDir.entryList(QStringList() << "*.qbp", QDir::Files);
if (projectFiles.count() == 1) {
QDir::setCurrent(searchDir.path());
return searchDir.absoluteFilePath(projectFiles.first());
} else if (projectFiles.count() > 1) {
QString str = QLatin1String("Multiple project files found in '%1'.\n"
"Please specify the correct project file using the -f option.");
qbsError(qPrintable(str.arg(QDir::toNativeSeparators(searchDir.absolutePath()))));
return QString();
}
if (!searchDir.cdUp())
break;
}
return QString();
}
} // namespace qbs
<|endoftext|>
|
<commit_before>/*
* Copyright 2009-2020 The VOTCA Development Team
* (http://www.votca.org)
*
* 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.
*
*/
// Local VOTCA includes
#include "votca/xtp/openmp_cuda.h"
namespace votca {
namespace xtp {
OpenMP_CUDA::OpenMP_CUDA() {
inside_Parallel_region_ = OPENMP::InsideActiveParallelRegion();
threadID_parent_ = OPENMP::getThreadId();
cpu_intermediate_input_.resize(getNumberThreads());
cpu_temporaries_.resize(getNumberThreads());
#ifdef USE_CUDA
Index no_gpus = count_available_gpus();
gpus_.clear();
if (inside_Parallel_region_) {
if (threadID_parent_ < no_gpus) {
gpus_.push_back(GPU_data(threadID_parent_));
}
} else {
for (Index i = 0; i < no_gpus; i++) {
gpus_.push_back(GPU_data(i));
}
}
#endif
}
#ifdef USE_CUDA
void OpenMP_CUDA::setOperators(const std::vector<Eigen::MatrixXd>& tensor,
const Eigen::MatrixXd& rightoperator) {
rightoperator_ = &rightoperator;
#pragma omp parallel for num_threads(gpus_.size())
for (Index i = 0; i < Index(gpus_.size()); i++) {
GPU_data& gpu = gpus_[i];
gpu.activateGPU();
const Eigen::MatrixXd& head = tensor.front();
gpu.push_back(head.rows(), head.cols());
gpu.push_back(rightoperator);
gpu.push_back(head.rows(), rightoperator.cols());
}
}
#else
void OpenMP_CUDA::setOperators(const std::vector<Eigen::MatrixXd>&,
const Eigen::MatrixXd& rightoperator) {
rightoperator_ = &rightoperator;
}
#endif
#ifdef USE_CUDA
bool OpenMP_CUDA::isInVector(Index Id, const std::vector<GPU_data>& vec) {
return (std::find_if(vec.begin(), vec.end(), [&Id](const GPU_data& d) {
return d.Id == Id;
}) != vec.end());
}
bool OpenMP_CUDA::isGPUthread(Index ParentThreadId) const {
return isInVector(ParentThreadId, gpus_);
}
#endif
Index OpenMP_CUDA::getParentThreadId() const {
return inside_Parallel_region_ ? threadID_parent_ : OPENMP::getThreadId();
}
Index OpenMP_CUDA::getLocalThreadId(Index ParentThreadId) const {
return inside_Parallel_region_ ? 0 : ParentThreadId;
}
Index OpenMP_CUDA::getNumberThreads() const {
return inside_Parallel_region_ ? 1 : OPENMP::getMaxThreads();
}
/*
* The Cuda device behaves like a server that is receiving matrix-matrix
* multiplications from a single stream (an Nvidia queue) and handle them
* in an asynchronous way. It performs the following operations when recieving
* a request:
* 1. Check that there is enough space for the arrays
* 2. Allocate memory for each matrix
* 3. Copy the matrix to the allocated space
* 4. Perform the matrix multiplication
* 5. Return the result matrix
* The Cuda device knows to which memory address it needs to copy back the
* result. see: https://docs.nvidia.com/cuda/cublas/index.html#thread-safety2
*/
void OpenMP_CUDA::MultiplyRight(Eigen::MatrixXd& tensor) {
// All the GPU communication happens through a single thread that reuses
// all memory allocated in the GPU and it's dynamically load-balanced by
// OpenMP. The rest of the threads use the default CPU matrix
// multiplication
#ifdef USE_CUDA
Index threadid = getParentThreadId();
if (isGPUthread(threadid)) {
GPU_data& gpu = gpus_[getLocalThreadId(threadid)];
gpu.activateGPU();
gpu.Mat(0).copy_to_gpu(tensor);
gpu.pipe().gemm(gpu.Mat(0), gpu.Mat(1), gpu.Mat(2));
tensor = gpu.Mat(2);
} else {
tensor *= *rightoperator_;
}
#else
tensor *= *rightoperator_;
#endif
return;
}
void OpenMP_CUDA::setOperators(const Eigen::MatrixXd& leftoperator,
const Eigen::MatrixXd& rightoperator) {
rightoperator_ = &rightoperator;
leftoperator_ = &leftoperator;
#ifdef USE_CUDA
#pragma omp parallel for num_threads(gpus_.size())
for (Index i = 0; i < Index(gpus_.size()); i++) {
GPU_data& gpu = gpus_[i];
gpu.activateGPU();
gpu.push_back(leftoperator);
gpu.push_back(leftoperator.cols(), rightoperator.rows());
gpu.push_back(leftoperator.rows(), rightoperator.rows());
gpu.push_back(rightoperator);
gpu.push_back(leftoperator.rows(), rightoperator.cols());
}
#endif
}
void OpenMP_CUDA::MultiplyLeftRight(Eigen::MatrixXd& matrix) {
#ifdef USE_CUDA
Index threadid = getParentThreadId();
if (isGPUthread(threadid)) {
GPU_data& gpu = gpus_[getLocalThreadId(threadid)];
gpu.activateGPU();
gpu.Mat(1).copy_to_gpu(matrix);
gpu.pipe().gemm(gpu.Mat(0), gpu.Mat(1), gpu.Mat(2));
gpu.pipe().gemm(gpu.Mat(2), gpu.Mat(3), gpu.Mat(4));
matrix = gpu.Mat(4);
} else {
matrix = (*leftoperator_) * matrix * (*rightoperator_);
}
#else
matrix = (*leftoperator_) * matrix * (*rightoperator_);
#endif
return;
}
#ifdef USE_CUDA
void OpenMP_CUDA::createTemporaries(Index rows, Index cols) {
reduction_ = std::vector<Eigen::MatrixXd>(getNumberThreads(),
Eigen::MatrixXd::Zero(cols, cols));
#pragma omp parallel for num_threads(gpus_.size())
for (Index i = 0; i < Index(gpus_.size()); i++) {
GPU_data& gpu = gpus_[i];
gpu.activateGPU();
gpu.push_back(rows, 1);
gpu.push_back(rows, cols);
gpu.push_back(rows, cols);
gpu.push_back(reduction_[i]);
}
}
#else
void OpenMP_CUDA::createTemporaries(Index, Index cols) {
reduction_ = std::vector<Eigen::MatrixXd>(getNumberThreads(),
Eigen::MatrixXd::Zero(cols, cols));
}
#endif
void OpenMP_CUDA::PushMatrix(Eigen::MatrixXd& matrix) {
Index parentid = getParentThreadId();
Index threadid = getLocalThreadId(parentid);
#ifdef USE_CUDA
if (isGPUthread(parentid)) {
GPU_data& gpu = gpus_[threadid];
gpu.activateGPU();
gpu.Mat(1).copy_to_gpu(matrix);
} else {
cpu_intermediate_input_[threadid] = &matrix;
}
#else
cpu_intermediate_input_[threadid] = &matrix;
#endif
}
void OpenMP_CUDA::A_TDA(const Eigen::VectorXd& vec) {
Index parentid = getParentThreadId();
Index threadid = getLocalThreadId(parentid);
#ifdef USE_CUDA
if (isGPUthread(parentid)) {
GPU_data& gpu = gpus_[threadid];
gpu.activateGPU();
gpu.Mat(0).copy_to_gpu(vec);
gpu.pipe().diag_gemm(gpu.Mat(1), gpu.Mat(0), gpu.Mat(2));
gpu.pipe().gemm(gpu.Mat(1).transpose(), gpu.Mat(2), gpu.Mat(3), 1.0);
} else {
reduction_[threadid] += cpu_intermediate_input_[threadid]->transpose() *
vec.asDiagonal() *
(*cpu_intermediate_input_[threadid]);
}
#else
reduction_[threadid] += cpu_intermediate_input_[threadid]->transpose() *
vec.asDiagonal() *
(*cpu_intermediate_input_[threadid]);
#endif
}
#ifdef USE_CUDA
void OpenMP_CUDA::createTemporaries(const Eigen::VectorXd& vec,
const Eigen::MatrixXd& input, Index rows1,
Index rows2, Index cols) {
reduction_ = std::vector<Eigen::MatrixXd>(
getNumberThreads(), Eigen::MatrixXd::Zero(input.rows(), input.cols()));
temp_ = std::vector<Eigen::VectorXd>(
getNumberThreads(), Eigen::VectorXd::Zero(input.cols()));
rightoperator_ = &input;
vec_ = &vec;
#pragma omp parallel for num_threads(gpus_.size())
for (Index i = 0; i < Index(gpus_.size()); i++) {
GPU_data& gpu = gpus_[i];
gpu.activateGPU();
gpu.push_back(vec);
gpu.push_back(input);
gpu.push_back(rows1, cols);
gpu.push_back(rows2, cols);
gpu.push_back(rows1 * rows2, 1);
gpu.push_back(rows1 * rows2, 1);
gpu.push_back(reduction_[i]);
}
}
#else
void OpenMP_CUDA::createTemporaries(const Eigen::VectorXd& vec,
const Eigen::MatrixXd& input, Index, Index,
Index) {
reduction_ = std::vector<Eigen::MatrixXd>(
getNumberThreads(), Eigen::MatrixXd::Zero(input.rows(), input.cols()));
temp_ = std::vector<Eigen::VectorXd>(
getNumberThreads(), Eigen::VectorXd::Zero(input.rows()));
rightoperator_ = &input;
vec_ = &vec;
}
#endif
void OpenMP_CUDA::PrepareMatrix1(Eigen::MatrixXd& mat) {
Index parentid = getParentThreadId();
Index threadid = getLocalThreadId(parentid);
#ifdef USE_CUDA
if (isGPUthread(parentid)) {
GPU_data& gpu = gpus_[threadid];
gpu.activateGPU();
gpu.Mat(2).copy_to_gpu(mat);
gpu.pipe().diag_gemm(gpu.Mat(2), gpu.Mat(0), gpu.Mat(2));
} else {
cpu_intermediate_input_[threadid] = &mat;
mat *= vec_->asDiagonal();
}
#else
cpu_intermediate_input_[threadid] = &mat;
mat *= vec_->asDiagonal();
#endif
}
void OpenMP_CUDA::SetTempZero() {
Index parentid = getParentThreadId();
Index threadid = getLocalThreadId(parentid);
#ifdef USE_CUDA
if (isGPUthread(parentid)) {
GPU_data& gpu = gpus_[threadid];
gpu.activateGPU();
gpu.Mat(4).setZero();
} else {
temp_[threadid].setZero();
}
#else
temp_[threadid].setZero();
#endif
}
void OpenMP_CUDA::PrepareMatrix2(const Eigen::MatrixXd& mat, bool Hd2) {
Index parentid = getParentThreadId();
Index threadid = getLocalThreadId(parentid);
#ifdef USE_CUDA
if (isGPUthread(parentid)) {
GPU_data& gpu = gpus_[threadid];
gpu.activateGPU();
gpu.Mat(3).copy_to_gpu(mat);
if (Hd2) {
gpu.Mat(4).reshape(gpu.Mat(3).rows(), gpu.Mat(2).rows());
gpu.pipe().gemm(gpu.Mat(3), gpu.Mat(2).transpose(), gpu.Mat(4), 1.0);
} else {
gpu.Mat(4).reshape(gpu.Mat(2).rows(), gpu.Mat(3).rows());
gpu.pipe().gemm(gpu.Mat(2), gpu.Mat(3).transpose(), gpu.Mat(4), 1.0);
}
gpu.Mat(4).reshape(gpu.Mat(2).rows() * gpu.Mat(3).rows(), 1);
} else {
if (Hd2) {
Eigen::Map<Eigen::MatrixXd> row(
temp_[threadid].data(), mat.rows(),
cpu_intermediate_input_[threadid]->rows());
row += mat * cpu_intermediate_input_[threadid]->transpose();
} else {
Eigen::Map<Eigen::MatrixXd> row(temp_[threadid].data(),
cpu_intermediate_input_[threadid]->rows(),
mat.rows());
row += *cpu_intermediate_input_[threadid] * mat.transpose();
}
}
#else
if (Hd2) {
Eigen::Map<Eigen::MatrixXd> row(temp_[threadid].data(), mat.rows(),
cpu_intermediate_input_[threadid]->rows());
row += mat * cpu_intermediate_input_[threadid]->transpose();
} else {
Eigen::Map<Eigen::MatrixXd> row(temp_[threadid].data(),
cpu_intermediate_input_[threadid]->rows(),
mat.rows());
row += *cpu_intermediate_input_[threadid] * mat.transpose();
}
#endif
}
void OpenMP_CUDA::Addvec(const Eigen::VectorXd& row) {
Index parentid = getParentThreadId();
Index threadid = getLocalThreadId(parentid);
#ifdef USE_CUDA
if (isGPUthread(parentid)) {
GPU_data& gpu = gpus_[threadid];
gpu.activateGPU();
gpu.Mat(5).copy_to_gpu(row);
gpu.pipe().axpy(gpu.Mat(5), gpu.Mat(4), 1.0);
} else {
temp_[threadid] += row;
}
#else
temp_[threadid] += row;
#endif
}
void OpenMP_CUDA::MultiplyRow(Index row) {
Index parentid = getParentThreadId();
Index threadid = getLocalThreadId(parentid);
#ifdef USE_CUDA
if (isGPUthread(parentid)) {
GPU_data& gpu = gpus_[threadid];
gpu.activateGPU();
gpu.pipe().gemm(gpu.Mat(4).transpose(), gpu.Mat(1),
gpu.Mat(6).block(row, 0, 1, gpu.Mat(1).cols()), 0.0);
} else {
reduction_[threadid].row(row) = temp_[threadid].transpose() * (*rightoperator_);
}
#else
reduction_[threadid].row(row) = temp_[threadid].transpose() * (*rightoperator_);
#endif
}
Eigen::MatrixXd OpenMP_CUDA::getReductionVar() {
#ifdef USE_CUDA
#pragma omp parallel for num_threads(gpus_.size())
for (Index i = 0; i < Index(gpus_.size()); i++) {
GPU_data& gpu = gpus_[i];
gpu.activateGPU();
reduction_[i] = *(gpu.temp.back());
}
#endif
for (Index i = 1; i < Index(reduction_.size()); i++) {
reduction_[0] += reduction_[i];
}
return reduction_[0];
}
} // namespace xtp
} // namespace votca
<commit_msg>forgot rpa transpose()<commit_after>/*
* Copyright 2009-2020 The VOTCA Development Team
* (http://www.votca.org)
*
* 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.
*
*/
// Local VOTCA includes
#include "votca/xtp/openmp_cuda.h"
namespace votca {
namespace xtp {
OpenMP_CUDA::OpenMP_CUDA() {
inside_Parallel_region_ = OPENMP::InsideActiveParallelRegion();
threadID_parent_ = OPENMP::getThreadId();
cpu_intermediate_input_.resize(getNumberThreads());
cpu_temporaries_.resize(getNumberThreads());
#ifdef USE_CUDA
Index no_gpus = count_available_gpus();
gpus_.clear();
if (inside_Parallel_region_) {
if (threadID_parent_ < no_gpus) {
gpus_.push_back(GPU_data(threadID_parent_));
}
} else {
for (Index i = 0; i < no_gpus; i++) {
gpus_.push_back(GPU_data(i));
}
}
#endif
}
#ifdef USE_CUDA
void OpenMP_CUDA::setOperators(const std::vector<Eigen::MatrixXd>& tensor,
const Eigen::MatrixXd& rightoperator) {
rightoperator_ = &rightoperator;
#pragma omp parallel for num_threads(gpus_.size())
for (Index i = 0; i < Index(gpus_.size()); i++) {
GPU_data& gpu = gpus_[i];
gpu.activateGPU();
const Eigen::MatrixXd& head = tensor.front();
gpu.push_back(head.rows(), head.cols());
gpu.push_back(rightoperator);
gpu.push_back(head.rows(), rightoperator.cols());
}
}
#else
void OpenMP_CUDA::setOperators(const std::vector<Eigen::MatrixXd>&,
const Eigen::MatrixXd& rightoperator) {
rightoperator_ = &rightoperator;
}
#endif
#ifdef USE_CUDA
bool OpenMP_CUDA::isInVector(Index Id, const std::vector<GPU_data>& vec) {
return (std::find_if(vec.begin(), vec.end(), [&Id](const GPU_data& d) {
return d.Id == Id;
}) != vec.end());
}
bool OpenMP_CUDA::isGPUthread(Index ParentThreadId) const {
return isInVector(ParentThreadId, gpus_);
}
#endif
Index OpenMP_CUDA::getParentThreadId() const {
return inside_Parallel_region_ ? threadID_parent_ : OPENMP::getThreadId();
}
Index OpenMP_CUDA::getLocalThreadId(Index ParentThreadId) const {
return inside_Parallel_region_ ? 0 : ParentThreadId;
}
Index OpenMP_CUDA::getNumberThreads() const {
return inside_Parallel_region_ ? 1 : OPENMP::getMaxThreads();
}
/*
* The Cuda device behaves like a server that is receiving matrix-matrix
* multiplications from a single stream (an Nvidia queue) and handle them
* in an asynchronous way. It performs the following operations when recieving
* a request:
* 1. Check that there is enough space for the arrays
* 2. Allocate memory for each matrix
* 3. Copy the matrix to the allocated space
* 4. Perform the matrix multiplication
* 5. Return the result matrix
* The Cuda device knows to which memory address it needs to copy back the
* result. see: https://docs.nvidia.com/cuda/cublas/index.html#thread-safety2
*/
void OpenMP_CUDA::MultiplyRight(Eigen::MatrixXd& tensor) {
// All the GPU communication happens through a single thread that reuses
// all memory allocated in the GPU and it's dynamically load-balanced by
// OpenMP. The rest of the threads use the default CPU matrix
// multiplication
#ifdef USE_CUDA
Index threadid = getParentThreadId();
if (isGPUthread(threadid)) {
GPU_data& gpu = gpus_[getLocalThreadId(threadid)];
gpu.activateGPU();
gpu.Mat(0).copy_to_gpu(tensor);
gpu.pipe().gemm(gpu.Mat(0), gpu.Mat(1), gpu.Mat(2));
tensor = gpu.Mat(2);
} else {
tensor *= *rightoperator_;
}
#else
tensor *= *rightoperator_;
#endif
return;
}
void OpenMP_CUDA::setOperators(const Eigen::MatrixXd& leftoperator,
const Eigen::MatrixXd& rightoperator) {
rightoperator_ = &rightoperator;
leftoperator_ = &leftoperator;
#ifdef USE_CUDA
#pragma omp parallel for num_threads(gpus_.size())
for (Index i = 0; i < Index(gpus_.size()); i++) {
GPU_data& gpu = gpus_[i];
gpu.activateGPU();
gpu.push_back(leftoperator);
gpu.push_back(leftoperator.cols(), rightoperator.rows());
gpu.push_back(leftoperator.rows(), rightoperator.rows());
gpu.push_back(rightoperator);
gpu.push_back(leftoperator.rows(), rightoperator.cols());
}
#endif
}
void OpenMP_CUDA::MultiplyLeftRight(Eigen::MatrixXd& matrix) {
#ifdef USE_CUDA
Index threadid = getParentThreadId();
if (isGPUthread(threadid)) {
GPU_data& gpu = gpus_[getLocalThreadId(threadid)];
gpu.activateGPU();
gpu.Mat(1).copy_to_gpu(matrix);
gpu.pipe().gemm(gpu.Mat(0), gpu.Mat(1), gpu.Mat(2));
gpu.pipe().gemm(gpu.Mat(2), gpu.Mat(3), gpu.Mat(4));
matrix = gpu.Mat(4);
} else {
matrix = (*leftoperator_) * matrix * (*rightoperator_);
}
#else
matrix = (*leftoperator_) * matrix * (*rightoperator_);
#endif
return;
}
#ifdef USE_CUDA
void OpenMP_CUDA::createTemporaries(Index rows, Index cols) {
reduction_ = std::vector<Eigen::MatrixXd>(getNumberThreads(),
Eigen::MatrixXd::Zero(cols, cols));
#pragma omp parallel for num_threads(gpus_.size())
for (Index i = 0; i < Index(gpus_.size()); i++) {
GPU_data& gpu = gpus_[i];
gpu.activateGPU();
gpu.push_back(rows, 1);
gpu.push_back(rows, cols);
gpu.push_back(rows, cols);
gpu.push_back(reduction_[i]);
}
}
#else
void OpenMP_CUDA::createTemporaries(Index, Index cols) {
reduction_ = std::vector<Eigen::MatrixXd>(getNumberThreads(),
Eigen::MatrixXd::Zero(cols, cols));
}
#endif
void OpenMP_CUDA::PushMatrix(Eigen::MatrixXd& matrix) {
Index parentid = getParentThreadId();
Index threadid = getLocalThreadId(parentid);
#ifdef USE_CUDA
if (isGPUthread(parentid)) {
GPU_data& gpu = gpus_[threadid];
gpu.activateGPU();
gpu.Mat(1).copy_to_gpu(matrix);
} else {
cpu_intermediate_input_[threadid] = &matrix;
}
#else
cpu_intermediate_input_[threadid] = &matrix;
#endif
}
void OpenMP_CUDA::A_TDA(const Eigen::VectorXd& vec) {
Index parentid = getParentThreadId();
Index threadid = getLocalThreadId(parentid);
#ifdef USE_CUDA
if (isGPUthread(parentid)) {
GPU_data& gpu = gpus_[threadid];
gpu.activateGPU();
gpu.Mat(0).copy_to_gpu(vec);
gpu.pipe().diag_gemm(gpu.Mat(1).transpose(), gpu.Mat(0), gpu.Mat(2));
gpu.pipe().gemm(gpu.Mat(1).transpose(), gpu.Mat(2), gpu.Mat(3), 1.0);
} else {
reduction_[threadid] += cpu_intermediate_input_[threadid]->transpose() *
vec.asDiagonal() *
(*cpu_intermediate_input_[threadid]);
}
#else
reduction_[threadid] += cpu_intermediate_input_[threadid]->transpose() *
vec.asDiagonal() *
(*cpu_intermediate_input_[threadid]);
#endif
}
#ifdef USE_CUDA
void OpenMP_CUDA::createTemporaries(const Eigen::VectorXd& vec,
const Eigen::MatrixXd& input, Index rows1,
Index rows2, Index cols) {
reduction_ = std::vector<Eigen::MatrixXd>(
getNumberThreads(), Eigen::MatrixXd::Zero(input.rows(), input.cols()));
temp_ = std::vector<Eigen::VectorXd>(
getNumberThreads(), Eigen::VectorXd::Zero(input.cols()));
rightoperator_ = &input;
vec_ = &vec;
#pragma omp parallel for num_threads(gpus_.size())
for (Index i = 0; i < Index(gpus_.size()); i++) {
GPU_data& gpu = gpus_[i];
gpu.activateGPU();
gpu.push_back(vec);
gpu.push_back(input);
gpu.push_back(rows1, cols);
gpu.push_back(rows2, cols);
gpu.push_back(rows1 * rows2, 1);
gpu.push_back(rows1 * rows2, 1);
gpu.push_back(reduction_[i]);
}
}
#else
void OpenMP_CUDA::createTemporaries(const Eigen::VectorXd& vec,
const Eigen::MatrixXd& input, Index, Index,
Index) {
reduction_ = std::vector<Eigen::MatrixXd>(
getNumberThreads(), Eigen::MatrixXd::Zero(input.rows(), input.cols()));
temp_ = std::vector<Eigen::VectorXd>(
getNumberThreads(), Eigen::VectorXd::Zero(input.rows()));
rightoperator_ = &input;
vec_ = &vec;
}
#endif
void OpenMP_CUDA::PrepareMatrix1(Eigen::MatrixXd& mat) {
Index parentid = getParentThreadId();
Index threadid = getLocalThreadId(parentid);
#ifdef USE_CUDA
if (isGPUthread(parentid)) {
GPU_data& gpu = gpus_[threadid];
gpu.activateGPU();
gpu.Mat(2).copy_to_gpu(mat);
gpu.pipe().diag_gemm(gpu.Mat(2), gpu.Mat(0), gpu.Mat(2));
} else {
cpu_intermediate_input_[threadid] = &mat;
mat *= vec_->asDiagonal();
}
#else
cpu_intermediate_input_[threadid] = &mat;
mat *= vec_->asDiagonal();
#endif
}
void OpenMP_CUDA::SetTempZero() {
Index parentid = getParentThreadId();
Index threadid = getLocalThreadId(parentid);
#ifdef USE_CUDA
if (isGPUthread(parentid)) {
GPU_data& gpu = gpus_[threadid];
gpu.activateGPU();
gpu.Mat(4).setZero();
} else {
temp_[threadid].setZero();
}
#else
temp_[threadid].setZero();
#endif
}
void OpenMP_CUDA::PrepareMatrix2(const Eigen::MatrixXd& mat, bool Hd2) {
Index parentid = getParentThreadId();
Index threadid = getLocalThreadId(parentid);
#ifdef USE_CUDA
if (isGPUthread(parentid)) {
GPU_data& gpu = gpus_[threadid];
gpu.activateGPU();
gpu.Mat(3).copy_to_gpu(mat);
if (Hd2) {
gpu.Mat(4).reshape(gpu.Mat(3).rows(), gpu.Mat(2).rows());
gpu.pipe().gemm(gpu.Mat(3), gpu.Mat(2).transpose(), gpu.Mat(4), 1.0);
} else {
gpu.Mat(4).reshape(gpu.Mat(2).rows(), gpu.Mat(3).rows());
gpu.pipe().gemm(gpu.Mat(2), gpu.Mat(3).transpose(), gpu.Mat(4), 1.0);
}
gpu.Mat(4).reshape(gpu.Mat(2).rows() * gpu.Mat(3).rows(), 1);
} else {
if (Hd2) {
Eigen::Map<Eigen::MatrixXd> row(
temp_[threadid].data(), mat.rows(),
cpu_intermediate_input_[threadid]->rows());
row += mat * cpu_intermediate_input_[threadid]->transpose();
} else {
Eigen::Map<Eigen::MatrixXd> row(temp_[threadid].data(),
cpu_intermediate_input_[threadid]->rows(),
mat.rows());
row += *cpu_intermediate_input_[threadid] * mat.transpose();
}
}
#else
if (Hd2) {
Eigen::Map<Eigen::MatrixXd> row(temp_[threadid].data(), mat.rows(),
cpu_intermediate_input_[threadid]->rows());
row += mat * cpu_intermediate_input_[threadid]->transpose();
} else {
Eigen::Map<Eigen::MatrixXd> row(temp_[threadid].data(),
cpu_intermediate_input_[threadid]->rows(),
mat.rows());
row += *cpu_intermediate_input_[threadid] * mat.transpose();
}
#endif
}
void OpenMP_CUDA::Addvec(const Eigen::VectorXd& row) {
Index parentid = getParentThreadId();
Index threadid = getLocalThreadId(parentid);
#ifdef USE_CUDA
if (isGPUthread(parentid)) {
GPU_data& gpu = gpus_[threadid];
gpu.activateGPU();
gpu.Mat(5).copy_to_gpu(row);
gpu.pipe().axpy(gpu.Mat(5), gpu.Mat(4), 1.0);
} else {
temp_[threadid] += row;
}
#else
temp_[threadid] += row;
#endif
}
void OpenMP_CUDA::MultiplyRow(Index row) {
Index parentid = getParentThreadId();
Index threadid = getLocalThreadId(parentid);
#ifdef USE_CUDA
if (isGPUthread(parentid)) {
GPU_data& gpu = gpus_[threadid];
gpu.activateGPU();
gpu.pipe().gemm(gpu.Mat(4).transpose(), gpu.Mat(1),
gpu.Mat(6).block(row, 0, 1, gpu.Mat(1).cols()), 0.0);
} else {
reduction_[threadid].row(row) = temp_[threadid].transpose() * (*rightoperator_);
}
#else
reduction_[threadid].row(row) = temp_[threadid].transpose() * (*rightoperator_);
#endif
}
Eigen::MatrixXd OpenMP_CUDA::getReductionVar() {
#ifdef USE_CUDA
#pragma omp parallel for num_threads(gpus_.size())
for (Index i = 0; i < Index(gpus_.size()); i++) {
GPU_data& gpu = gpus_[i];
gpu.activateGPU();
reduction_[i] = *(gpu.temp.back());
}
#endif
for (Index i = 1; i < Index(reduction_.size()); i++) {
reduction_[0] += reduction_[i];
}
return reduction_[0];
}
} // namespace xtp
} // namespace votca
<|endoftext|>
|
<commit_before>
const char COPYRIGHT[] =
"Copyright (c) 1998-2000 Stephen Williams (steve@icarus.com)";
/*
* This source code is free software; you can redistribute it
* and/or modify it in source code form under the terms of the GNU
* General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#if !defined(WINNT) && !defined(macintosh)
#ident "$Id: main.cc,v 1.42 2001/06/23 18:41:02 steve Exp $"
#endif
const char NOTICE[] =
" This program is free software; you can redistribute it and/or modify\n"
" it under the terms of the GNU General Public License as published by\n"
" the Free Software Foundation; either version 2 of the License, or\n"
" (at your option) any later version.\n"
"\n"
" This program is distributed in the hope that it will be useful,\n"
" but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
" GNU General Public License for more details.\n"
"\n"
" You should have received a copy of the GNU General Public License\n"
" along with this program; if not, write to the Free Software\n"
" Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA\n"
;
# include <stdio.h>
# include <iostream.h>
# include <fstream>
# include <queue>
# include <map>
# include <unistd.h>
# include <stdlib.h>
#if defined(HAVE_GETOPT_H)
# include <getopt.h>
#endif
# include "pform.h"
# include "netlist.h"
# include "target.h"
# include "compiler.h"
#if defined(__MINGW32__) && !defined(HAVE_GETOPT_H)
extern "C" int getopt(int argc, char*argv[], const char*fmt);
extern "C" int optind;
extern "C" const char*optarg;
#endif
const char VERSION[] = "$Name: $ $State: Exp $";
const char*target = "null";
string start_module = "";
map<string,string> flags;
/*
* These are the warning enable flags.
*/
bool warn_implicit = false;
static void parm_to_flagmap(const string&flag)
{
string key, value;
unsigned off = flag.find('=');
if (off > flag.size()) {
key = flag;
value = "";
} else {
key = flag.substr(0, off);
value = flag.substr(off+1);
}
flags[key] = value;
}
extern Design* elaborate(const map<string,Module*>&modules,
const map<string,PUdp*>&primitives,
const string&root);
extern void cprop(Design*des);
extern void synth(Design*des);
extern void syn_rules(Design*des);
extern void nodangle(Design*des);
extern void xnfio(Design*des);
typedef void (*net_func)(Design*);
static struct net_func_map {
const char*name;
void (*func)(Design*);
} func_table[] = {
{ "cprop", &cprop },
{ "nodangle",&nodangle },
{ "synth", &synth },
{ "syn-rules", &syn_rules },
{ "xnfio", &xnfio },
{ 0, 0 }
};
net_func name_to_net_func(const string&name)
{
for (unsigned idx = 0 ; func_table[idx].name ; idx += 1)
if (name == func_table[idx].name)
return func_table[idx].func;
return 0;
}
int main(int argc, char*argv[])
{
bool help_flag = false;
const char* net_path = 0;
const char* pf_path = 0;
const char* warn_en = "";
int opt;
unsigned flag_errors = 0;
queue<net_func> net_func_queue;
flags["VPI_MODULE_LIST"] = "system";
flags["-o"] = "a.out";
min_typ_max_flag = TYP;
min_typ_max_warn = 10;
while ((opt = getopt(argc, argv, "F:f:hm:N:o:P:p:s:T:t:vW:")) != EOF) switch (opt) {
case 'F': {
net_func tmp = name_to_net_func(optarg);
if (tmp == 0) {
cerr << "No such design transform function ``"
<< optarg << "''." << endl;
flag_errors += 1;
break;
}
net_func_queue.push(tmp);
break;
}
case 'f':
parm_to_flagmap(optarg);
break;
case 'h':
help_flag = true;
break;
case 'm':
flags["VPI_MODULE_LIST"] = flags["VPI_MODULE_LIST"]+","+optarg;
break;
case 'N':
net_path = optarg;
break;
case 'o':
flags["-o"] = optarg;
break;
case 'P':
pf_path = optarg;
break;
case 'p':
parm_to_flagmap(optarg);
break;
case 's':
start_module = optarg;
break;
case 'T':
if (strcmp(optarg,"min") == 0) {
min_typ_max_flag = MIN;
min_typ_max_warn = 0;
} else if (strcmp(optarg,"typ") == 0) {
min_typ_max_flag = TYP;
min_typ_max_warn = 0;
} else if (strcmp(optarg,"max") == 0) {
min_typ_max_flag = MAX;
min_typ_max_warn = 0;
} else {
cerr << "Invalid argument (" << optarg << ") to -T flag."
<< endl;
flag_errors += 1;
}
break;
case 't':
target = optarg;
break;
case 'v':
cout << "Icarus Verilog version " << VERSION << endl;
cout << COPYRIGHT << endl;
cout << endl << NOTICE << endl;
return 0;
case 'W':
warn_en = optarg;
break;
default:
flag_errors += 1;
break;
}
if (flag_errors)
return flag_errors;
if (help_flag) {
cout << "Netlist functions:" << endl;
for (unsigned idx = 0 ; func_table[idx].name ; idx += 1)
cout << " " << func_table[idx].name << endl;
cout << "Target types:" << endl;
for (unsigned idx = 0 ; target_table[idx] ; idx += 1)
cout << " " << target_table[idx]->name << endl;
return 0;
}
if (optind == argc) {
cerr << "No input files." << endl;
return 1;
}
/* Scan the warnings enable string for warning flags. */
for (const char*cp = warn_en ; *cp ; cp += 1) switch (*cp) {
case 'i':
warn_implicit = true;
break;
default:
break;
}
/* Parse the input. Make the pform. */
map<string,Module*> modules;
map<string,PUdp*> primitives;
int rc = pform_parse(argv[optind], modules, primitives);
if (pf_path) {
ofstream out (pf_path);
out << "PFORM DUMP MODULES:" << endl;
for (map<string,Module*>::iterator mod = modules.begin()
; mod != modules.end()
; mod ++ ) {
pform_dump(out, (*mod).second);
}
out << "PFORM DUMP PRIMITIVES:" << endl;
for (map<string,PUdp*>::iterator idx = primitives.begin()
; idx != primitives.end()
; idx ++ ) {
(*idx).second->dump(out);
}
}
if (rc) {
return rc;
}
/* If the user did not give a specific module to start with,
then look for the single module that has no ports. If there
are multiple modules with no ports, then give up. */
if (start_module == "") {
for (map<string,Module*>::iterator mod = modules.begin()
; mod != modules.end()
; mod ++ ) {
Module*cur = (*mod).second;
if (cur->port_count() == 0)
if (start_module == "") {
start_module = cur->get_name();
} else {
cerr << "More then 1 top level module."
<< endl;
return 1;
}
}
}
/* If the previous attempt to find a start module failed, but
there is only one module, then just let the user get away
with it. */
if ((start_module == "") && (modules.size() == 1)) {
map<string,Module*>::iterator mod = modules.begin();
Module*cur = (*mod).second;
start_module = cur->get_name();
}
/* If there is *still* no guess for the root module, then give
up completely, and complain. */
if (start_module == "") {
cerr << "No top level modules, and no -s option." << endl;
return 1;
}
/* On with the process of elaborating the module. */
Design*des = elaborate(modules, primitives, start_module);
if (des == 0) {
cerr << start_module << ": error: "
<< "Unable to elaborate module." << endl;
return 1;
}
if (des->errors) {
cerr << start_module << ": error: " << des->errors
<< " elaborating module." << endl;
return des->errors;
}
des->set_flags(flags);
while (!net_func_queue.empty()) {
net_func func = net_func_queue.front();
net_func_queue.pop();
func(des);
}
if (net_path) {
ofstream out (net_path);
des->dump(out);
}
bool emit_rc = emit(des, target);
if (!emit_rc) {
cerr << "error: Code generation had errors." << endl;
return 1;
}
return 0;
}
/*
* $Log: main.cc,v $
* Revision 1.42 2001/06/23 18:41:02 steve
* Include stdlib.h
*
* Revision 1.41 2001/05/20 17:35:05 steve
* declare getopt by hand in mingw32 compile.
*
* Revision 1.40 2001/01/20 19:02:05 steve
* Switch hte -f flag to the -p flag.
*
* Revision 1.39 2000/11/22 20:48:32 steve
* Allow sole module to be a root.
*
* Revision 1.38 2000/09/12 01:17:40 steve
* Version information for vlog_vpi_info.
*
* Revision 1.37 2000/08/09 03:43:45 steve
* Move all file manipulation out of target class.
*
* Revision 1.36 2000/07/29 17:58:21 steve
* Introduce min:typ:max support.
*
* Revision 1.35 2000/07/14 06:12:57 steve
* Move inital value handling from NetNet to Nexus
* objects. This allows better propogation of inital
* values.
*
* Clean up constant propagation a bit to account
* for regs that are not really values.
*
* Revision 1.34 2000/05/13 20:55:47 steve
* Use yacc based synthesizer.
*
* Revision 1.33 2000/05/08 05:29:43 steve
* no need for nobufz functor.
*
* Revision 1.32 2000/05/03 22:14:31 steve
* More features of ivl available through iverilog.
*
* Revision 1.31 2000/04/12 20:02:53 steve
* Finally remove the NetNEvent and NetPEvent classes,
* Get synthesis working with the NetEvWait class,
* and get started supporting multiple events in a
* wait in vvm.
*/
<commit_msg> Add the -V flag, and some verbose messages.<commit_after>
const char COPYRIGHT[] =
"Copyright (c) 1998-2000 Stephen Williams (steve@icarus.com)";
/*
* This source code is free software; you can redistribute it
* and/or modify it in source code form under the terms of the GNU
* General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#if !defined(WINNT) && !defined(macintosh)
#ident "$Id: main.cc,v 1.43 2001/07/02 01:57:27 steve Exp $"
#endif
const char NOTICE[] =
" This program is free software; you can redistribute it and/or modify\n"
" it under the terms of the GNU General Public License as published by\n"
" the Free Software Foundation; either version 2 of the License, or\n"
" (at your option) any later version.\n"
"\n"
" This program is distributed in the hope that it will be useful,\n"
" but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
" GNU General Public License for more details.\n"
"\n"
" You should have received a copy of the GNU General Public License\n"
" along with this program; if not, write to the Free Software\n"
" Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA\n"
;
# include <stdio.h>
# include <iostream.h>
# include <fstream>
# include <queue>
# include <map>
# include <unistd.h>
# include <stdlib.h>
#if defined(HAVE_GETOPT_H)
# include <getopt.h>
#endif
# include "pform.h"
# include "netlist.h"
# include "target.h"
# include "compiler.h"
#if defined(__MINGW32__) && !defined(HAVE_GETOPT_H)
extern "C" int getopt(int argc, char*argv[], const char*fmt);
extern "C" int optind;
extern "C" const char*optarg;
#endif
const char VERSION[] = "$Name: $ $State: Exp $";
const char*target = "null";
string start_module = "";
map<string,string> flags;
/*
* These are the warning enable flags.
*/
bool warn_implicit = false;
static void parm_to_flagmap(const string&flag)
{
string key, value;
unsigned off = flag.find('=');
if (off > flag.size()) {
key = flag;
value = "";
} else {
key = flag.substr(0, off);
value = flag.substr(off+1);
}
flags[key] = value;
}
extern Design* elaborate(const map<string,Module*>&modules,
const map<string,PUdp*>&primitives,
const string&root);
extern void cprop(Design*des);
extern void synth(Design*des);
extern void syn_rules(Design*des);
extern void nodangle(Design*des);
extern void xnfio(Design*des);
typedef void (*net_func)(Design*);
static struct net_func_map {
const char*name;
void (*func)(Design*);
} func_table[] = {
{ "cprop", &cprop },
{ "nodangle",&nodangle },
{ "synth", &synth },
{ "syn-rules", &syn_rules },
{ "xnfio", &xnfio },
{ 0, 0 }
};
net_func name_to_net_func(const string&name)
{
for (unsigned idx = 0 ; func_table[idx].name ; idx += 1)
if (name == func_table[idx].name)
return func_table[idx].func;
return 0;
}
int main(int argc, char*argv[])
{
bool help_flag = false;
bool verbose_flag = false;
const char* net_path = 0;
const char* pf_path = 0;
const char* warn_en = "";
int opt;
unsigned flag_errors = 0;
queue<net_func> net_func_queue;
flags["VPI_MODULE_LIST"] = "system";
flags["-o"] = "a.out";
min_typ_max_flag = TYP;
min_typ_max_warn = 10;
while ((opt = getopt(argc, argv, "F:f:hm:N:o:P:p:s:T:t:VvW:")) != EOF) switch (opt) {
case 'F': {
net_func tmp = name_to_net_func(optarg);
if (tmp == 0) {
cerr << "No such design transform function ``"
<< optarg << "''." << endl;
flag_errors += 1;
break;
}
net_func_queue.push(tmp);
break;
}
case 'f':
parm_to_flagmap(optarg);
break;
case 'h':
help_flag = true;
break;
case 'm':
flags["VPI_MODULE_LIST"] = flags["VPI_MODULE_LIST"]+","+optarg;
break;
case 'N':
net_path = optarg;
break;
case 'o':
flags["-o"] = optarg;
break;
case 'P':
pf_path = optarg;
break;
case 'p':
parm_to_flagmap(optarg);
break;
case 's':
start_module = optarg;
break;
case 'T':
if (strcmp(optarg,"min") == 0) {
min_typ_max_flag = MIN;
min_typ_max_warn = 0;
} else if (strcmp(optarg,"typ") == 0) {
min_typ_max_flag = TYP;
min_typ_max_warn = 0;
} else if (strcmp(optarg,"max") == 0) {
min_typ_max_flag = MAX;
min_typ_max_warn = 0;
} else {
cerr << "Invalid argument (" << optarg << ") to -T flag."
<< endl;
flag_errors += 1;
}
break;
case 't':
target = optarg;
break;
case 'V':
verbose_flag = true;
break;
case 'v':
cout << "Icarus Verilog version " << VERSION << endl;
cout << COPYRIGHT << endl;
cout << endl << NOTICE << endl;
return 0;
case 'W':
warn_en = optarg;
break;
default:
flag_errors += 1;
break;
}
if (flag_errors)
return flag_errors;
if (help_flag) {
cout << "Netlist functions:" << endl;
for (unsigned idx = 0 ; func_table[idx].name ; idx += 1)
cout << " " << func_table[idx].name << endl;
cout << "Target types:" << endl;
for (unsigned idx = 0 ; target_table[idx] ; idx += 1)
cout << " " << target_table[idx]->name << endl;
return 0;
}
if (optind == argc) {
cerr << "No input files." << endl;
return 1;
}
/* Scan the warnings enable string for warning flags. */
for (const char*cp = warn_en ; *cp ; cp += 1) switch (*cp) {
case 'i':
warn_implicit = true;
break;
default:
break;
}
if (verbose_flag) {
cout << "PARSING INPUT..." << endl;
}
/* Parse the input. Make the pform. */
map<string,Module*> modules;
map<string,PUdp*> primitives;
int rc = pform_parse(argv[optind], modules, primitives);
if (pf_path) {
ofstream out (pf_path);
out << "PFORM DUMP MODULES:" << endl;
for (map<string,Module*>::iterator mod = modules.begin()
; mod != modules.end()
; mod ++ ) {
pform_dump(out, (*mod).second);
}
out << "PFORM DUMP PRIMITIVES:" << endl;
for (map<string,PUdp*>::iterator idx = primitives.begin()
; idx != primitives.end()
; idx ++ ) {
(*idx).second->dump(out);
}
}
if (rc) {
return rc;
}
/* If the user did not give a specific module to start with,
then look for the single module that has no ports. If there
are multiple modules with no ports, then give up. */
if (start_module == "") {
for (map<string,Module*>::iterator mod = modules.begin()
; mod != modules.end()
; mod ++ ) {
Module*cur = (*mod).second;
if (cur->port_count() == 0)
if (start_module == "") {
start_module = cur->get_name();
} else {
cerr << "More then 1 top level module."
<< endl;
return 1;
}
}
}
/* If the previous attempt to find a start module failed, but
there is only one module, then just let the user get away
with it. */
if ((start_module == "") && (modules.size() == 1)) {
map<string,Module*>::iterator mod = modules.begin();
Module*cur = (*mod).second;
start_module = cur->get_name();
}
/* If there is *still* no guess for the root module, then give
up completely, and complain. */
if (start_module == "") {
cerr << "No top level modules, and no -s option." << endl;
return 1;
}
if (verbose_flag) {
cout << "ELABORATING DESIGN..." << endl;
}
/* On with the process of elaborating the module. */
Design*des = elaborate(modules, primitives, start_module);
if (des == 0) {
cerr << start_module << ": error: "
<< "Unable to elaborate module." << endl;
return 1;
}
if (des->errors) {
cerr << start_module << ": error: " << des->errors
<< " elaborating module." << endl;
return des->errors;
}
des->set_flags(flags);
if (verbose_flag) {
cout << "RUNNING FUNCTORS..." << endl;
}
while (!net_func_queue.empty()) {
net_func func = net_func_queue.front();
net_func_queue.pop();
func(des);
}
if (net_path) {
ofstream out (net_path);
des->dump(out);
}
if (verbose_flag) {
cout << "STARTING CODE GENERATOR..." << endl;
}
bool emit_rc = emit(des, target);
if (!emit_rc) {
cerr << "error: Code generation had errors." << endl;
return 1;
}
if (verbose_flag) {
cout << "DONE." << endl;
}
return 0;
}
/*
* $Log: main.cc,v $
* Revision 1.43 2001/07/02 01:57:27 steve
* Add the -V flag, and some verbose messages.
*
* Revision 1.42 2001/06/23 18:41:02 steve
* Include stdlib.h
*
* Revision 1.41 2001/05/20 17:35:05 steve
* declare getopt by hand in mingw32 compile.
*
* Revision 1.40 2001/01/20 19:02:05 steve
* Switch hte -f flag to the -p flag.
*
* Revision 1.39 2000/11/22 20:48:32 steve
* Allow sole module to be a root.
*
* Revision 1.38 2000/09/12 01:17:40 steve
* Version information for vlog_vpi_info.
*
* Revision 1.37 2000/08/09 03:43:45 steve
* Move all file manipulation out of target class.
*
* Revision 1.36 2000/07/29 17:58:21 steve
* Introduce min:typ:max support.
*
* Revision 1.35 2000/07/14 06:12:57 steve
* Move inital value handling from NetNet to Nexus
* objects. This allows better propogation of inital
* values.
*
* Clean up constant propagation a bit to account
* for regs that are not really values.
*
* Revision 1.34 2000/05/13 20:55:47 steve
* Use yacc based synthesizer.
*
* Revision 1.33 2000/05/08 05:29:43 steve
* no need for nobufz functor.
*
* Revision 1.32 2000/05/03 22:14:31 steve
* More features of ivl available through iverilog.
*
* Revision 1.31 2000/04/12 20:02:53 steve
* Finally remove the NetNEvent and NetPEvent classes,
* Get synthesis working with the NetEvWait class,
* and get started supporting multiple events in a
* wait in vvm.
*/
<|endoftext|>
|
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXDE-Qt - a lightweight, Qt based, desktop toolset
* http://lxde.org/
*
* Copyright: 2014 LXQt team
* Authors:
* Hong Jen Yee (PCMan) <pcman.tw@gmail.com>
*
* This program or library is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* END_COMMON_COPYRIGHT_HEADER */
#include "lxqtplatformtheme.h"
#include <QVariant>
#include <QDebug>
#include <QIcon>
#include <QStandardPaths>
#include <QApplication>
#include <QWidget>
#include <QMetaObject>
#include <QMetaProperty>
#include <QMetaEnum>
#include <QToolBar>
#include <QSettings>
#include <QTimer>
#include <QDir>
#include <QFileInfo>
#include <QFileSystemWatcher>
#include <QStyle>
#include "qiconloader_p.h"
LXQtPlatformTheme::LXQtPlatformTheme():
settingsWatcher_(NULL)
{
// When the plugin is loaded, it seems that the app is not yet running and
// QThread environment is not completely set up. So creating filesystem watcher
// does not work since it uses QSocketNotifier internally which can only be
// created within QThread thread. So let's schedule a idle handler to initialize
// the watcher in the main event loop.
loadSettings();
QTimer::singleShot(0, this, SLOT(initWatch()));
}
LXQtPlatformTheme::~LXQtPlatformTheme() {
if(settingsWatcher_)
delete settingsWatcher_;
}
void LXQtPlatformTheme::initWatch()
{
settingsWatcher_ = new QFileSystemWatcher();
settingsWatcher_->addPath(settingsFile_);
connect(settingsWatcher_, &QFileSystemWatcher::fileChanged, this, &LXQtPlatformTheme::onSettingsChanged);
}
void LXQtPlatformTheme::loadSettings() {
// QSettings is really handy. It tries to read from /etc/xdg/lxqt/lxqt.conf
// as a fallback if a key is missing from the user config file ~/.config/lxqt/lxqt.conf.
// So we can customize the default values in /etc/xdg/lxqt/lxqt.conf and does
// not necessarily to hard code the default values here.
QSettings settings(QSettings::UserScope, "lxqt", "lxqt");
settingsFile_ = settings.fileName();
// icon theme
iconTheme_ = settings.value("icon_theme", "oxygen").toString();
// read other widget related settings form LxQt settings.
QByteArray tb_style = settings.value("tool_button_style").toByteArray();
// convert toolbar style name to value
QMetaEnum me = QToolBar::staticMetaObject.property(QToolBar::staticMetaObject.indexOfProperty("toolButtonStyle")).enumerator();
int value = me.keyToValue(tb_style.constData());
if(value == -1)
toolButtonStyle_ = Qt::ToolButtonTextBesideIcon;
else
toolButtonStyle_ = static_cast<Qt::ToolButtonStyle>(value);
// single click activation
singleClickActivate_ = settings.value("single_click_activate").toBool();
// load Qt settings
settings.beginGroup(QLatin1String("Qt"));
// widget style
style_ = settings.value(QLatin1String("style"), QLatin1String("fusion")).toString();
// SystemFont
fontStr_ = settings.value(QLatin1String("font")).toString();
if(!fontStr_.isEmpty()) {
if(font_.fromString(fontStr_))
QApplication::setFont(font_); // it seems that we need to do this manually.
}
// FixedFont
fixedFontStr_ = settings.value(QLatin1String("fixedFont")).toString();
if(!fixedFontStr_.isEmpty()) {
fixedFont_.fromString(fixedFontStr_);
}
// mouse
doubleClickInterval_ = settings.value(QLatin1String("doubleClickInterval"));
wheelScrollLines_ = settings.value(QLatin1String("wheelScrollLines"));
// keyboard
cursorFlashTime_ = settings.value(QLatin1String("cursorFlashTime"));
settings.endGroup();
}
// this is called whenever the config file is changed.
void LXQtPlatformTheme::onSettingsChanged() {
// D*mn! yet another Qt 5.4 regression!!!
// See the bug report: https://github.com/lxde/lxqt/issues/441
// Since Qt 5.4, QSettings uses QSaveFile to save the config files.
// https://github.com/qtproject/qtbase/commit/8d15068911d7c0ba05732e2796aaa7a90e34a6a1#diff-e691c0405f02f3478f4f50a27bdaecde
// QSaveFile will save the content to a new temp file, and replace the old file later.
// Hence the existing config file is not changed. Instead, it's deleted and then replaced.
// This new behaviour unfortunately breaks QFileSystemWatcher.
// After file deletion, we can no longer receive any new change notifications.
// The most ridiculous thing is, QFileSystemWatcher does not provide a
// way for us to know if a file is deleted. WT*?
// Luckily, I found a workaround: If the file path no longer exists
// in the watcher's files(), this file is deleted.
bool file_deleted = !settingsWatcher_->files().contains(settingsFile_);
if(file_deleted) // if our config file is already deleted, reinstall a new watcher
settingsWatcher_->addPath(settingsFile_);
// NOTE: in Qt4, Qt monitors the change of _QT_SETTINGS_TIMESTAMP root property and
// reload Trolltech.conf when the value is changed. Then, it automatically
// applies the new settings.
// Unfortunately, this is no longer the case in Qt5. Yes, yet another regression.
// We're free to provide our own platform plugin, but Qt5 does not
// update the settings and repaint the UI. We need to do it ourselves
// through dirty hacks and private Qt internal APIs.
QString oldStyle = style_;
QString oldIconTheme = iconTheme_;
QString oldFont = fontStr_;
QString oldFixedFont = fixedFontStr_;
loadSettings(); // reload the config file
if(style_ != oldStyle) // the widget style is changed
{
// ask Qt5 to apply the new style
if (qobject_cast<QApplication *>(QCoreApplication::instance()))
QApplication::setStyle(style_);
}
if(iconTheme_ != oldIconTheme) { // the icon theme is changed
QIconLoader::instance()->updateSystemTheme(); // this is a private internal API of Qt5.
}
// if font is changed
if(oldFont != fontStr_ || oldFixedFont != fixedFontStr_){
// FIXME: to my knowledge there is no way to ask Qt to reload the fonts.
// Should we call QApplication::setFont() to override the font?
// This does not work with QSS, though.
//
// After reading the source code of Qt, I think the right method to call
// here is QApplicationPrivate::setSystemFont(). However, this is an
// internal API and should not be used. Let's call QApplication::setFont()
// instead since it approximately does the same thing.
// Internally, QApplication will emit QEvent::ApplicationFontChange so
// all of the widgets will update their fonts.
// FIXME: should we call the internal API: QApplicationPrivate::setFont() instead?
// QGtkStyle does this internally.
fixedFont_.fromString(fixedFontStr_); // FIXME: how to set this to the app?
if(font_.fromString(fontStr_))
QApplication::setFont(font_);
}
// emit a ThemeChange event to all widgets
Q_FOREACH(QWidget* widget, QApplication::allWidgets()) {
// Qt5 added a QEvent::ThemeChange event.
QEvent event(QEvent::ThemeChange);
QApplication::sendEvent(widget, &event);
}
}
bool LXQtPlatformTheme::usePlatformNativeDialog(DialogType type) const {
return false;
}
#if 0
QPlatformDialogHelper *LXQtPlatformTheme::createPlatformDialogHelper(DialogType type) const {
return 0;
}
#endif
const QPalette *LXQtPlatformTheme::palette(Palette type) const {
if (type == QPlatformTheme::SystemPalette)
// the default constructor uses the default palette
return new QPalette;
return QPlatformTheme::palette(type);
}
const QFont *LXQtPlatformTheme::font(Font type) const {
if(type == SystemFont && !fontStr_.isEmpty()) {
// NOTE: for some reason, this is not called by Qt when program startup.
// So we do QApplication::setFont() manually.
return &font_;
}
else if(type == FixedFont && !fixedFontStr_.isEmpty()) {
return &fixedFont_;
}
return QPlatformTheme::font(type);
}
QVariant LXQtPlatformTheme::themeHint(ThemeHint hint) const {
switch (hint) {
case CursorFlashTime:
return cursorFlashTime_;
case KeyboardInputInterval:
break;
case MouseDoubleClickInterval:
return doubleClickInterval_;
case StartDragDistance:
break;
case StartDragTime:
break;
case KeyboardAutoRepeatRate:
break;
case PasswordMaskDelay:
break;
case StartDragVelocity:
break;
case TextCursorWidth:
break;
case DropShadow:
return QVariant(true);
case MaximumScrollBarDragDistance:
break;
case ToolButtonStyle:
return QVariant(toolButtonStyle_);
case ToolBarIconSize:
break;
case ItemViewActivateItemOnSingleClick:
return QVariant(singleClickActivate_);
case SystemIconThemeName:
return iconTheme_;
case SystemIconFallbackThemeName:
return "hicolor";
case IconThemeSearchPaths:
return xdgIconThemePaths();
case StyleNames:
return QStringList() << style_;
case WindowAutoPlacement:
break;
case DialogButtonBoxLayout:
break;
case DialogButtonBoxButtonsHaveIcons:
return QVariant(true);
case UseFullScreenForPopupMenu:
break;
case KeyboardScheme:
return QVariant(X11KeyboardScheme);
case UiEffects:
break;
case SpellCheckUnderlineStyle:
break;
case TabAllWidgets:
break;
case IconPixmapSizes:
break;
case PasswordMaskCharacter:
break;
case DialogSnapToDefaultButton:
break;
case ContextMenuOnMouseRelease:
break;
case MousePressAndHoldInterval:
break;
case MouseDoubleClickDistance:
break;
default:
break;
}
return QPlatformTheme::themeHint(hint);
}
// Helper to return the icon theme paths from XDG.
QStringList LXQtPlatformTheme::xdgIconThemePaths() const
{
QStringList paths;
// Add home directory first in search path
const QFileInfo homeIconDir(QDir::homePath() + QStringLiteral("/.icons"));
if (homeIconDir.isDir())
paths.prepend(homeIconDir.absoluteFilePath());
QString xdgDirString = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
if (xdgDirString.isEmpty())
xdgDirString = QLatin1String("/usr/local/share/:/usr/share/");
foreach (const QString &xdgDir, xdgDirString.split(QLatin1Char(':'))) {
const QFileInfo xdgIconsDir(xdgDir + QStringLiteral("/icons"));
if (xdgIconsDir.isDir())
paths.append(xdgIconsDir.absoluteFilePath());
}
return paths;
}
<commit_msg>Adds $XDG_DATA_HOME to the XdgIconThemePaths<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXDE-Qt - a lightweight, Qt based, desktop toolset
* http://lxde.org/
*
* Copyright: 2014 LXQt team
* Authors:
* Hong Jen Yee (PCMan) <pcman.tw@gmail.com>
*
* This program or library is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* END_COMMON_COPYRIGHT_HEADER */
#include "lxqtplatformtheme.h"
#include <QVariant>
#include <QDebug>
#include <QIcon>
#include <QStandardPaths>
#include <QApplication>
#include <QWidget>
#include <QMetaObject>
#include <QMetaProperty>
#include <QMetaEnum>
#include <QToolBar>
#include <QSettings>
#include <QTimer>
#include <QDir>
#include <QFileInfo>
#include <QFileSystemWatcher>
#include <QStyle>
#include "qiconloader_p.h"
LXQtPlatformTheme::LXQtPlatformTheme():
settingsWatcher_(NULL)
{
// When the plugin is loaded, it seems that the app is not yet running and
// QThread environment is not completely set up. So creating filesystem watcher
// does not work since it uses QSocketNotifier internally which can only be
// created within QThread thread. So let's schedule a idle handler to initialize
// the watcher in the main event loop.
loadSettings();
QTimer::singleShot(0, this, SLOT(initWatch()));
}
LXQtPlatformTheme::~LXQtPlatformTheme() {
if(settingsWatcher_)
delete settingsWatcher_;
}
void LXQtPlatformTheme::initWatch()
{
settingsWatcher_ = new QFileSystemWatcher();
settingsWatcher_->addPath(settingsFile_);
connect(settingsWatcher_, &QFileSystemWatcher::fileChanged, this, &LXQtPlatformTheme::onSettingsChanged);
}
void LXQtPlatformTheme::loadSettings() {
// QSettings is really handy. It tries to read from /etc/xdg/lxqt/lxqt.conf
// as a fallback if a key is missing from the user config file ~/.config/lxqt/lxqt.conf.
// So we can customize the default values in /etc/xdg/lxqt/lxqt.conf and does
// not necessarily to hard code the default values here.
QSettings settings(QSettings::UserScope, "lxqt", "lxqt");
settingsFile_ = settings.fileName();
// icon theme
iconTheme_ = settings.value("icon_theme", "oxygen").toString();
// read other widget related settings form LxQt settings.
QByteArray tb_style = settings.value("tool_button_style").toByteArray();
// convert toolbar style name to value
QMetaEnum me = QToolBar::staticMetaObject.property(QToolBar::staticMetaObject.indexOfProperty("toolButtonStyle")).enumerator();
int value = me.keyToValue(tb_style.constData());
if(value == -1)
toolButtonStyle_ = Qt::ToolButtonTextBesideIcon;
else
toolButtonStyle_ = static_cast<Qt::ToolButtonStyle>(value);
// single click activation
singleClickActivate_ = settings.value("single_click_activate").toBool();
// load Qt settings
settings.beginGroup(QLatin1String("Qt"));
// widget style
style_ = settings.value(QLatin1String("style"), QLatin1String("fusion")).toString();
// SystemFont
fontStr_ = settings.value(QLatin1String("font")).toString();
if(!fontStr_.isEmpty()) {
if(font_.fromString(fontStr_))
QApplication::setFont(font_); // it seems that we need to do this manually.
}
// FixedFont
fixedFontStr_ = settings.value(QLatin1String("fixedFont")).toString();
if(!fixedFontStr_.isEmpty()) {
fixedFont_.fromString(fixedFontStr_);
}
// mouse
doubleClickInterval_ = settings.value(QLatin1String("doubleClickInterval"));
wheelScrollLines_ = settings.value(QLatin1String("wheelScrollLines"));
// keyboard
cursorFlashTime_ = settings.value(QLatin1String("cursorFlashTime"));
settings.endGroup();
}
// this is called whenever the config file is changed.
void LXQtPlatformTheme::onSettingsChanged() {
// D*mn! yet another Qt 5.4 regression!!!
// See the bug report: https://github.com/lxde/lxqt/issues/441
// Since Qt 5.4, QSettings uses QSaveFile to save the config files.
// https://github.com/qtproject/qtbase/commit/8d15068911d7c0ba05732e2796aaa7a90e34a6a1#diff-e691c0405f02f3478f4f50a27bdaecde
// QSaveFile will save the content to a new temp file, and replace the old file later.
// Hence the existing config file is not changed. Instead, it's deleted and then replaced.
// This new behaviour unfortunately breaks QFileSystemWatcher.
// After file deletion, we can no longer receive any new change notifications.
// The most ridiculous thing is, QFileSystemWatcher does not provide a
// way for us to know if a file is deleted. WT*?
// Luckily, I found a workaround: If the file path no longer exists
// in the watcher's files(), this file is deleted.
bool file_deleted = !settingsWatcher_->files().contains(settingsFile_);
if(file_deleted) // if our config file is already deleted, reinstall a new watcher
settingsWatcher_->addPath(settingsFile_);
// NOTE: in Qt4, Qt monitors the change of _QT_SETTINGS_TIMESTAMP root property and
// reload Trolltech.conf when the value is changed. Then, it automatically
// applies the new settings.
// Unfortunately, this is no longer the case in Qt5. Yes, yet another regression.
// We're free to provide our own platform plugin, but Qt5 does not
// update the settings and repaint the UI. We need to do it ourselves
// through dirty hacks and private Qt internal APIs.
QString oldStyle = style_;
QString oldIconTheme = iconTheme_;
QString oldFont = fontStr_;
QString oldFixedFont = fixedFontStr_;
loadSettings(); // reload the config file
if(style_ != oldStyle) // the widget style is changed
{
// ask Qt5 to apply the new style
if (qobject_cast<QApplication *>(QCoreApplication::instance()))
QApplication::setStyle(style_);
}
if(iconTheme_ != oldIconTheme) { // the icon theme is changed
QIconLoader::instance()->updateSystemTheme(); // this is a private internal API of Qt5.
}
// if font is changed
if(oldFont != fontStr_ || oldFixedFont != fixedFontStr_){
// FIXME: to my knowledge there is no way to ask Qt to reload the fonts.
// Should we call QApplication::setFont() to override the font?
// This does not work with QSS, though.
//
// After reading the source code of Qt, I think the right method to call
// here is QApplicationPrivate::setSystemFont(). However, this is an
// internal API and should not be used. Let's call QApplication::setFont()
// instead since it approximately does the same thing.
// Internally, QApplication will emit QEvent::ApplicationFontChange so
// all of the widgets will update their fonts.
// FIXME: should we call the internal API: QApplicationPrivate::setFont() instead?
// QGtkStyle does this internally.
fixedFont_.fromString(fixedFontStr_); // FIXME: how to set this to the app?
if(font_.fromString(fontStr_))
QApplication::setFont(font_);
}
// emit a ThemeChange event to all widgets
Q_FOREACH(QWidget* widget, QApplication::allWidgets()) {
// Qt5 added a QEvent::ThemeChange event.
QEvent event(QEvent::ThemeChange);
QApplication::sendEvent(widget, &event);
}
}
bool LXQtPlatformTheme::usePlatformNativeDialog(DialogType type) const {
return false;
}
#if 0
QPlatformDialogHelper *LXQtPlatformTheme::createPlatformDialogHelper(DialogType type) const {
return 0;
}
#endif
const QPalette *LXQtPlatformTheme::palette(Palette type) const {
if (type == QPlatformTheme::SystemPalette)
// the default constructor uses the default palette
return new QPalette;
return QPlatformTheme::palette(type);
}
const QFont *LXQtPlatformTheme::font(Font type) const {
if(type == SystemFont && !fontStr_.isEmpty()) {
// NOTE: for some reason, this is not called by Qt when program startup.
// So we do QApplication::setFont() manually.
return &font_;
}
else if(type == FixedFont && !fixedFontStr_.isEmpty()) {
return &fixedFont_;
}
return QPlatformTheme::font(type);
}
QVariant LXQtPlatformTheme::themeHint(ThemeHint hint) const {
switch (hint) {
case CursorFlashTime:
return cursorFlashTime_;
case KeyboardInputInterval:
break;
case MouseDoubleClickInterval:
return doubleClickInterval_;
case StartDragDistance:
break;
case StartDragTime:
break;
case KeyboardAutoRepeatRate:
break;
case PasswordMaskDelay:
break;
case StartDragVelocity:
break;
case TextCursorWidth:
break;
case DropShadow:
return QVariant(true);
case MaximumScrollBarDragDistance:
break;
case ToolButtonStyle:
return QVariant(toolButtonStyle_);
case ToolBarIconSize:
break;
case ItemViewActivateItemOnSingleClick:
return QVariant(singleClickActivate_);
case SystemIconThemeName:
return iconTheme_;
case SystemIconFallbackThemeName:
return "hicolor";
case IconThemeSearchPaths:
return xdgIconThemePaths();
case StyleNames:
return QStringList() << style_;
case WindowAutoPlacement:
break;
case DialogButtonBoxLayout:
break;
case DialogButtonBoxButtonsHaveIcons:
return QVariant(true);
case UseFullScreenForPopupMenu:
break;
case KeyboardScheme:
return QVariant(X11KeyboardScheme);
case UiEffects:
break;
case SpellCheckUnderlineStyle:
break;
case TabAllWidgets:
break;
case IconPixmapSizes:
break;
case PasswordMaskCharacter:
break;
case DialogSnapToDefaultButton:
break;
case ContextMenuOnMouseRelease:
break;
case MousePressAndHoldInterval:
break;
case MouseDoubleClickDistance:
break;
default:
break;
}
return QPlatformTheme::themeHint(hint);
}
// Helper to return the icon theme paths from XDG.
QStringList LXQtPlatformTheme::xdgIconThemePaths() const
{
QStringList paths;
QStringList xdgDirs;
// Add home directory first in search path
const QFileInfo homeIconDir(QDir::homePath() + QStringLiteral("/.icons"));
if (homeIconDir.isDir())
paths.prepend(homeIconDir.absoluteFilePath());
QString xdgDataHome = QFile::decodeName(qgetenv("XDG_DATA_HOME"));
if (xdgDataHome.isEmpty())
xdgDataHome = QDir::homePath() + QLatin1String("/.local/share");
xdgDirs.append(xdgDataHome);
QString xdgDataDirs = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
if (xdgDataDirs.isEmpty())
xdgDataDirs = QLatin1String("/usr/local/share/:/usr/share/");
xdgDirs.append(xdgDataDirs);
foreach (const QString &s, xdgDirs) {
foreach (const QString &xdgDir, s.split(QLatin1Char(':'))) {
const QFileInfo xdgIconsDir(xdgDir + QStringLiteral("/icons"));
if (xdgIconsDir.isDir())
paths.append(xdgIconsDir.absoluteFilePath());
}
}
return paths;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Library: TubeTK
Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
All rights reserved.
Licensed under the Apache License, Version 2.0 ( the "License" );
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkSpatialObjectReader.h"
#include "itkGroupSpatialObject.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkMersenneTwisterRandomVariateGenerator.h"
#include "../itkRidgeExtractor.h"
int itkRidgeExtractorTest2( int argc, char * argv[] )
{
if( argc != 3 )
{
std::cout
<< "itkRidgeExtractorTest <inputImage> <vessel.tre>"
<< std::endl;
return EXIT_FAILURE;
}
typedef itk::Image<float, 3> ImageType;
typedef itk::ImageFileReader< ImageType > ImageReaderType;
ImageReaderType::Pointer imReader = ImageReaderType::New();
imReader->SetFileName( argv[1] );
imReader->Update();
ImageType::Pointer im = imReader->GetOutput();
typedef itk::RidgeExtractor<ImageType> RidgeOpType;
RidgeOpType::Pointer ridgeOp = RidgeOpType::New();
ridgeOp->SetInputImage( im );
ridgeOp->SetStepX( 0.75 );
ridgeOp->SetScale( 2.0 );
ridgeOp->SetExtent( 3.0 );
ridgeOp->SetDynamicScale( true );
typedef itk::SpatialObjectReader<> ReaderType;
typedef itk::SpatialObject<>::ChildrenListType ObjectListType;
typedef itk::GroupSpatialObject<> GroupType;
typedef itk::VesselTubeSpatialObject<> TubeType;
typedef TubeType::PointListType PointListType;
typedef TubeType::PointType PointType;
typedef TubeType::TubePointType TubePointType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[2] );
reader->Update();
GroupType::Pointer group = reader->GetGroup();
std::cout << "Number of children = " << group->GetNumberOfChildren()
<< std::endl;
char tubeName[17];
strcpy( tubeName, "Tube" );
ObjectListType * tubeList = group->GetChildren( -1, tubeName );
unsigned int numTubes = tubeList->size();
std::cout << "Number of tubes = " << numTubes << std::endl;
typedef itk::Statistics::MersenneTwisterRandomVariateGenerator
RandGenType;
RandGenType::Pointer rndGen = RandGenType::New();
rndGen->Initialize(); // set seed here
int failures = 0;
for( unsigned int mcRun=0; mcRun<10; mcRun++ )
{
std::cout << std::endl;
std::cout << std::endl;
std::cout << "***** Beginning tube test ***** " << std::endl;
std::cout << "***** Beginning tube test ***** " << std::endl;
unsigned int rndTubeNum = rndGen->GetUniformVariate( 0, 1 ) * numTubes;
if( rndTubeNum > numTubes-1 )
{
rndTubeNum = numTubes-1;
}
ObjectListType::iterator tubeIter = tubeList->begin();
for( unsigned int i=0; i<rndTubeNum; i++ )
{
++tubeIter;
}
TubeType::Pointer tube = static_cast< TubeType * >(
tubeIter->GetPointer() );
std::cout << "Test tube = " << rndTubeNum << std::endl;
PointListType tubePointList = tube->GetPoints();
unsigned int numPoints = tubePointList.size();
unsigned int rndPointNum = rndGen->GetUniformVariate( 0, 1 )
* numPoints;
if( rndPointNum > numPoints-1 )
{
rndPointNum = numPoints-1;
}
PointListType::iterator pntIter = tubePointList.begin();
for( unsigned int i=0; i<rndPointNum; i++ )
{
++pntIter;
}
TubePointType * pnt = static_cast< TubePointType * >(&(*pntIter));
std::cout << "Test point = " << rndPointNum << std::endl;
RidgeOpType::ContinuousIndexType x0;
for( unsigned int i=0; i<ImageType::ImageDimension; i++)
{
x0[i] = pnt->GetPosition()[i];
}
std::cout << "Test index = " << x0 << std::endl;
RidgeOpType::ContinuousIndexType x1 = x0;
ridgeOp->SetDebug( true );
if( !ridgeOp->LocalRidge( x1 ) )
{
std::cerr << "Local ridge test failed. No ridge found." << std::endl;
std::cerr << " Source = " << x0 << std::endl;
std::cerr << " Result = " << x1 << std::endl;
++failures;
continue;
}
double diff = 0;
for( unsigned int i=0; i<ImageType::ImageDimension; i++)
{
double tf = x0[i]-x1[i];
diff += tf * tf;
}
diff = vcl_sqrt( diff );
if( diff > 2 )
{
std::cerr << "Local ridge test failed. Local ridge too far."
<< std::endl;
std::cerr << " Source = " << x0 << std::endl;
std::cerr << " Result = " << x1 << std::endl;
++failures;
continue;
}
std::cout << "Local ridge discovery a success!" << std::endl;
std::cout << std::endl;
std::cout << "***** Beginning tube extraction ***** " << std::endl;
TubeType::Pointer xTube = ridgeOp->Extract( x1, mcRun );
std::cout << "***** Ending tube extraction ***** " << std::endl;
if( xTube.IsNull() )
{
std::cerr << "Ridge extraction failed" << std::endl;
++failures;
continue;
}
TubeType::Pointer xTube2;
xTube2 = ridgeOp->Extract( x1, 101 );
if( xTube2.IsNotNull() )
{
std::cerr << "Ridge extracted twice - test failed" << std::endl;
++failures;
continue;
}
if( !ridgeOp->DeleteTube< RidgeOpType::MaskType >( xTube ) )
{
std::cerr << "Delete tube failed" << std::endl;
++failures;
continue;
}
xTube = ridgeOp->Extract( x1, 101 );
if( xTube.IsNull() )
{
std::cerr << "Ridge extraction after delete failed." << std::endl;
++failures;
continue;
}
if( !ridgeOp->DeleteTube< RidgeOpType::MaskType >( xTube ) )
{
std::cerr << "Second delete tube failed" << std::endl;
++failures;
continue;
}
if( xTube.IsNull() )
{
std::cerr << "Ridge extraction failed" << std::endl;
++failures;
continue;
}
ridgeOp->SmoothTubeX( xTube, 5 );
if( !ridgeOp->AddTube< RidgeOpType::MaskType >( xTube ) )
{
std::cerr << "Add tube failed" << std::endl;
++failures;
continue;
}
if( !ridgeOp->DeleteTube< RidgeOpType::MaskType >( xTube ) )
{
std::cerr << "Third delete tube failed" << std::endl;
++failures;
continue;
}
}
RidgeOpType::MaskType::Pointer mask = ridgeOp->GetDataMask();
itk::ImageRegionIterator< RidgeOpType::MaskType > maskIt( mask,
mask->GetLargestPossibleRegion() );
while( !maskIt.IsAtEnd() )
{
if( maskIt.Get() != 0 )
{
std::cout << "Final mask not blank." << std::endl;
std::cout << "Number of failures = " << failures << std::endl;
return EXIT_FAILURE;
}
}
std::cout << "Number of failures = " << failures << std::endl;
if( failures > 10 )
{
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>BUG: Missing increment in loop caused inifinite loop.<commit_after>/*=========================================================================
Library: TubeTK
Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
All rights reserved.
Licensed under the Apache License, Version 2.0 ( the "License" );
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkSpatialObjectReader.h"
#include "itkGroupSpatialObject.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkMersenneTwisterRandomVariateGenerator.h"
#include "../itkRidgeExtractor.h"
int itkRidgeExtractorTest2( int argc, char * argv[] )
{
if( argc != 3 )
{
std::cout
<< "itkRidgeExtractorTest <inputImage> <vessel.tre>"
<< std::endl;
return EXIT_FAILURE;
}
typedef itk::Image<float, 3> ImageType;
typedef itk::ImageFileReader< ImageType > ImageReaderType;
ImageReaderType::Pointer imReader = ImageReaderType::New();
imReader->SetFileName( argv[1] );
imReader->Update();
ImageType::Pointer im = imReader->GetOutput();
typedef itk::RidgeExtractor<ImageType> RidgeOpType;
RidgeOpType::Pointer ridgeOp = RidgeOpType::New();
ridgeOp->SetInputImage( im );
ridgeOp->SetStepX( 0.75 );
ridgeOp->SetScale( 2.0 );
ridgeOp->SetExtent( 3.0 );
ridgeOp->SetDynamicScale( true );
typedef itk::SpatialObjectReader<> ReaderType;
typedef itk::SpatialObject<>::ChildrenListType ObjectListType;
typedef itk::GroupSpatialObject<> GroupType;
typedef itk::VesselTubeSpatialObject<> TubeType;
typedef TubeType::PointListType PointListType;
typedef TubeType::PointType PointType;
typedef TubeType::TubePointType TubePointType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[2] );
reader->Update();
GroupType::Pointer group = reader->GetGroup();
std::cout << "Number of children = " << group->GetNumberOfChildren()
<< std::endl;
char tubeName[17];
strcpy( tubeName, "Tube" );
ObjectListType * tubeList = group->GetChildren( -1, tubeName );
unsigned int numTubes = tubeList->size();
std::cout << "Number of tubes = " << numTubes << std::endl;
typedef itk::Statistics::MersenneTwisterRandomVariateGenerator
RandGenType;
RandGenType::Pointer rndGen = RandGenType::New();
rndGen->Initialize(); // set seed here
int failures = 0;
for( unsigned int mcRun=0; mcRun<10; mcRun++ )
{
std::cout << std::endl;
std::cout << std::endl;
std::cout << "***** Beginning tube test ***** " << std::endl;
std::cout << "***** Beginning tube test ***** " << std::endl;
unsigned int rndTubeNum = rndGen->GetUniformVariate( 0, 1 ) * numTubes;
if( rndTubeNum > numTubes-1 )
{
rndTubeNum = numTubes-1;
}
ObjectListType::iterator tubeIter = tubeList->begin();
for( unsigned int i=0; i<rndTubeNum; i++ )
{
++tubeIter;
}
TubeType::Pointer tube = static_cast< TubeType * >(
tubeIter->GetPointer() );
std::cout << "Test tube = " << rndTubeNum << std::endl;
PointListType tubePointList = tube->GetPoints();
unsigned int numPoints = tubePointList.size();
unsigned int rndPointNum = rndGen->GetUniformVariate( 0, 1 )
* numPoints;
if( rndPointNum > numPoints-1 )
{
rndPointNum = numPoints-1;
}
PointListType::iterator pntIter = tubePointList.begin();
for( unsigned int i=0; i<rndPointNum; i++ )
{
++pntIter;
}
TubePointType * pnt = static_cast< TubePointType * >(&(*pntIter));
std::cout << "Test point = " << rndPointNum << std::endl;
RidgeOpType::ContinuousIndexType x0;
for( unsigned int i=0; i<ImageType::ImageDimension; i++)
{
x0[i] = pnt->GetPosition()[i];
}
std::cout << "Test index = " << x0 << std::endl;
RidgeOpType::ContinuousIndexType x1 = x0;
ridgeOp->SetDebug( true );
if( !ridgeOp->LocalRidge( x1 ) )
{
std::cerr << "Local ridge test failed. No ridge found." << std::endl;
std::cerr << " Source = " << x0 << std::endl;
std::cerr << " Result = " << x1 << std::endl;
++failures;
continue;
}
double diff = 0;
for( unsigned int i=0; i<ImageType::ImageDimension; i++)
{
double tf = x0[i]-x1[i];
diff += tf * tf;
}
diff = vcl_sqrt( diff );
if( diff > 2 )
{
std::cerr << "Local ridge test failed. Local ridge too far."
<< std::endl;
std::cerr << " Source = " << x0 << std::endl;
std::cerr << " Result = " << x1 << std::endl;
++failures;
continue;
}
std::cout << "Local ridge discovery a success!" << std::endl;
std::cout << std::endl;
std::cout << "***** Beginning tube extraction ***** " << std::endl;
TubeType::Pointer xTube = ridgeOp->Extract( x1, mcRun );
std::cout << "***** Ending tube extraction ***** " << std::endl;
if( xTube.IsNull() )
{
std::cerr << "Ridge extraction failed" << std::endl;
++failures;
continue;
}
TubeType::Pointer xTube2;
xTube2 = ridgeOp->Extract( x1, 101 );
if( xTube2.IsNotNull() )
{
std::cerr << "Ridge extracted twice - test failed" << std::endl;
++failures;
continue;
}
if( !ridgeOp->DeleteTube< RidgeOpType::MaskType >( xTube ) )
{
std::cerr << "Delete tube failed" << std::endl;
++failures;
continue;
}
xTube = ridgeOp->Extract( x1, 101 );
if( xTube.IsNull() )
{
std::cerr << "Ridge extraction after delete failed." << std::endl;
++failures;
continue;
}
if( !ridgeOp->DeleteTube< RidgeOpType::MaskType >( xTube ) )
{
std::cerr << "Second delete tube failed" << std::endl;
++failures;
continue;
}
if( xTube.IsNull() )
{
std::cerr << "Ridge extraction failed" << std::endl;
++failures;
continue;
}
ridgeOp->SmoothTubeX( xTube, 5 );
if( !ridgeOp->AddTube< RidgeOpType::MaskType >( xTube ) )
{
std::cerr << "Add tube failed" << std::endl;
++failures;
continue;
}
if( !ridgeOp->DeleteTube< RidgeOpType::MaskType >( xTube ) )
{
std::cerr << "Third delete tube failed" << std::endl;
++failures;
continue;
}
}
RidgeOpType::MaskType::Pointer mask = ridgeOp->GetDataMask();
itk::ImageRegionIterator< RidgeOpType::MaskType > maskIt( mask,
mask->GetLargestPossibleRegion() );
while( !maskIt.IsAtEnd() )
{
if( maskIt.Get() != 0 )
{
std::cout << "Final mask not blank." << std::endl;
std::cout << "Number of failures = " << failures << std::endl;
return EXIT_FAILURE;
}
++maskIt;
}
std::cout << "Number of failures = " << failures << std::endl;
if( failures > 10 )
{
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>// Copyright © 2010-2015 The CefSharp Project. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#pragma once
#include "Stdafx.h"
#include "CefBrowserWrapper.h"
#include "CefAppUnmanagedWrapper.h"
#include "JavascriptRootObjectWrapper.h"
#include "Serialization\V8Serialization.h"
#include "Serialization\JsObjectsSerialization.h"
#include "Async/JavascriptAsyncMethodCallback.h"
#include "..\CefSharp.Core\Internals\Messaging\Messages.h"
#include "..\CefSharp.Core\Internals\Serialization\Primitives.h"
using namespace System::Diagnostics;
using namespace System::Collections::Generic;
using namespace CefSharp::Internals::Messaging;
using namespace CefSharp::Internals::Serialization;
namespace CefSharp
{
const CefString CefAppUnmanagedWrapper::kPromiseCreatorFunction = "cefsharp_CreatePromise";
const CefString CefAppUnmanagedWrapper::kPromiseCreatorScript = ""
"function cefsharp_CreatePromise() {"
" var object = {};"
" var promise = new Promise(function(resolve, reject) {"
" object.resolve = resolve;object.reject = reject;"
" });"
" return{ p: promise, res : object.resolve, rej: object.reject};"
"}";
CefRefPtr<CefRenderProcessHandler> CefAppUnmanagedWrapper::GetRenderProcessHandler()
{
return this;
};
// CefRenderProcessHandler
void CefAppUnmanagedWrapper::OnBrowserCreated(CefRefPtr<CefBrowser> browser)
{
auto wrapper = gcnew CefBrowserWrapper(browser);
_onBrowserCreated->Invoke(wrapper);
//Multiple CefBrowserWrappers created when opening popups
_browserWrappers->TryAdd(browser->GetIdentifier(), wrapper);
}
void CefAppUnmanagedWrapper::OnBrowserDestroyed(CefRefPtr<CefBrowser> browser)
{
CefBrowserWrapper^ wrapper;
if (_browserWrappers->TryRemove(browser->GetIdentifier(), wrapper))
{
_onBrowserDestroyed->Invoke(wrapper);
delete wrapper;
}
};
void CefAppUnmanagedWrapper::OnContextCreated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context)
{
auto browserWrapper = FindBrowserWrapper(browser->GetIdentifier(), true);
auto rootObjectWrappers = browserWrapper->JavascriptRootObjectWrappers;
auto frameId = frame->GetIdentifier();
if (rootObjectWrappers->ContainsKey(frameId))
{
LOG(WARNING) << "A context has been created for the same browser / frame without context released called previously";
}
else
{
auto rootObject = gcnew JavascriptRootObjectWrapper(browser->GetIdentifier(), browserWrapper->BrowserProcess);
if (!Object::ReferenceEquals(_javascriptRootObject, nullptr) || !Object::ReferenceEquals(_javascriptAsyncRootObject, nullptr))
{
rootObject->Bind(_javascriptRootObject, _javascriptAsyncRootObject, context->GetGlobal());
}
rootObjectWrappers->TryAdd(frameId, rootObject);
}
};
void CefAppUnmanagedWrapper::OnContextReleased(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context)
{
auto browserWrapper = FindBrowserWrapper(browser->GetIdentifier(), true);
auto rootObjectWrappers = browserWrapper->JavascriptRootObjectWrappers;
JavascriptRootObjectWrapper^ wrapper;
if (rootObjectWrappers->TryRemove(frame->GetIdentifier(), wrapper))
{
delete wrapper;
}
};
CefBrowserWrapper^ CefAppUnmanagedWrapper::FindBrowserWrapper(int browserId, bool mustExist)
{
CefBrowserWrapper^ wrapper = nullptr;
_browserWrappers->TryGetValue(browserId, wrapper);
if (mustExist && wrapper == nullptr)
{
throw gcnew InvalidOperationException(String::Format("Failed to identify BrowserWrapper in OnContextCreated. : {0}", browserId));
}
return wrapper;
}
bool CefAppUnmanagedWrapper::OnProcessMessageReceived(CefRefPtr<CefBrowser> browser, CefProcessId sourceProcessId, CefRefPtr<CefProcessMessage> message)
{
auto handled = false;
auto name = message->GetName();
auto argList = message->GetArgumentList();
auto browserWrapper = FindBrowserWrapper(browser->GetIdentifier(), false);
//Error handling for missing/closed browser
if (browserWrapper == nullptr)
{
if (name == kJavascriptCallbackDestroyRequest ||
name == kJavascriptRootObjectRequest ||
name == kJavascriptAsyncMethodCallResponse)
{
//If we can't find the browser wrapper then we'll just
//ignore this as it's likely already been disposed of
return true;
}
CefString responseName;
if (name == kEvaluateJavascriptRequest)
{
responseName = kEvaluateJavascriptResponse;
}
else if (name == kJavascriptCallbackRequest)
{
responseName = kJavascriptCallbackResponse;
}
else
{
//TODO: Should be throw an exception here? It's likely that only a CefSharp developer would see this
// when they added a new message and havn't yet implemented the render process functionality.
throw gcnew Exception("Unsupported message type");
}
auto callbackId = GetInt64(argList, 1);
auto response = CefProcessMessage::Create(responseName);
auto responseArgList = response->GetArgumentList();
auto errorMessage = String::Format("Request BrowserId : {0} not found it's likely the browser is already closed", browser->GetIdentifier());
//success: false
responseArgList->SetBool(0, false);
SetInt64(callbackId, responseArgList, 1);
responseArgList->SetString(2, StringUtils::ToNative(errorMessage));
browser->SendProcessMessage(sourceProcessId, response);
return true;
}
//these messages are roughly handled the same way
if (name == kEvaluateJavascriptRequest || name == kJavascriptCallbackRequest)
{
bool success = false;
CefRefPtr<CefV8Value> result;
CefString errorMessage;
CefRefPtr<CefProcessMessage> response;
if (name == kEvaluateJavascriptRequest)
{
response = CefProcessMessage::Create(kEvaluateJavascriptResponse);
}
else
{
response = CefProcessMessage::Create(kJavascriptCallbackResponse);
}
//both messages have the frameId stored at 0 and callbackId stored at index 1
auto frameId = GetInt64(argList, 0);
int64 callbackId = GetInt64(argList, 1);
JavascriptRootObjectWrapper^ rootObjectWrapper;
browserWrapper->JavascriptRootObjectWrappers->TryGetValue(frameId, rootObjectWrapper);
auto callbackRegistry = rootObjectWrapper == nullptr ? nullptr : rootObjectWrapper->CallbackRegistry;
if (callbackRegistry == nullptr)
{
errorMessage = StringUtils::ToNative("Frame " + frameId + " is no longer available, most likely the Frame has been Disposed.");
}
else if (name == kEvaluateJavascriptRequest)
{
auto script = argList->GetString(2);
auto frame = browser->GetFrame(frameId);
if (frame.get())
{
auto context = frame->GetV8Context();
if (context.get() && context->Enter())
{
try
{
CefRefPtr<CefV8Exception> exception;
success = context->Eval(script, result, exception);
//we need to do this here to be able to store the v8context
if (success)
{
auto responseArgList = response->GetArgumentList();
SerializeV8Object(result, responseArgList, 2, callbackRegistry);
}
else
{
errorMessage = exception->GetMessage();
}
}
finally
{
context->Exit();
}
}
else
{
errorMessage = "Unable to Enter Context";
}
}
else
{
errorMessage = StringUtils::ToNative("Frame " + frameId + " is no longer available, most likely the Frame has been Disposed or Removed.");
}
}
else
{
auto jsCallbackId = GetInt64(argList, 2);
auto parameterList = argList->GetList(3);
CefV8ValueList params;
for (CefV8ValueList::size_type i = 0; i < parameterList->GetSize(); i++)
{
params.push_back(DeserializeV8Object(parameterList, static_cast<int>(i)));
}
auto callbackWrapper = callbackRegistry->FindWrapper(jsCallbackId);
if (callbackWrapper == nullptr)
{
errorMessage = "Unable to find callbackWrapper";
}
else
{
auto context = callbackWrapper->GetContext();
auto value = callbackWrapper->GetValue();
if (context.get() && context->Enter())
{
try
{
result = value->ExecuteFunction(nullptr, params);
success = result.get() != nullptr;
//we need to do this here to be able to store the v8context
if (success)
{
auto responseArgList = response->GetArgumentList();
SerializeV8Object(result, responseArgList, 2, callbackRegistry);
}
else
{
auto exception = value->GetException();
if (exception.get())
{
errorMessage = exception->GetMessage();
}
}
}
finally
{
context->Exit();
}
}
else
{
errorMessage = "Unable to Enter Context";
}
}
}
auto responseArgList = response->GetArgumentList();
responseArgList->SetBool(0, success);
SetInt64(callbackId, responseArgList, 1);
if (!success)
{
responseArgList->SetString(2, errorMessage);
}
browser->SendProcessMessage(sourceProcessId, response);
handled = true;
}
else if (name == kJavascriptCallbackDestroyRequest)
{
auto jsCallbackId = GetInt64(argList, 0);
auto frameId = GetInt64(argList, 1);
JavascriptRootObjectWrapper^ rootObjectWrapper;
browserWrapper->JavascriptRootObjectWrappers->TryGetValue(frameId, rootObjectWrapper);
if (rootObjectWrapper != nullptr && rootObjectWrapper->CallbackRegistry != nullptr)
{
rootObjectWrapper->CallbackRegistry->Deregister(jsCallbackId);
}
handled = true;
}
else if (name == kJavascriptRootObjectRequest)
{
_javascriptAsyncRootObject = DeserializeJsRootObject(argList, 0);
_javascriptRootObject = DeserializeJsRootObject(argList, 1);
handled = true;
}
else if (name == kJavascriptAsyncMethodCallResponse)
{
auto frameId = GetInt64(argList, 0);
auto callbackId = GetInt64(argList, 1);
JavascriptRootObjectWrapper^ rootObjectWrapper;
browserWrapper->JavascriptRootObjectWrappers->TryGetValue(frameId, rootObjectWrapper);
if (rootObjectWrapper != nullptr)
{
JavascriptAsyncMethodCallback^ callback;
if (rootObjectWrapper->TryGetAndRemoveMethodCallback(callbackId, callback))
{
auto success = argList->GetBool(2);
if (success)
{
callback->Success(DeserializeV8Object(argList, 3));
}
else
{
callback->Fail(argList->GetString(3));
}
//dispose
delete callback;
}
}
handled = true;
}
return handled;
};
void CefAppUnmanagedWrapper::OnRenderThreadCreated(CefRefPtr<CefListValue> extraInfo)
{
auto extensionList = extraInfo->GetList(0);
for (size_t i = 0; i < extensionList->GetSize(); i++)
{
auto extension = extensionList->GetList(i);
auto ext = gcnew CefExtension(StringUtils::ToClr(extension->GetString(0)), StringUtils::ToClr(extension->GetString(1)));
_extensions->Add(ext);
}
}
void CefAppUnmanagedWrapper::OnWebKitInitialized()
{
//we need to do this because the builtin Promise object is not accesible
CefRegisterExtension("cefsharp/promisecreator", kPromiseCreatorScript, NULL);
for each(CefExtension^ extension in _extensions->AsReadOnly())
{
//only support extensions without handlers now
CefRegisterExtension(StringUtils::ToNative(extension->Name), StringUtils::ToNative(extension->JavascriptCode), NULL);
}
}
void CefAppUnmanagedWrapper::OnRegisterCustomSchemes(CefRefPtr<CefSchemeRegistrar> registrar)
{
for each (CefCustomScheme^ scheme in _schemes->AsReadOnly())
{
registrar->AddCustomScheme(StringUtils::ToNative(scheme->SchemeName), scheme->IsStandard, scheme->IsLocal, scheme->IsDisplayIsolated);
}
}
}<commit_msg>do not create two objects in the promis creaton function<commit_after>// Copyright © 2010-2015 The CefSharp Project. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#pragma once
#include "Stdafx.h"
#include "CefBrowserWrapper.h"
#include "CefAppUnmanagedWrapper.h"
#include "JavascriptRootObjectWrapper.h"
#include "Serialization\V8Serialization.h"
#include "Serialization\JsObjectsSerialization.h"
#include "Async/JavascriptAsyncMethodCallback.h"
#include "..\CefSharp.Core\Internals\Messaging\Messages.h"
#include "..\CefSharp.Core\Internals\Serialization\Primitives.h"
using namespace System::Diagnostics;
using namespace System::Collections::Generic;
using namespace CefSharp::Internals::Messaging;
using namespace CefSharp::Internals::Serialization;
namespace CefSharp
{
const CefString CefAppUnmanagedWrapper::kPromiseCreatorFunction = "cefsharp_CreatePromise";
const CefString CefAppUnmanagedWrapper::kPromiseCreatorScript = ""
"function cefsharp_CreatePromise() {"
" var result = {};"
" var promise = new Promise(function(resolve, reject) {"
" result.res = resolve; result.rej = reject;"
" });"
" result.p = promise;"
" return result;"
"}";
CefRefPtr<CefRenderProcessHandler> CefAppUnmanagedWrapper::GetRenderProcessHandler()
{
return this;
};
// CefRenderProcessHandler
void CefAppUnmanagedWrapper::OnBrowserCreated(CefRefPtr<CefBrowser> browser)
{
auto wrapper = gcnew CefBrowserWrapper(browser);
_onBrowserCreated->Invoke(wrapper);
//Multiple CefBrowserWrappers created when opening popups
_browserWrappers->TryAdd(browser->GetIdentifier(), wrapper);
}
void CefAppUnmanagedWrapper::OnBrowserDestroyed(CefRefPtr<CefBrowser> browser)
{
CefBrowserWrapper^ wrapper;
if (_browserWrappers->TryRemove(browser->GetIdentifier(), wrapper))
{
_onBrowserDestroyed->Invoke(wrapper);
delete wrapper;
}
};
void CefAppUnmanagedWrapper::OnContextCreated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context)
{
auto browserWrapper = FindBrowserWrapper(browser->GetIdentifier(), true);
auto rootObjectWrappers = browserWrapper->JavascriptRootObjectWrappers;
auto frameId = frame->GetIdentifier();
if (rootObjectWrappers->ContainsKey(frameId))
{
LOG(WARNING) << "A context has been created for the same browser / frame without context released called previously";
}
else
{
auto rootObject = gcnew JavascriptRootObjectWrapper(browser->GetIdentifier(), browserWrapper->BrowserProcess);
if (!Object::ReferenceEquals(_javascriptRootObject, nullptr) || !Object::ReferenceEquals(_javascriptAsyncRootObject, nullptr))
{
rootObject->Bind(_javascriptRootObject, _javascriptAsyncRootObject, context->GetGlobal());
}
rootObjectWrappers->TryAdd(frameId, rootObject);
}
};
void CefAppUnmanagedWrapper::OnContextReleased(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context)
{
auto browserWrapper = FindBrowserWrapper(browser->GetIdentifier(), true);
auto rootObjectWrappers = browserWrapper->JavascriptRootObjectWrappers;
JavascriptRootObjectWrapper^ wrapper;
if (rootObjectWrappers->TryRemove(frame->GetIdentifier(), wrapper))
{
delete wrapper;
}
};
CefBrowserWrapper^ CefAppUnmanagedWrapper::FindBrowserWrapper(int browserId, bool mustExist)
{
CefBrowserWrapper^ wrapper = nullptr;
_browserWrappers->TryGetValue(browserId, wrapper);
if (mustExist && wrapper == nullptr)
{
throw gcnew InvalidOperationException(String::Format("Failed to identify BrowserWrapper in OnContextCreated. : {0}", browserId));
}
return wrapper;
}
bool CefAppUnmanagedWrapper::OnProcessMessageReceived(CefRefPtr<CefBrowser> browser, CefProcessId sourceProcessId, CefRefPtr<CefProcessMessage> message)
{
auto handled = false;
auto name = message->GetName();
auto argList = message->GetArgumentList();
auto browserWrapper = FindBrowserWrapper(browser->GetIdentifier(), false);
//Error handling for missing/closed browser
if (browserWrapper == nullptr)
{
if (name == kJavascriptCallbackDestroyRequest ||
name == kJavascriptRootObjectRequest ||
name == kJavascriptAsyncMethodCallResponse)
{
//If we can't find the browser wrapper then we'll just
//ignore this as it's likely already been disposed of
return true;
}
CefString responseName;
if (name == kEvaluateJavascriptRequest)
{
responseName = kEvaluateJavascriptResponse;
}
else if (name == kJavascriptCallbackRequest)
{
responseName = kJavascriptCallbackResponse;
}
else
{
//TODO: Should be throw an exception here? It's likely that only a CefSharp developer would see this
// when they added a new message and havn't yet implemented the render process functionality.
throw gcnew Exception("Unsupported message type");
}
auto callbackId = GetInt64(argList, 1);
auto response = CefProcessMessage::Create(responseName);
auto responseArgList = response->GetArgumentList();
auto errorMessage = String::Format("Request BrowserId : {0} not found it's likely the browser is already closed", browser->GetIdentifier());
//success: false
responseArgList->SetBool(0, false);
SetInt64(callbackId, responseArgList, 1);
responseArgList->SetString(2, StringUtils::ToNative(errorMessage));
browser->SendProcessMessage(sourceProcessId, response);
return true;
}
//these messages are roughly handled the same way
if (name == kEvaluateJavascriptRequest || name == kJavascriptCallbackRequest)
{
bool success = false;
CefRefPtr<CefV8Value> result;
CefString errorMessage;
CefRefPtr<CefProcessMessage> response;
if (name == kEvaluateJavascriptRequest)
{
response = CefProcessMessage::Create(kEvaluateJavascriptResponse);
}
else
{
response = CefProcessMessage::Create(kJavascriptCallbackResponse);
}
//both messages have the frameId stored at 0 and callbackId stored at index 1
auto frameId = GetInt64(argList, 0);
int64 callbackId = GetInt64(argList, 1);
JavascriptRootObjectWrapper^ rootObjectWrapper;
browserWrapper->JavascriptRootObjectWrappers->TryGetValue(frameId, rootObjectWrapper);
auto callbackRegistry = rootObjectWrapper == nullptr ? nullptr : rootObjectWrapper->CallbackRegistry;
if (callbackRegistry == nullptr)
{
errorMessage = StringUtils::ToNative("Frame " + frameId + " is no longer available, most likely the Frame has been Disposed.");
}
else if (name == kEvaluateJavascriptRequest)
{
auto script = argList->GetString(2);
auto frame = browser->GetFrame(frameId);
if (frame.get())
{
auto context = frame->GetV8Context();
if (context.get() && context->Enter())
{
try
{
CefRefPtr<CefV8Exception> exception;
success = context->Eval(script, result, exception);
//we need to do this here to be able to store the v8context
if (success)
{
auto responseArgList = response->GetArgumentList();
SerializeV8Object(result, responseArgList, 2, callbackRegistry);
}
else
{
errorMessage = exception->GetMessage();
}
}
finally
{
context->Exit();
}
}
else
{
errorMessage = "Unable to Enter Context";
}
}
else
{
errorMessage = StringUtils::ToNative("Frame " + frameId + " is no longer available, most likely the Frame has been Disposed or Removed.");
}
}
else
{
auto jsCallbackId = GetInt64(argList, 2);
auto parameterList = argList->GetList(3);
CefV8ValueList params;
for (CefV8ValueList::size_type i = 0; i < parameterList->GetSize(); i++)
{
params.push_back(DeserializeV8Object(parameterList, static_cast<int>(i)));
}
auto callbackWrapper = callbackRegistry->FindWrapper(jsCallbackId);
if (callbackWrapper == nullptr)
{
errorMessage = "Unable to find callbackWrapper";
}
else
{
auto context = callbackWrapper->GetContext();
auto value = callbackWrapper->GetValue();
if (context.get() && context->Enter())
{
try
{
result = value->ExecuteFunction(nullptr, params);
success = result.get() != nullptr;
//we need to do this here to be able to store the v8context
if (success)
{
auto responseArgList = response->GetArgumentList();
SerializeV8Object(result, responseArgList, 2, callbackRegistry);
}
else
{
auto exception = value->GetException();
if (exception.get())
{
errorMessage = exception->GetMessage();
}
}
}
finally
{
context->Exit();
}
}
else
{
errorMessage = "Unable to Enter Context";
}
}
}
auto responseArgList = response->GetArgumentList();
responseArgList->SetBool(0, success);
SetInt64(callbackId, responseArgList, 1);
if (!success)
{
responseArgList->SetString(2, errorMessage);
}
browser->SendProcessMessage(sourceProcessId, response);
handled = true;
}
else if (name == kJavascriptCallbackDestroyRequest)
{
auto jsCallbackId = GetInt64(argList, 0);
auto frameId = GetInt64(argList, 1);
JavascriptRootObjectWrapper^ rootObjectWrapper;
browserWrapper->JavascriptRootObjectWrappers->TryGetValue(frameId, rootObjectWrapper);
if (rootObjectWrapper != nullptr && rootObjectWrapper->CallbackRegistry != nullptr)
{
rootObjectWrapper->CallbackRegistry->Deregister(jsCallbackId);
}
handled = true;
}
else if (name == kJavascriptRootObjectRequest)
{
_javascriptAsyncRootObject = DeserializeJsRootObject(argList, 0);
_javascriptRootObject = DeserializeJsRootObject(argList, 1);
handled = true;
}
else if (name == kJavascriptAsyncMethodCallResponse)
{
auto frameId = GetInt64(argList, 0);
auto callbackId = GetInt64(argList, 1);
JavascriptRootObjectWrapper^ rootObjectWrapper;
browserWrapper->JavascriptRootObjectWrappers->TryGetValue(frameId, rootObjectWrapper);
if (rootObjectWrapper != nullptr)
{
JavascriptAsyncMethodCallback^ callback;
if (rootObjectWrapper->TryGetAndRemoveMethodCallback(callbackId, callback))
{
auto success = argList->GetBool(2);
if (success)
{
callback->Success(DeserializeV8Object(argList, 3));
}
else
{
callback->Fail(argList->GetString(3));
}
//dispose
delete callback;
}
}
handled = true;
}
return handled;
};
void CefAppUnmanagedWrapper::OnRenderThreadCreated(CefRefPtr<CefListValue> extraInfo)
{
auto extensionList = extraInfo->GetList(0);
for (size_t i = 0; i < extensionList->GetSize(); i++)
{
auto extension = extensionList->GetList(i);
auto ext = gcnew CefExtension(StringUtils::ToClr(extension->GetString(0)), StringUtils::ToClr(extension->GetString(1)));
_extensions->Add(ext);
}
}
void CefAppUnmanagedWrapper::OnWebKitInitialized()
{
//we need to do this because the builtin Promise object is not accesible
CefRegisterExtension("cefsharp/promisecreator", kPromiseCreatorScript, NULL);
for each(CefExtension^ extension in _extensions->AsReadOnly())
{
//only support extensions without handlers now
CefRegisterExtension(StringUtils::ToNative(extension->Name), StringUtils::ToNative(extension->JavascriptCode), NULL);
}
}
void CefAppUnmanagedWrapper::OnRegisterCustomSchemes(CefRefPtr<CefSchemeRegistrar> registrar)
{
for each (CefCustomScheme^ scheme in _schemes->AsReadOnly())
{
registrar->AddCustomScheme(StringUtils::ToNative(scheme->SchemeName), scheme->IsStandard, scheme->IsLocal, scheme->IsDisplayIsolated);
}
}
}<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Monteverdi2
Language: C++
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See Copyright.txt for details.
Monteverdi2 is distributed under the CeCILL licence version 2. See
Licence_CeCILL_V2-en.txt or
http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mvdWrapperQtWidgetView.h"
/*****************************************************************************/
/* INCLUDE SECTION */
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
//
// System includes (sorted by alphabetic order)
//
// ITK includes (sorted by alphabetic order)
//
// OTB includes (sorted by alphabetic order)
#include "otbWrapperQtWidgetProgressReport.h"
#include "otbWrapperQtWidgetSimpleProgressReport.h"
#include "otbWrapperQtWidgetOutputImageParameter.h"
#include "otbWrapperApplicationHtmlDocGenerator.h"
#include "otbWrapperTypes.h"
#include "otbWrapperOutputImageParameter.h"
#include "otbWrapperComplexOutputImageParameter.h" // TODO : handle
// this param to
// get the outfname
//
// Monteverdi includes (sorted by alphabetic order)
#include "mvdWrapperQtWidgetParameterFactory.h"
//
#include "Core/mvdI18nCoreApplication.h"
namespace mvd
{
namespace Wrapper
{
/*
TRANSLATOR mvd::ApplicationLauncher
Necessary for lupdate to be aware of C++ namespaces.
Context comment for translator.
*/
/*****************************************************************************/
/* CONSTANTS */
/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION */
/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION */
/*******************************************************************************/
QtWidgetView
::QtWidgetView( otb::Wrapper::Application::Pointer otbApp,
QWidget* parent,
Qt::WindowFlags flags ) :
m_Application( otbApp ),
m_Model( NULL ),
m_ExecButton( NULL ),
m_QuitButton( NULL ),
m_Message( NULL ),
m_IsClosable( true )
{
m_Model = new otb::Wrapper::QtWidgetModel( otbApp );
QObject::connect(
m_Model, SIGNAL( SetProgressReportBegin() ),
this, SLOT( OnProgressReportBegin() )
);
QObject::connect(
m_Model, SIGNAL( SetProgressReportDone( int ) ),
this, SLOT( OnProgressReportEnd( int ) )
);
QObject::connect(
m_Model, SIGNAL( ExceptionRaised( QString ) ),
this, SLOT( OnExceptionRaised( QString ) )
);
}
/*******************************************************************************/
QtWidgetView
::~QtWidgetView()
{
// m_Application is smart-pointed and will be automatically deleted.
delete m_Model;
m_Model = NULL;
}
/*******************************************************************************/
void
QtWidgetView
::CreateGui()
{
// Create a VBoxLayout with the header, the input widgets, and the footer
QVBoxLayout *mainLayout = new QVBoxLayout();
QTabWidget *tab = new QTabWidget();
tab->addTab(CreateInputWidgets(), "Parameters");
//otb::Wrapper::QtWidgetProgressReport* prog = new otb::Wrapper::QtWidgetProgressReport(m_Model);
//prog->SetApplication(m_Application);
//tab->addTab(prog, "Progress");
tab->addTab(CreateDoc(), "Documentation");
mainLayout->addWidget(tab);
QTextEdit *log = new QTextEdit();
connect( m_Model->GetLogOutput(), SIGNAL(NewContentLog(QString)), log, SLOT(append(QString) ) );
tab->addTab(log, "Logs");
m_Message = new QLabel("<center><font color=\"#FF0000\">Select parameters</font></center>");
connect(
m_Model,
SIGNAL( SetApplicationReady( bool ) ),
this, SLOT( UpdateMessageAfterApplicationReady( bool ) )
);
mainLayout->addWidget(m_Message);
otb::Wrapper::QtWidgetSimpleProgressReport* progressReport =
new otb::Wrapper::QtWidgetSimpleProgressReport(m_Model);
progressReport->SetApplication(m_Application);
QHBoxLayout *footLayout = new QHBoxLayout;
footLayout->addWidget(progressReport);
footLayout->addWidget(CreateFooter());
mainLayout->addLayout(footLayout);
QGroupBox *mainGroup = new QGroupBox();
mainGroup->setLayout(mainLayout);
QVBoxLayout *finalLayout = new QVBoxLayout();
finalLayout->addWidget(mainGroup);
// Make the final layout to the widget
this->setLayout(finalLayout);
}
/*******************************************************************************/
QWidget*
QtWidgetView
::CreateInputWidgets()
{
QScrollArea *scrollArea = new QScrollArea;
// Put the main group inside a scroll area
QWidget * widgets =
mvd::Wrapper::QtWidgetParameterFactory::CreateQtWidget(m_Model->GetApplication()->GetParameterList(),
m_Model);
scrollArea->setWidget(widgets);
scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
scrollArea->setWidgetResizable(true);
//
// need to be connected to the end of a process
QObject::connect(
m_Model,
SIGNAL( SetProgressReportDone( int ) ),
// to:
this,
SLOT ( OnApplicationExecutionDone( int ) )
);
//
// setup the default output in Widgets OutputImageParameter
FillOTBAppDefaultOutputImageParameter(widgets);
return scrollArea;
}
/*******************************************************************************/
QWidget*
QtWidgetView
::CreateFooter()
{
// an HLayout with two buttons : Execute and Quit
QGroupBox *footerGroup = new QGroupBox;
QHBoxLayout *footerLayout = new QHBoxLayout;
footerGroup->setFixedHeight(40);
footerGroup->setContentsMargins(0, 0, 0, 0);
footerLayout->setContentsMargins(5, 5, 5, 5);
m_ExecButton = new QPushButton(footerGroup);
m_ExecButton->setDefault(true);
m_ExecButton->setEnabled(false);
m_ExecButton->setText(QObject::tr("Execute"));
connect(
m_Model, SIGNAL( SetApplicationReady( bool ) ),
m_ExecButton, SLOT( setEnabled( bool ) )
);
QObject::connect(
m_ExecButton, SIGNAL( clicked() ),
// to:
this, SLOT( OnExecButtonClicked() )
);
QObject::connect(
this, SIGNAL( ExecuteAndWriteOutput() ),
// to:
m_Model, SLOT( ExecuteAndWriteOutputSlot() )
);
m_QuitButton = new QPushButton(footerGroup);
m_QuitButton->setText(QObject::tr("Quit"));
connect(
m_QuitButton, SIGNAL( clicked() ),
this, SLOT( CloseSlot() )
);
// Put the buttons on the right
footerLayout->addStretch();
footerLayout->addWidget(m_ExecButton);
footerLayout->addWidget(m_QuitButton);
footerGroup->setLayout(footerLayout);
return footerGroup;
}
/*******************************************************************************/
QWidget*
QtWidgetView
::CreateDoc()
{
QTextEdit *text = new QTextEdit;
text->setReadOnly(true);
QTextDocument * doc = new QTextDocument();
std::string docContain;
otb::Wrapper::ApplicationHtmlDocGenerator::GenerateDoc( m_Application, docContain);
doc->setHtml(docContain.c_str());
text->setDocument(doc);
return text;
}
/*******************************************************************************/
void
QtWidgetView
::FillOTBAppDefaultOutputImageParameter( QWidget * widgets)
{
//
// Get the cache dir
// get the const instance of the application.
I18nCoreApplication* app = I18nCoreApplication::Instance();
//
// get the OTB application widget layout
QLayout * layout = widgets->layout();
for (int idx = 0; idx < layout->count(); idx++ )
{
QWidget * currentWidget = layout->itemAt(idx)->widget();
// is it a QtWidgetOutputImageParameter ?
otb::Wrapper::QtWidgetOutputImageParameter * outParam
= qobject_cast<otb::Wrapper::QtWidgetOutputImageParameter *>(currentWidget);
if (outParam)
{
// generate a default output fname for the current
// OutputImageParameter
QString outfname =
app->GetResultsDir().absolutePath()
+ "/"+ m_Application->GetName()
+"_"+ GenerateIdentifier() +".tif";
// use it
outParam->SetFileName(outfname);
outParam->UpdateGUI();
} // else is it a {Group/Choice}Parameter Widget containing
// QtWidgetOutputImageParameters ?
else
{
//
QList< otb::Wrapper::QtWidgetOutputImageParameter *> outParameterWidget
= currentWidget->findChildren<otb::Wrapper::QtWidgetOutputImageParameter*>();
QList<otb::Wrapper::QtWidgetOutputImageParameter *>::iterator it = outParameterWidget.begin();
//
while(it != outParameterWidget.end())
{
if (*it)
{
// generate a default output fname for the current
// OutputImageParameter
QString outfname =
app->GetResultsDir().absolutePath() + "/"+ m_Application->GetName()+"_"+GenerateIdentifier()+".tif";
// use the outfname
(*it)->SetFileName(outfname);
(*it)->UpdateGUI();
}
++it;
}
}
}
}
/*******************************************************************************/
QString
QtWidgetView
::GenerateIdentifier()
{
//
// get an unique identifier and remove braces
QString identifier = QUuid::createUuid().toString();
identifier.replace("{", "");
identifier.replace("}", "");
return identifier;
}
/*******************************************************************************/
/* SLOTS */
/*******************************************************************************/
void
QtWidgetView
::CloseSlot()
{
// Close the widget
this->close();
// Emit a signal to close any widget that this gui belonging to
emit QuitSignal();
}
/*******************************************************************************/
#if 0
void
QtWidgetView
::UpdateMessageAfterExcuteClicked()
{
m_Message->setText("<center><font color=\"#FF0000\">Running</font></center>");
}
#endif
/*******************************************************************************/
void
QtWidgetView
::OnExecButtonClicked()
{
assert( m_Model!=NULL );
assert( m_Model->GetApplication()!=NULL );
otb::Wrapper::Application::Pointer otbApp( m_Model->GetApplication() );
StringVector paramKeys( otbApp->GetParametersKeys() );
bool isSure = true;
/*
typedef QVector< QFileInfo > FileInfoVector;
FileInfoVector fileInfos;
*/
for( StringVector::const_iterator it( paramKeys.begin() );
it!=paramKeys.end() && isSure;
++it )
{
if( otbApp->GetParameterType( *it )==
otb::Wrapper::ParameterType_OutputImage &&
otbApp->IsParameterEnabled( *it ) &&
otbApp->HasValue( *it ) )
{
otb::Wrapper::Parameter::Pointer param( otbApp->GetParameterByKey( *it ) );
otb::Wrapper::OutputImageParameter::Pointer outImgParam(
otb::DynamicCast< otb::Wrapper::OutputImageParameter >( param )
);
QFileInfo fileInfo( outImgParam->GetFileName() );
if( fileInfo.exists() )
{
QMessageBox::StandardButton questionButton =
QMessageBox::question(
this,
tr( PROJECT_NAME ),
tr( "Are you sure you want to overwrite file '%1'?" )
.arg( outImgParam->GetFileName() ),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::No
);
if( questionButton==QMessageBox::Yes )
{
/*
fileInfos.push_back( fileInfo );
*/
}
else
isSure = false;
}
}
}
if( !isSure )
return;
/* U N S A F E
// BUGFIX: Mantis-750
//
// Remove files which will be overwritten in order to use
// file-existence to check whether to emit the OutputImageChanged
// signal (see ::OnApplicationExecutionDone()).
for( FileInfoVector::const_iterator it( fileInfos.begin() );
it!=fileInfos.end();
++it )
{
qDebug() << "Removing:" << it->filePath();
it->dir().remove( it->fileName() );
}
*/
m_Message->setText("<center><font color=\"#FF0000\">Running</font></center>");
emit ExecuteAndWriteOutput();
}
/*******************************************************************************/
void
QtWidgetView
::UpdateMessageAfterApplicationReady( bool val )
{
if(val == true)
m_Message->setText("<center><font color=\"#00FF00\">Ready to run</font></center>");
else
m_Message->setText("<center><font color=\"#FF0000\">Select parameters</font></center>");
}
/*******************************************************************************/
void
QtWidgetView
::OnExceptionRaised( QString what )
{
qWarning() << what;
#if defined( _DEBUG )
QMessageBox::warning(
this,
PROJECT_NAME,
what,
QMessageBox::Ok
);
#endif
}
/*******************************************************************************/
void
QtWidgetView
::OnApplicationExecutionDone( int status )
{
otb::Wrapper::Application::Pointer otbApp( m_Model->GetApplication() );
if( status!=0 )
{
QMessageBox::information(
this,
PROJECT_NAME,
tr( "'%1' has failed with return status %2.\n"
"Please refer to '%1' documentation and check log tab."
)
.arg( otbApp->GetName() )
.arg( status ),
QMessageBox::Ok
);
emit ExecutionDone( status );
return;
}
QMessageBox::information(
this,
PROJECT_NAME,
tr( "'%1' has succeeded with return status %2.\n"
"Result(s) will be imported as dataset(s).\n"
"Please check '%1' log tab." )
.arg( otbApp->GetName() )
.arg( status ),
QMessageBox::Ok
);
CountType count = 0;
//
// detect if this application has outputImageParameter. emit
// the output filenames if any
StringVector paramList( otbApp->GetParametersKeys( true ) );
// iterate on the application parameters
for ( StringVector::const_iterator it( paramList.begin() );
it!=paramList.end();
++it )
{
// parameter key
const std::string& key = *it;
// get a valid outputParameter
if( otbApp->GetParameterType( key )
==otb::Wrapper::ParameterType_OutputImage &&
otbApp->IsParameterEnabled( key ) &&
otbApp->HasValue( key ) )
{
// get the parameter
otb::Wrapper::Parameter* param = otbApp->GetParameterByKey( key );
// try to cast it
otb::Wrapper::OutputImageParameter* outputParam =
dynamic_cast< otb::Wrapper::OutputImageParameter* >( param );
// emit the output image filename selected
if( outputParam!=NULL )
{
QFileInfo fileInfo( outputParam->GetFileName() );
/* U N S A F E
// BUGFIX: Mantis-750
//
// If output image-exists, it's sure that it has been output
// from the OTB-application process because overwritten
// files are first deleted (see OnExecButtonClicked()).
if( fileInfo.exists() )
{
*/
++ count;
emit OTBApplicationOutputImageChanged(
QString( otbApp->GetName() ),
QString( outputParam->GetFileName() )
);
/*
}
*/
}
}
}
emit ExecutionDone( status );
}
}
}
<commit_msg>ENH: Better checking of otb::Application output parameters when clicking exec button (more cases OutputImageParameter, OutputFilenameParameter, OutputVectorDataParameter, ComplexOutputImageParameter); ignore parameters disabled or which have a disabled parent).<commit_after>/*=========================================================================
Program: Monteverdi2
Language: C++
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See Copyright.txt for details.
Monteverdi2 is distributed under the CeCILL licence version 2. See
Licence_CeCILL_V2-en.txt or
http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mvdWrapperQtWidgetView.h"
/*****************************************************************************/
/* INCLUDE SECTION */
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
//
// System includes (sorted by alphabetic order)
//
// ITK includes (sorted by alphabetic order)
//
// OTB includes (sorted by alphabetic order)
#include "otbWrapperQtWidgetProgressReport.h"
#include "otbWrapperQtWidgetSimpleProgressReport.h"
#include "otbWrapperQtWidgetOutputImageParameter.h"
#include "otbWrapperApplicationHtmlDocGenerator.h"
#include "otbWrapperTypes.h"
#include "otbWrapperOutputFilenameParameter.h"
#include "otbWrapperOutputImageParameter.h"
#include "otbWrapperOutputVectorDataParameter.h"
#include "otbWrapperComplexOutputImageParameter.h"
//
// Monteverdi includes (sorted by alphabetic order)
#include "mvdWrapperQtWidgetParameterFactory.h"
//
#include "Core/mvdI18nCoreApplication.h"
namespace mvd
{
namespace Wrapper
{
/*
TRANSLATOR mvd::ApplicationLauncher
Necessary for lupdate to be aware of C++ namespaces.
Context comment for translator.
*/
/*****************************************************************************/
/* CONSTANTS */
/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION */
/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION */
/*******************************************************************************/
QtWidgetView
::QtWidgetView( otb::Wrapper::Application::Pointer otbApp,
QWidget* parent,
Qt::WindowFlags flags ) :
m_Application( otbApp ),
m_Model( NULL ),
m_ExecButton( NULL ),
m_QuitButton( NULL ),
m_Message( NULL ),
m_IsClosable( true )
{
m_Model = new otb::Wrapper::QtWidgetModel( otbApp );
QObject::connect(
m_Model, SIGNAL( SetProgressReportBegin() ),
this, SLOT( OnProgressReportBegin() )
);
QObject::connect(
m_Model, SIGNAL( SetProgressReportDone( int ) ),
this, SLOT( OnProgressReportEnd( int ) )
);
QObject::connect(
m_Model, SIGNAL( ExceptionRaised( QString ) ),
this, SLOT( OnExceptionRaised( QString ) )
);
}
/*******************************************************************************/
QtWidgetView
::~QtWidgetView()
{
// m_Application is smart-pointed and will be automatically deleted.
delete m_Model;
m_Model = NULL;
}
/*******************************************************************************/
void
QtWidgetView
::CreateGui()
{
// Create a VBoxLayout with the header, the input widgets, and the footer
QVBoxLayout *mainLayout = new QVBoxLayout();
QTabWidget *tab = new QTabWidget();
tab->addTab(CreateInputWidgets(), "Parameters");
//otb::Wrapper::QtWidgetProgressReport* prog = new otb::Wrapper::QtWidgetProgressReport(m_Model);
//prog->SetApplication(m_Application);
//tab->addTab(prog, "Progress");
tab->addTab(CreateDoc(), "Documentation");
mainLayout->addWidget(tab);
QTextEdit *log = new QTextEdit();
connect( m_Model->GetLogOutput(), SIGNAL(NewContentLog(QString)), log, SLOT(append(QString) ) );
tab->addTab(log, "Logs");
m_Message = new QLabel("<center><font color=\"#FF0000\">Select parameters</font></center>");
connect(
m_Model,
SIGNAL( SetApplicationReady( bool ) ),
this, SLOT( UpdateMessageAfterApplicationReady( bool ) )
);
mainLayout->addWidget(m_Message);
otb::Wrapper::QtWidgetSimpleProgressReport* progressReport =
new otb::Wrapper::QtWidgetSimpleProgressReport(m_Model);
progressReport->SetApplication(m_Application);
QHBoxLayout *footLayout = new QHBoxLayout;
footLayout->addWidget(progressReport);
footLayout->addWidget(CreateFooter());
mainLayout->addLayout(footLayout);
QGroupBox *mainGroup = new QGroupBox();
mainGroup->setLayout(mainLayout);
QVBoxLayout *finalLayout = new QVBoxLayout();
finalLayout->addWidget(mainGroup);
// Make the final layout to the widget
this->setLayout(finalLayout);
}
/*******************************************************************************/
QWidget*
QtWidgetView
::CreateInputWidgets()
{
QScrollArea *scrollArea = new QScrollArea;
// Put the main group inside a scroll area
QWidget * widgets =
mvd::Wrapper::QtWidgetParameterFactory::CreateQtWidget(m_Model->GetApplication()->GetParameterList(),
m_Model);
scrollArea->setWidget(widgets);
scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
scrollArea->setWidgetResizable(true);
//
// need to be connected to the end of a process
QObject::connect(
m_Model,
SIGNAL( SetProgressReportDone( int ) ),
// to:
this,
SLOT ( OnApplicationExecutionDone( int ) )
);
//
// setup the default output in Widgets OutputImageParameter
FillOTBAppDefaultOutputImageParameter(widgets);
return scrollArea;
}
/*******************************************************************************/
QWidget*
QtWidgetView
::CreateFooter()
{
// an HLayout with two buttons : Execute and Quit
QGroupBox *footerGroup = new QGroupBox;
QHBoxLayout *footerLayout = new QHBoxLayout;
footerGroup->setFixedHeight(40);
footerGroup->setContentsMargins(0, 0, 0, 0);
footerLayout->setContentsMargins(5, 5, 5, 5);
m_ExecButton = new QPushButton(footerGroup);
m_ExecButton->setDefault(true);
m_ExecButton->setEnabled(false);
m_ExecButton->setText(QObject::tr("Execute"));
connect(
m_Model, SIGNAL( SetApplicationReady( bool ) ),
m_ExecButton, SLOT( setEnabled( bool ) )
);
QObject::connect(
m_ExecButton, SIGNAL( clicked() ),
// to:
this, SLOT( OnExecButtonClicked() )
);
QObject::connect(
this, SIGNAL( ExecuteAndWriteOutput() ),
// to:
m_Model, SLOT( ExecuteAndWriteOutputSlot() )
);
m_QuitButton = new QPushButton(footerGroup);
m_QuitButton->setText(QObject::tr("Quit"));
connect(
m_QuitButton, SIGNAL( clicked() ),
this, SLOT( CloseSlot() )
);
// Put the buttons on the right
footerLayout->addStretch();
footerLayout->addWidget(m_ExecButton);
footerLayout->addWidget(m_QuitButton);
footerGroup->setLayout(footerLayout);
return footerGroup;
}
/*******************************************************************************/
QWidget*
QtWidgetView
::CreateDoc()
{
QTextEdit *text = new QTextEdit;
text->setReadOnly(true);
QTextDocument * doc = new QTextDocument();
std::string docContain;
otb::Wrapper::ApplicationHtmlDocGenerator::GenerateDoc( m_Application, docContain);
doc->setHtml(docContain.c_str());
text->setDocument(doc);
return text;
}
/*******************************************************************************/
void
QtWidgetView
::FillOTBAppDefaultOutputImageParameter( QWidget * widgets)
{
//
// Get the cache dir
// get the const instance of the application.
I18nCoreApplication* app = I18nCoreApplication::Instance();
//
// get the OTB application widget layout
QLayout * layout = widgets->layout();
for (int idx = 0; idx < layout->count(); idx++ )
{
QWidget * currentWidget = layout->itemAt(idx)->widget();
// is it a QtWidgetOutputImageParameter ?
otb::Wrapper::QtWidgetOutputImageParameter * outParam
= qobject_cast<otb::Wrapper::QtWidgetOutputImageParameter *>(currentWidget);
if (outParam)
{
// generate a default output fname for the current
// OutputImageParameter
QString outfname =
app->GetResultsDir().absolutePath()
+ "/"+ m_Application->GetName()
+"_"+ GenerateIdentifier() +".tif";
// use it
outParam->SetFileName(outfname);
outParam->UpdateGUI();
} // else is it a {Group/Choice}Parameter Widget containing
// QtWidgetOutputImageParameters ?
else
{
//
QList< otb::Wrapper::QtWidgetOutputImageParameter *> outParameterWidget
= currentWidget->findChildren<otb::Wrapper::QtWidgetOutputImageParameter*>();
QList<otb::Wrapper::QtWidgetOutputImageParameter *>::iterator it = outParameterWidget.begin();
//
while(it != outParameterWidget.end())
{
if (*it)
{
// generate a default output fname for the current
// OutputImageParameter
QString outfname =
app->GetResultsDir().absolutePath() + "/"+ m_Application->GetName()+"_"+GenerateIdentifier()+".tif";
// use the outfname
(*it)->SetFileName(outfname);
(*it)->UpdateGUI();
}
++it;
}
}
}
}
/*******************************************************************************/
QString
QtWidgetView
::GenerateIdentifier()
{
//
// get an unique identifier and remove braces
QString identifier = QUuid::createUuid().toString();
identifier.replace("{", "");
identifier.replace("}", "");
return identifier;
}
/*******************************************************************************/
/* SLOTS */
/*******************************************************************************/
void
QtWidgetView
::CloseSlot()
{
// Close the widget
this->close();
// Emit a signal to close any widget that this gui belonging to
emit QuitSignal();
}
/*******************************************************************************/
#if 0
void
QtWidgetView
::UpdateMessageAfterExcuteClicked()
{
m_Message->setText("<center><font color=\"#FF0000\">Running</font></center>");
}
#endif
/*******************************************************************************/
void
QtWidgetView
::OnExecButtonClicked()
{
assert( m_Model!=NULL );
assert( m_Model->GetApplication()!=NULL );
otb::Wrapper::Application::Pointer otbApp( m_Model->GetApplication() );
StringVector paramKeys( otbApp->GetParametersKeys() );
bool isSure = true;
/*
typedef QVector< QFileInfo > FileInfoVector;
FileInfoVector fileInfos;
*/
for( StringVector::const_iterator it( paramKeys.begin() );
it!=paramKeys.end() && isSure;
++it )
{
if( otbApp->IsParameterEnabled( *it, true ) &&
otbApp->HasValue( *it ) )
{
otb::Wrapper::Parameter::Pointer param( otbApp->GetParameterByKey( *it ) );
assert( !param.IsNull() );
// qDebug()
// << it->c_str() << ": type" << otbApp->GetParameterType( *it );
// const char* filename = NULL;
std::string filename;
switch( otbApp->GetParameterType( *it ) )
{
case otb::Wrapper::ParameterType_OutputFilename:
/*
assert(
otb::DynamicCast< otb::Wrapper::OutputImageParameter >( param )
== param
);
*/
filename =
otb::DynamicCast< otb::Wrapper::OutputFilenameParameter >( param )
->GetValue();
break;
//
// FILENAME.
//
// IMAGE.
case otb::Wrapper::ParameterType_OutputImage:
filename =
otb::DynamicCast< otb::Wrapper::OutputImageParameter >( param )
->GetFileName();
break;
//
// VECTOR-DATA.
case otb::Wrapper::ParameterType_OutputVectorData:
filename =
otb::DynamicCast< otb::Wrapper::OutputVectorDataParameter >( param )
->GetFileName();
break;
//
// COMPLEX IMAGE.
case otb::Wrapper::ParameterType_ComplexOutputImage:
filename =
otb::DynamicCast< otb::Wrapper::ComplexOutputImageParameter >( param )
->GetFileName();
break;
//
// NONE.
default:
break;
}
if( !filename.empty() )
{
// qDebug()
// << it->c_str() << ":" << QString( filename.c_str() );
QFileInfo fileInfo( filename.c_str() );
if( fileInfo.exists() )
{
QMessageBox::StandardButton questionButton =
QMessageBox::question(
this,
tr( PROJECT_NAME ),
tr( "Are you sure you want to overwrite file '%1'?" )
.arg( filename.c_str() ),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::No
);
if( questionButton==QMessageBox::Yes )
{
/*
fileInfos.push_back( fileInfo );
*/
}
else
isSure = false;
}
}
}
}
if( !isSure )
return;
/* U N S A F E
// BUGFIX: Mantis-750
//
// Remove files which will be overwritten in order to use
// file-existence to check whether to emit the OutputImageChanged
// signal (see ::OnApplicationExecutionDone()).
for( FileInfoVector::const_iterator it( fileInfos.begin() );
it!=fileInfos.end();
++it )
{
qDebug() << "Removing:" << it->filePath();
it->dir().remove( it->fileName() );
}
*/
m_Message->setText("<center><font color=\"#FF0000\">Running</font></center>");
emit ExecuteAndWriteOutput();
}
/*******************************************************************************/
void
QtWidgetView
::UpdateMessageAfterApplicationReady( bool val )
{
if(val == true)
m_Message->setText("<center><font color=\"#00FF00\">Ready to run</font></center>");
else
m_Message->setText("<center><font color=\"#FF0000\">Select parameters</font></center>");
}
/*******************************************************************************/
void
QtWidgetView
::OnExceptionRaised( QString what )
{
qWarning() << what;
#if defined( _DEBUG )
QMessageBox::warning(
this,
PROJECT_NAME,
what,
QMessageBox::Ok
);
#endif
}
/*******************************************************************************/
void
QtWidgetView
::OnApplicationExecutionDone( int status )
{
otb::Wrapper::Application::Pointer otbApp( m_Model->GetApplication() );
if( status!=0 )
{
QMessageBox::information(
this,
PROJECT_NAME,
tr( "'%1' has failed with return status %2.\n"
"Please refer to '%1' documentation and check log tab."
)
.arg( otbApp->GetName() )
.arg( status ),
QMessageBox::Ok
);
emit ExecutionDone( status );
return;
}
QMessageBox::information(
this,
PROJECT_NAME,
tr( "'%1' has succeeded with return status %2.\n"
"Result(s) will be imported as dataset(s).\n"
"Please check '%1' log tab." )
.arg( otbApp->GetName() )
.arg( status ),
QMessageBox::Ok
);
CountType count = 0;
//
// detect if this application has outputImageParameter. emit
// the output filenames if any
StringVector paramList( otbApp->GetParametersKeys( true ) );
// iterate on the application parameters
for ( StringVector::const_iterator it( paramList.begin() );
it!=paramList.end();
++it )
{
// parameter key
const std::string& key = *it;
// get a valid outputParameter
if( otbApp->GetParameterType( key )
==otb::Wrapper::ParameterType_OutputImage &&
otbApp->IsParameterEnabled( key, true ) &&
otbApp->HasValue( key ) )
{
// get the parameter
otb::Wrapper::Parameter* param = otbApp->GetParameterByKey( key );
// try to cast it
otb::Wrapper::OutputImageParameter* outputParam =
dynamic_cast< otb::Wrapper::OutputImageParameter* >( param );
// emit the output image filename selected
if( outputParam!=NULL )
{
QFileInfo fileInfo( outputParam->GetFileName() );
/* U N S A F E
// BUGFIX: Mantis-750
//
// If output image-exists, it's sure that it has been output
// from the OTB-application process because overwritten
// files are first deleted (see OnExecButtonClicked()).
if( fileInfo.exists() )
{
*/
++ count;
emit OTBApplicationOutputImageChanged(
QString( otbApp->GetName() ),
QString( outputParam->GetFileName() )
);
/*
}
*/
}
}
}
emit ExecutionDone( status );
}
}
}
<|endoftext|>
|
<commit_before>/***************************************************************************
* *
* Copyright (C) 2009-2015 by frePPLe bvba *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Affero General Public License as published *
* by the Free Software Foundation; either version 3 of the License, or *
* (at your option) any later version. *
* *
* 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 Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public *
* License along with this program. *
* If not, see <http://www.gnu.org/licenses/>. *
* *
***************************************************************************/
#define FREPPLE_CORE
#include "frepple/model.h"
namespace frepple
{
template<class SetupMatrix> DECLARE_EXPORT Tree utils::HasName<SetupMatrix>::st;
DECLARE_EXPORT const MetaCategory* SetupMatrix::metadata;
DECLARE_EXPORT const MetaClass* SetupMatrixDefault::metadata;
DECLARE_EXPORT const MetaCategory* SetupMatrixRule::metadata;
int SetupMatrix::initialize()
{
// Initialize the metadata
metadata = MetaCategory::registerCategory<SetupMatrix>("setupmatrix", "setupmatrices", reader, writer, finder);
registerFields<SetupMatrix>(const_cast<MetaCategory*>(metadata));
// Initialize the Python class
FreppleCategory<SetupMatrix>::getPythonType().addMethod("addRule",
addPythonRule, METH_VARARGS | METH_KEYWORDS, "add a new setup rule");
return FreppleCategory<SetupMatrix>::initialize()
+ SetupMatrixRuleIterator::initialize();
}
int SetupMatrixRule::initialize()
{
// Initialize the metadata
metadata = MetaCategory::registerCategory<SetupMatrixRule>("setupmatrixrule", "setupmatrixrules");
registerFields<SetupMatrixRule>(const_cast<MetaCategory*>(metadata));
// Initialize the Python class
PythonType& x = PythonExtension<SetupMatrixRule>::getPythonType();
x.setName("setupmatrixrule");
x.setDoc("frePPLe setupmatrixrule");
x.supportgetattro();
x.supportsetattro();
const_cast<MetaCategory*>(metadata)->pythonClass = x.type_object();
return x.typeReady();
}
int SetupMatrixDefault::initialize()
{
// Initialize the metadata
SetupMatrixDefault::metadata = MetaClass::registerClass<SetupMatrixDefault>(
"setupmatrix",
"setupmatrix_default",
Object::create<SetupMatrixDefault>, true);
// Initialize the Python class
return FreppleClass<SetupMatrixDefault,SetupMatrix>::initialize();
}
DECLARE_EXPORT SetupMatrix::~SetupMatrix()
{
// Destroy the rules.
// Note that the rule destructor updates the firstRule field.
while (firstRule) delete firstRule;
// Remove all references to this setup matrix from resources
for (Resource::iterator m = Resource::begin(); m != Resource::end(); ++m)
if (m->getSetupMatrix() == this) m->setSetupMatrix(NULL);
}
DECLARE_EXPORT SetupMatrixRule* SetupMatrix::createRule(const DataValueDict& atts)
{
// Pick up the start, end and name attributes
int priority = atts.get(Tags::priority)->getInt();
// Check for existence of a rule with the same priority
SetupMatrixRule* result = firstRule;
while (result && priority > result->priority)
result = result->nextRule;
if (result && result->priority != priority) result = NULL;
// Pick up the action attribute and update the rule accordingly
switch (MetaClass::decodeAction(atts))
{
case ADD:
// Only additions are allowed
if (result)
{
ostringstream o;
o << "Rule with priority " << priority
<< " already exists in setup matrix '" << getName() << "'";
throw DataException(o.str());
}
result = new SetupMatrixRule(this, priority);
return result;
case CHANGE:
// Only changes are allowed
if (!result)
{
ostringstream o;
o << "No rule with priority " << priority
<< " exists in setup matrix '" << getName() << "'";
throw DataException(o.str());
}
return result;
case REMOVE:
// Delete the entity
if (!result)
{
ostringstream o;
o << "No rule with priority " << priority
<< " exists in setup matrix '" << getName() << "'";
throw DataException(o.str());
}
else
{
// Delete it
delete result;
return NULL;
}
case ADD_CHANGE:
if (!result)
// Adding a new rule
result = new SetupMatrixRule(this, priority);
return result;
}
// This part of the code isn't expected not be reached
throw LogicException("Unreachable code reached");
}
DECLARE_EXPORT PyObject* SetupMatrix::addPythonRule(PyObject* self, PyObject* args, PyObject* kwdict)
{
try
{
// Pick up the setup matrix
SetupMatrix *matrix = static_cast<SetupMatrix*>(self);
if (!matrix) throw LogicException("Can't add a rule to a NULL setupmatrix");
// Parse the arguments
int prio = 0;
PyObject *pyfrom = NULL;
PyObject *pyto = NULL;
long duration = 0;
double cost = 0;
static const char *kwlist[] = {"priority", "fromsetup", "tosetup", "duration", "cost", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwdict,
"i|ssld:addRule",
const_cast<char**>(kwlist), &prio, &pyfrom, &pyto, &duration, &cost))
return NULL;
// Add the new rule
SetupMatrixRule *r = new SetupMatrixRule(matrix, prio);
if (pyfrom) r->setFromSetup(PythonData(pyfrom).getString());
if (pyto) r->setToSetup(PythonData(pyfrom).getString());
r->setDuration(duration);
r->setCost(cost);
return PythonData(r);
}
catch(...)
{
PythonType::evalException();
return NULL;
}
}
DECLARE_EXPORT SetupMatrixRule::SetupMatrixRule(SetupMatrix *s, int p)
: cost(0), priority(p), matrix(s), nextRule(NULL), prevRule(NULL)
{
// Validate the arguments
if (!matrix) throw DataException("Can't add a rule to NULL setup matrix");
// Find the right place in the list
SetupMatrixRule *next = matrix->firstRule, *prev = NULL;
while (next && p > next->priority)
{
prev = next;
next = next->nextRule;
}
// Duplicate priority
if (next && next->priority == p)
throw DataException("Multiple rules with identical priority in setup matrix");
// Maintain linked list
nextRule = next;
prevRule = prev;
if (prev) prev->nextRule = this;
else matrix->firstRule = this;
if (next) next->prevRule = this;
// Initialize the Python type
initType(metadata);
}
DECLARE_EXPORT SetupMatrixRule::~SetupMatrixRule()
{
// Maintain linked list
if (nextRule) nextRule->prevRule = prevRule;
if (prevRule) prevRule->nextRule = nextRule;
else matrix->firstRule = nextRule;
}
DECLARE_EXPORT void SetupMatrixRule::setPriority(const int n)
{
// Update the field
priority = n;
// Check ordering on the left
while (prevRule && priority < prevRule->priority)
{
SetupMatrixRule* next = nextRule;
SetupMatrixRule* prev = prevRule;
if (prev && prev->prevRule) prev->prevRule->nextRule = this;
else matrix->firstRule = this;
if (prev) prev->nextRule = nextRule;
nextRule = prev;
prevRule = prev ? prev->prevRule : NULL;
if (next && next->nextRule) next->nextRule->prevRule = prev;
if (next) next->prevRule = prev;
if (prev) prev->prevRule = this;
}
// Check ordering on the right
while (nextRule && priority > nextRule->priority)
{
SetupMatrixRule* next = nextRule;
SetupMatrixRule* prev = prevRule;
nextRule = next->nextRule;
if (next && next->nextRule) next->nextRule->prevRule = this;
if (prev) prev->nextRule = next;
if (next) next->nextRule = this;
if (next) next->prevRule = prev;
prevRule = next;
}
// Check for duplicate priorities
if ((prevRule && prevRule->priority == priority)
|| (nextRule && nextRule->priority == priority))
{
ostringstream o;
o << "Duplicate priority " << priority << " in setup matrix '"
<< matrix->getName() << "'";
throw DataException(o.str());
}
}
int SetupMatrixRuleIterator::initialize()
{
// Initialize the type
PythonType& x = PythonExtension<SetupMatrixRuleIterator>::getPythonType();
x.setName("setupmatrixRuleIterator");
x.setDoc("frePPLe iterator for setupmatrix rules");
x.supportiter();
return x.typeReady();
}
PyObject* SetupMatrixRuleIterator::iternext()
{
if (currule == SetupMatrixRule::iterator::end()) return NULL;
PyObject *result = &*(currule++);
Py_INCREF(result);
return result;
}
DECLARE_EXPORT SetupMatrixRule* SetupMatrix::calculateSetup
(const string oldsetup, const string newsetup) const
{
// No need to look
if (oldsetup == newsetup) return NULL;
// Loop through all rules
for (SetupMatrixRule *curRule = firstRule; curRule; curRule = curRule->nextRule)
{
// Need a match on the fromsetup
if (!curRule->getFromSetup().empty()
&& !matchWildcard(curRule->getFromSetup().c_str(), oldsetup.c_str()))
continue;
// Need a match on the tosetup
if (!curRule->getToSetup().empty()
&& !matchWildcard(curRule->getToSetup().c_str(), newsetup.c_str()))
continue;
// Found a match
return curRule;
}
// No matching rule was found
logger << "Warning: Conversion from '" << oldsetup << "' to '" << newsetup
<< "' undefined in setup matrix '" << getName() << endl;
return NULL;
}
} // end namespace
<commit_msg>corrected logic to keep setupmatrix rules sorted<commit_after>/***************************************************************************
* *
* Copyright (C) 2009-2015 by frePPLe bvba *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Affero General Public License as published *
* by the Free Software Foundation; either version 3 of the License, or *
* (at your option) any later version. *
* *
* 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 Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public *
* License along with this program. *
* If not, see <http://www.gnu.org/licenses/>. *
* *
***************************************************************************/
#define FREPPLE_CORE
#include "frepple/model.h"
namespace frepple
{
template<class SetupMatrix> DECLARE_EXPORT Tree utils::HasName<SetupMatrix>::st;
DECLARE_EXPORT const MetaCategory* SetupMatrix::metadata;
DECLARE_EXPORT const MetaClass* SetupMatrixDefault::metadata;
DECLARE_EXPORT const MetaCategory* SetupMatrixRule::metadata;
int SetupMatrix::initialize()
{
// Initialize the metadata
metadata = MetaCategory::registerCategory<SetupMatrix>("setupmatrix", "setupmatrices", reader, writer, finder);
registerFields<SetupMatrix>(const_cast<MetaCategory*>(metadata));
// Initialize the Python class
FreppleCategory<SetupMatrix>::getPythonType().addMethod("addRule",
addPythonRule, METH_VARARGS | METH_KEYWORDS, "add a new setup rule");
return FreppleCategory<SetupMatrix>::initialize()
+ SetupMatrixRuleIterator::initialize();
}
int SetupMatrixRule::initialize()
{
// Initialize the metadata
metadata = MetaCategory::registerCategory<SetupMatrixRule>("setupmatrixrule", "setupmatrixrules");
registerFields<SetupMatrixRule>(const_cast<MetaCategory*>(metadata));
// Initialize the Python class
PythonType& x = PythonExtension<SetupMatrixRule>::getPythonType();
x.setName("setupmatrixrule");
x.setDoc("frePPLe setupmatrixrule");
x.supportgetattro();
x.supportsetattro();
const_cast<MetaCategory*>(metadata)->pythonClass = x.type_object();
return x.typeReady();
}
int SetupMatrixDefault::initialize()
{
// Initialize the metadata
SetupMatrixDefault::metadata = MetaClass::registerClass<SetupMatrixDefault>(
"setupmatrix",
"setupmatrix_default",
Object::create<SetupMatrixDefault>, true);
// Initialize the Python class
return FreppleClass<SetupMatrixDefault,SetupMatrix>::initialize();
}
DECLARE_EXPORT SetupMatrix::~SetupMatrix()
{
// Destroy the rules.
// Note that the rule destructor updates the firstRule field.
while (firstRule) delete firstRule;
// Remove all references to this setup matrix from resources
for (Resource::iterator m = Resource::begin(); m != Resource::end(); ++m)
if (m->getSetupMatrix() == this) m->setSetupMatrix(NULL);
}
DECLARE_EXPORT SetupMatrixRule* SetupMatrix::createRule(const DataValueDict& atts)
{
// Pick up the start, end and name attributes
int priority = atts.get(Tags::priority)->getInt();
// Check for existence of a rule with the same priority
SetupMatrixRule* result = firstRule;
while (result && priority > result->priority)
result = result->nextRule;
if (result && result->priority != priority) result = NULL;
// Pick up the action attribute and update the rule accordingly
switch (MetaClass::decodeAction(atts))
{
case ADD:
// Only additions are allowed
if (result)
{
ostringstream o;
o << "Rule with priority " << priority
<< " already exists in setup matrix '" << getName() << "'";
throw DataException(o.str());
}
result = new SetupMatrixRule(this, priority);
return result;
case CHANGE:
// Only changes are allowed
if (!result)
{
ostringstream o;
o << "No rule with priority " << priority
<< " exists in setup matrix '" << getName() << "'";
throw DataException(o.str());
}
return result;
case REMOVE:
// Delete the entity
if (!result)
{
ostringstream o;
o << "No rule with priority " << priority
<< " exists in setup matrix '" << getName() << "'";
throw DataException(o.str());
}
else
{
// Delete it
delete result;
return NULL;
}
case ADD_CHANGE:
if (!result)
// Adding a new rule
result = new SetupMatrixRule(this, priority);
return result;
}
// This part of the code isn't expected not be reached
throw LogicException("Unreachable code reached");
}
DECLARE_EXPORT PyObject* SetupMatrix::addPythonRule(PyObject* self, PyObject* args, PyObject* kwdict)
{
try
{
// Pick up the setup matrix
SetupMatrix *matrix = static_cast<SetupMatrix*>(self);
if (!matrix) throw LogicException("Can't add a rule to a NULL setupmatrix");
// Parse the arguments
int prio = 0;
PyObject *pyfrom = NULL;
PyObject *pyto = NULL;
long duration = 0;
double cost = 0;
static const char *kwlist[] = {"priority", "fromsetup", "tosetup", "duration", "cost", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwdict,
"i|ssld:addRule",
const_cast<char**>(kwlist), &prio, &pyfrom, &pyto, &duration, &cost))
return NULL;
// Add the new rule
SetupMatrixRule *r = new SetupMatrixRule(matrix, prio);
if (pyfrom) r->setFromSetup(PythonData(pyfrom).getString());
if (pyto) r->setToSetup(PythonData(pyfrom).getString());
r->setDuration(duration);
r->setCost(cost);
return PythonData(r);
}
catch(...)
{
PythonType::evalException();
return NULL;
}
}
DECLARE_EXPORT SetupMatrixRule::SetupMatrixRule(SetupMatrix *s, int p)
: cost(0), priority(p), matrix(s), nextRule(NULL), prevRule(NULL)
{
// Validate the arguments
if (!matrix) throw DataException("Can't add a rule to NULL setup matrix");
// Find the right place in the list
SetupMatrixRule *next = matrix->firstRule, *prev = NULL;
while (next && p > next->priority)
{
prev = next;
next = next->nextRule;
}
// Duplicate priority
if (next && next->priority == p)
throw DataException("Multiple rules with identical priority in setup matrix");
// Maintain linked list
nextRule = next;
prevRule = prev;
if (prev) prev->nextRule = this;
else matrix->firstRule = this;
if (next) next->prevRule = this;
// Initialize the Python type
initType(metadata);
}
DECLARE_EXPORT SetupMatrixRule::~SetupMatrixRule()
{
// Maintain linked list
if (nextRule) nextRule->prevRule = prevRule;
if (prevRule) prevRule->nextRule = nextRule;
else matrix->firstRule = nextRule;
}
DECLARE_EXPORT void SetupMatrixRule::setPriority(const int n)
{
// Update the field
priority = n;
// Check ordering on the left
while (prevRule && priority < prevRule->priority)
{
SetupMatrixRule* next = nextRule;
SetupMatrixRule* prev = prevRule;
if (prev->prevRule)
prev->prevRule->nextRule = this;
else
matrix->firstRule = this;
prev->nextRule = nextRule;
nextRule = prev;
prevRule = prev->prevRule;
if (next)
next->prevRule = prev;
prev->prevRule = this;
}
// Check ordering on the right
while (nextRule && priority > nextRule->priority)
{
SetupMatrixRule* next = nextRule;
SetupMatrixRule* prev = prevRule;
nextRule = next->nextRule;
if (next->nextRule)
next->nextRule->prevRule = this;
if (prev)
prev->nextRule = next;
else
matrix->firstRule = next;
next->nextRule = this;
next->prevRule = prev;
prevRule = next;
}
// Check for duplicate priorities
if ((prevRule && prevRule->priority == priority)
|| (nextRule && nextRule->priority == priority))
{
ostringstream o;
o << "Duplicate priority " << priority << " in setup matrix '"
<< matrix->getName() << "'";
throw DataException(o.str());
}
}
int SetupMatrixRuleIterator::initialize()
{
// Initialize the type
PythonType& x = PythonExtension<SetupMatrixRuleIterator>::getPythonType();
x.setName("setupmatrixRuleIterator");
x.setDoc("frePPLe iterator for setupmatrix rules");
x.supportiter();
return x.typeReady();
}
PyObject* SetupMatrixRuleIterator::iternext()
{
if (currule == SetupMatrixRule::iterator::end()) return NULL;
PyObject *result = &*(currule++);
Py_INCREF(result);
return result;
}
DECLARE_EXPORT SetupMatrixRule* SetupMatrix::calculateSetup
(const string oldsetup, const string newsetup) const
{
// No need to look
if (oldsetup == newsetup) return NULL;
// Loop through all rules
for (SetupMatrixRule *curRule = firstRule; curRule; curRule = curRule->nextRule)
{
// Need a match on the fromsetup
if (!curRule->getFromSetup().empty()
&& !matchWildcard(curRule->getFromSetup().c_str(), oldsetup.c_str()))
continue;
// Need a match on the tosetup
if (!curRule->getToSetup().empty()
&& !matchWildcard(curRule->getToSetup().c_str(), newsetup.c_str()))
continue;
// Found a match
return curRule;
}
// No matching rule was found
logger << "Warning: Conversion from '" << oldsetup << "' to '" << newsetup
<< "' undefined in setup matrix '" << getName() << endl;
return NULL;
}
} // end namespace
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2015 NoBNC
* Copyright (C) 2004-2015 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <nobnc/nomodule.h>
#include <nobnc/nochannel.h>
#include <nobnc/noregistry.h>
#include <nobnc/nonick.h>
#include <nobnc/noutils.h>
#include <nobnc/notable.h>
class NoAutoVoiceUser
{
public:
NoAutoVoiceUser()
{
}
NoAutoVoiceUser(const NoString& line)
{
FromString(line);
}
NoAutoVoiceUser(const NoString& username, const NoString& sHostmask, const NoString& sChannels)
: m_sUsername(username), m_sHostmask(sHostmask)
{
addChannels(sChannels);
}
const NoString& GetUsername() const
{
return m_sUsername;
}
const NoString& GetHostmask() const
{
return m_sHostmask;
}
bool ChannelMatches(const NoString& sChan) const
{
for (std::set<NoString>::const_iterator it = m_ssChans.begin(); it != m_ssChans.end(); ++it) {
if (No::wildCmp(sChan, *it, No::CaseInsensitive)) {
return true;
}
}
return false;
}
bool HostMatches(const NoString& sHostmask)
{
return No::wildCmp(sHostmask, m_sHostmask, No::CaseInsensitive);
}
NoString GetChannels() const
{
NoString ret;
for (std::set<NoString>::const_iterator it = m_ssChans.begin(); it != m_ssChans.end(); ++it) {
if (!ret.empty()) {
ret += " ";
}
ret += *it;
}
return ret;
}
void removeChannels(const NoString& sChans)
{
NoStringVector vsChans = sChans.split(" ");
for (uint a = 0; a < vsChans.size(); a++) {
m_ssChans.erase(vsChans[a].toLower());
}
}
void addChannels(const NoString& sChans)
{
NoStringVector vsChans = sChans.split(" ");
for (uint a = 0; a < vsChans.size(); a++) {
m_ssChans.insert(vsChans[a].toLower());
}
}
NoString ToString() const
{
NoString sChans;
for (std::set<NoString>::const_iterator it = m_ssChans.begin(); it != m_ssChans.end(); ++it) {
if (!sChans.empty()) {
sChans += " ";
}
sChans += *it;
}
return m_sUsername + "\t" + m_sHostmask + "\t" + sChans;
}
bool FromString(const NoString& line)
{
m_sUsername = No::token(line, 0, "\t");
m_sHostmask = No::token(line, 1, "\t");
NoStringVector vsChans = No::token(line, 2, "\t").split(" ");
m_ssChans = NoStringSet(vsChans.begin(), vsChans.end());
return !m_sHostmask.empty();
}
private:
protected:
NoString m_sUsername;
NoString m_sHostmask;
std::set<NoString> m_ssChans;
};
class NoAutoVoiceMod : public NoModule
{
public:
MODCONSTRUCTOR(NoAutoVoiceMod)
{
addHelpCommand();
addCommand("ListUsers",
static_cast<NoModule::CommandFunction>(&NoAutoVoiceMod::OnListUsersCommand),
"",
"List all users");
addCommand("addChannels",
static_cast<NoModule::CommandFunction>(&NoAutoVoiceMod::OnaddChannelsCommand),
"<user> <channel> [channel] ...",
"Adds channels to a user");
addCommand("removeChannels",
static_cast<NoModule::CommandFunction>(&NoAutoVoiceMod::OnremoveChannelsCommand),
"<user> <channel> [channel] ...",
"Removes channels from a user");
addCommand("AddUser",
static_cast<NoModule::CommandFunction>(&NoAutoVoiceMod::onAddUserCommand),
"<user> <hostmask> [channels]",
"Adds a user");
addCommand("DelUser",
static_cast<NoModule::CommandFunction>(&NoAutoVoiceMod::OnDelUserCommand),
"<user>",
"Removes a user");
}
bool onLoad(const NoString& args, NoString& message) override
{
// Load the chans from the command line
uint a = 0;
NoStringVector vsChans = args.split(" ", No::SkipEmptyParts);
for (NoStringVector::const_iterator it = vsChans.begin(); it != vsChans.end(); ++it) {
NoString name = "Args";
name += NoString(a);
AddUser(name, "*", *it);
}
// Load the saved users
NoRegistry registry(this);
for (const NoString& key : registry.keys()) {
const NoString& line = registry.value(key);
NoAutoVoiceUser* user = new NoAutoVoiceUser;
if (!user->FromString(line) || FindUser(user->GetUsername().toLower())) {
delete user;
} else {
m_msUsers[user->GetUsername().toLower()] = user;
}
}
return true;
}
virtual ~NoAutoVoiceMod()
{
for (std::map<NoString, NoAutoVoiceUser*>::iterator it = m_msUsers.begin(); it != m_msUsers.end(); ++it) {
delete it->second;
}
m_msUsers.clear();
}
void onJoin(const NoNick& nick, NoChannel* channel) override
{
// If we have ops in this chan
if (channel->hasPerm(NoChannel::Op) || channel->hasPerm(NoChannel::HalfOp)) {
for (std::map<NoString, NoAutoVoiceUser*>::iterator it = m_msUsers.begin(); it != m_msUsers.end(); ++it) {
// and the nick who joined is a valid user
if (it->second->HostMatches(nick.hostMask()) && it->second->ChannelMatches(channel->name())) {
putIrc("MODE " + channel->name() + " +v " + nick.nick());
break;
}
}
}
}
void onAddUserCommand(const NoString& line)
{
NoString sUser = No::token(line, 1);
NoString host = No::token(line, 2);
if (host.empty()) {
putModule("Usage: AddUser <user> <hostmask> [channels]");
} else {
NoAutoVoiceUser* user = AddUser(sUser, host, No::tokens(line, 3));
if (user) {
NoRegistry registry(this);
registry.setValue(sUser, user->ToString());
}
}
}
void OnDelUserCommand(const NoString& line)
{
NoString sUser = No::token(line, 1);
if (sUser.empty()) {
putModule("Usage: DelUser <user>");
} else {
DelUser(sUser);
NoRegistry registry(this);
registry.remove(sUser);
}
}
void OnListUsersCommand(const NoString& line)
{
if (m_msUsers.empty()) {
putModule("There are no users defined");
return;
}
NoTable Table;
Table.addColumn("User");
Table.addColumn("Hostmask");
Table.addColumn("Channels");
for (std::map<NoString, NoAutoVoiceUser*>::iterator it = m_msUsers.begin(); it != m_msUsers.end(); ++it) {
Table.addRow();
Table.setValue("User", it->second->GetUsername());
Table.setValue("Hostmask", it->second->GetHostmask());
Table.setValue("Channels", it->second->GetChannels());
}
putModule(Table);
}
void OnaddChannelsCommand(const NoString& line)
{
NoString sUser = No::token(line, 1);
NoString sChans = No::tokens(line, 2);
if (sChans.empty()) {
putModule("Usage: addChannels <user> <channel> [channel] ...");
return;
}
NoAutoVoiceUser* user = FindUser(sUser);
if (!user) {
putModule("No such user");
return;
}
user->addChannels(sChans);
putModule("channel(s) added to user [" + user->GetUsername() + "]");
NoRegistry registry(this);
registry.setValue(user->GetUsername(), user->ToString());
}
void OnremoveChannelsCommand(const NoString& line)
{
NoString sUser = No::token(line, 1);
NoString sChans = No::tokens(line, 2);
if (sChans.empty()) {
putModule("Usage: removeChannels <user> <channel> [channel] ...");
return;
}
NoAutoVoiceUser* user = FindUser(sUser);
if (!user) {
putModule("No such user");
return;
}
user->removeChannels(sChans);
putModule("channel(s) Removed from user [" + user->GetUsername() + "]");
NoRegistry registry(this);
registry.setValue(user->GetUsername(), user->ToString());
}
NoAutoVoiceUser* FindUser(const NoString& sUser)
{
std::map<NoString, NoAutoVoiceUser*>::iterator it = m_msUsers.find(sUser.toLower());
return (it != m_msUsers.end()) ? it->second : nullptr;
}
NoAutoVoiceUser* FindUserByHost(const NoString& sHostmask, const NoString& channel = "")
{
for (std::map<NoString, NoAutoVoiceUser*>::iterator it = m_msUsers.begin(); it != m_msUsers.end(); ++it) {
NoAutoVoiceUser* user = it->second;
if (user->HostMatches(sHostmask) && (channel.empty() || user->ChannelMatches(channel))) {
return user;
}
}
return nullptr;
}
void DelUser(const NoString& sUser)
{
std::map<NoString, NoAutoVoiceUser*>::iterator it = m_msUsers.find(sUser.toLower());
if (it == m_msUsers.end()) {
putModule("That user does not exist");
return;
}
delete it->second;
m_msUsers.erase(it);
putModule("User [" + sUser + "] removed");
}
NoAutoVoiceUser* AddUser(const NoString& sUser, const NoString& host, const NoString& sChans)
{
if (m_msUsers.find(sUser) != m_msUsers.end()) {
putModule("That user already exists");
return nullptr;
}
NoAutoVoiceUser* user = new NoAutoVoiceUser(sUser, host, sChans);
m_msUsers[sUser.toLower()] = user;
putModule("User [" + sUser + "] added with hostmask [" + host + "]");
return user;
}
private:
std::map<NoString, NoAutoVoiceUser*> m_msUsers;
};
template <>
void no_moduleInfo<NoAutoVoiceMod>(NoModuleInfo& info)
{
info.setWikiPage("autovoice");
info.setHasArgs(true);
info.setArgsHelpText("Each argument is either a channel you want autovoice for (which can include wildcards) or, "
"if it starts with !, it is an exception for autovoice.");
}
NETWORKMODULEDEFS(NoAutoVoiceMod, "Auto voice the good people")
<commit_msg>autovoice: reduce table columns to two<commit_after>/*
* Copyright (C) 2015 NoBNC
* Copyright (C) 2004-2015 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <nobnc/nomodule.h>
#include <nobnc/nochannel.h>
#include <nobnc/noregistry.h>
#include <nobnc/nonick.h>
#include <nobnc/noutils.h>
#include <nobnc/notable.h>
class NoAutoVoiceUser
{
public:
NoAutoVoiceUser()
{
}
NoAutoVoiceUser(const NoString& line)
{
FromString(line);
}
NoAutoVoiceUser(const NoString& username, const NoString& sHostmask, const NoString& sChannels)
: m_sUsername(username), m_sHostmask(sHostmask)
{
addChannels(sChannels);
}
const NoString& GetUsername() const
{
return m_sUsername;
}
const NoString& GetHostmask() const
{
return m_sHostmask;
}
bool ChannelMatches(const NoString& sChan) const
{
for (std::set<NoString>::const_iterator it = m_ssChans.begin(); it != m_ssChans.end(); ++it) {
if (No::wildCmp(sChan, *it, No::CaseInsensitive)) {
return true;
}
}
return false;
}
bool HostMatches(const NoString& sHostmask)
{
return No::wildCmp(sHostmask, m_sHostmask, No::CaseInsensitive);
}
NoString GetChannels() const
{
NoString ret;
for (std::set<NoString>::const_iterator it = m_ssChans.begin(); it != m_ssChans.end(); ++it) {
if (!ret.empty()) {
ret += " ";
}
ret += *it;
}
return ret;
}
void removeChannels(const NoString& sChans)
{
NoStringVector vsChans = sChans.split(" ");
for (uint a = 0; a < vsChans.size(); a++) {
m_ssChans.erase(vsChans[a].toLower());
}
}
void addChannels(const NoString& sChans)
{
NoStringVector vsChans = sChans.split(" ");
for (uint a = 0; a < vsChans.size(); a++) {
m_ssChans.insert(vsChans[a].toLower());
}
}
NoString ToString() const
{
NoString sChans;
for (std::set<NoString>::const_iterator it = m_ssChans.begin(); it != m_ssChans.end(); ++it) {
if (!sChans.empty()) {
sChans += " ";
}
sChans += *it;
}
return m_sUsername + "\t" + m_sHostmask + "\t" + sChans;
}
bool FromString(const NoString& line)
{
m_sUsername = No::token(line, 0, "\t");
m_sHostmask = No::token(line, 1, "\t");
NoStringVector vsChans = No::token(line, 2, "\t").split(" ");
m_ssChans = NoStringSet(vsChans.begin(), vsChans.end());
return !m_sHostmask.empty();
}
private:
protected:
NoString m_sUsername;
NoString m_sHostmask;
std::set<NoString> m_ssChans;
};
class NoAutoVoiceMod : public NoModule
{
public:
MODCONSTRUCTOR(NoAutoVoiceMod)
{
addHelpCommand();
addCommand("ListUsers",
static_cast<NoModule::CommandFunction>(&NoAutoVoiceMod::OnListUsersCommand),
"",
"List all users");
addCommand("addChannels",
static_cast<NoModule::CommandFunction>(&NoAutoVoiceMod::OnaddChannelsCommand),
"<user> <channel> [channel] ...",
"Adds channels to a user");
addCommand("removeChannels",
static_cast<NoModule::CommandFunction>(&NoAutoVoiceMod::OnremoveChannelsCommand),
"<user> <channel> [channel] ...",
"Removes channels from a user");
addCommand("AddUser",
static_cast<NoModule::CommandFunction>(&NoAutoVoiceMod::onAddUserCommand),
"<user> <hostmask> [channels]",
"Adds a user");
addCommand("DelUser",
static_cast<NoModule::CommandFunction>(&NoAutoVoiceMod::OnDelUserCommand),
"<user>",
"Removes a user");
}
bool onLoad(const NoString& args, NoString& message) override
{
// Load the chans from the command line
uint a = 0;
NoStringVector vsChans = args.split(" ", No::SkipEmptyParts);
for (NoStringVector::const_iterator it = vsChans.begin(); it != vsChans.end(); ++it) {
NoString name = "Args";
name += NoString(a);
AddUser(name, "*", *it);
}
// Load the saved users
NoRegistry registry(this);
for (const NoString& key : registry.keys()) {
const NoString& line = registry.value(key);
NoAutoVoiceUser* user = new NoAutoVoiceUser;
if (!user->FromString(line) || FindUser(user->GetUsername().toLower())) {
delete user;
} else {
m_msUsers[user->GetUsername().toLower()] = user;
}
}
return true;
}
virtual ~NoAutoVoiceMod()
{
for (std::map<NoString, NoAutoVoiceUser*>::iterator it = m_msUsers.begin(); it != m_msUsers.end(); ++it) {
delete it->second;
}
m_msUsers.clear();
}
void onJoin(const NoNick& nick, NoChannel* channel) override
{
// If we have ops in this chan
if (channel->hasPerm(NoChannel::Op) || channel->hasPerm(NoChannel::HalfOp)) {
for (std::map<NoString, NoAutoVoiceUser*>::iterator it = m_msUsers.begin(); it != m_msUsers.end(); ++it) {
// and the nick who joined is a valid user
if (it->second->HostMatches(nick.hostMask()) && it->second->ChannelMatches(channel->name())) {
putIrc("MODE " + channel->name() + " +v " + nick.nick());
break;
}
}
}
}
void onAddUserCommand(const NoString& line)
{
NoString sUser = No::token(line, 1);
NoString host = No::token(line, 2);
if (host.empty()) {
putModule("Usage: AddUser <user> <hostmask> [channels]");
} else {
NoAutoVoiceUser* user = AddUser(sUser, host, No::tokens(line, 3));
if (user) {
NoRegistry registry(this);
registry.setValue(sUser, user->ToString());
}
}
}
void OnDelUserCommand(const NoString& line)
{
NoString sUser = No::token(line, 1);
if (sUser.empty()) {
putModule("Usage: DelUser <user>");
} else {
DelUser(sUser);
NoRegistry registry(this);
registry.remove(sUser);
}
}
void OnListUsersCommand(const NoString& line)
{
if (m_msUsers.empty()) {
putModule("There are no users defined");
return;
}
NoTable Table;
Table.addColumn("User");
Table.addColumn("Hostmask (Channels)");
for (std::map<NoString, NoAutoVoiceUser*>::iterator it = m_msUsers.begin(); it != m_msUsers.end(); ++it) {
Table.addRow();
Table.setValue("User", it->second->GetUsername());
Table.setValue("Hostmask (Channels)", it->second->GetHostmask() + " (" + it->second->GetChannels() + ")");
}
putModule(Table);
}
void OnaddChannelsCommand(const NoString& line)
{
NoString sUser = No::token(line, 1);
NoString sChans = No::tokens(line, 2);
if (sChans.empty()) {
putModule("Usage: addChannels <user> <channel> [channel] ...");
return;
}
NoAutoVoiceUser* user = FindUser(sUser);
if (!user) {
putModule("No such user");
return;
}
user->addChannels(sChans);
putModule("channel(s) added to user [" + user->GetUsername() + "]");
NoRegistry registry(this);
registry.setValue(user->GetUsername(), user->ToString());
}
void OnremoveChannelsCommand(const NoString& line)
{
NoString sUser = No::token(line, 1);
NoString sChans = No::tokens(line, 2);
if (sChans.empty()) {
putModule("Usage: removeChannels <user> <channel> [channel] ...");
return;
}
NoAutoVoiceUser* user = FindUser(sUser);
if (!user) {
putModule("No such user");
return;
}
user->removeChannels(sChans);
putModule("channel(s) Removed from user [" + user->GetUsername() + "]");
NoRegistry registry(this);
registry.setValue(user->GetUsername(), user->ToString());
}
NoAutoVoiceUser* FindUser(const NoString& sUser)
{
std::map<NoString, NoAutoVoiceUser*>::iterator it = m_msUsers.find(sUser.toLower());
return (it != m_msUsers.end()) ? it->second : nullptr;
}
NoAutoVoiceUser* FindUserByHost(const NoString& sHostmask, const NoString& channel = "")
{
for (std::map<NoString, NoAutoVoiceUser*>::iterator it = m_msUsers.begin(); it != m_msUsers.end(); ++it) {
NoAutoVoiceUser* user = it->second;
if (user->HostMatches(sHostmask) && (channel.empty() || user->ChannelMatches(channel))) {
return user;
}
}
return nullptr;
}
void DelUser(const NoString& sUser)
{
std::map<NoString, NoAutoVoiceUser*>::iterator it = m_msUsers.find(sUser.toLower());
if (it == m_msUsers.end()) {
putModule("That user does not exist");
return;
}
delete it->second;
m_msUsers.erase(it);
putModule("User [" + sUser + "] removed");
}
NoAutoVoiceUser* AddUser(const NoString& sUser, const NoString& host, const NoString& sChans)
{
if (m_msUsers.find(sUser) != m_msUsers.end()) {
putModule("That user already exists");
return nullptr;
}
NoAutoVoiceUser* user = new NoAutoVoiceUser(sUser, host, sChans);
m_msUsers[sUser.toLower()] = user;
putModule("User [" + sUser + "] added with hostmask [" + host + "]");
return user;
}
private:
std::map<NoString, NoAutoVoiceUser*> m_msUsers;
};
template <>
void no_moduleInfo<NoAutoVoiceMod>(NoModuleInfo& info)
{
info.setWikiPage("autovoice");
info.setHasArgs(true);
info.setArgsHelpText("Each argument is either a channel you want autovoice for (which can include wildcards) or, "
"if it starts with !, it is an exception for autovoice.");
}
NETWORKMODULEDEFS(NoAutoVoiceMod, "Auto voice the good people")
<|endoftext|>
|
<commit_before>#include "modules/meta/base.hpp"
#include <utility>
#include "components/builder.hpp"
#include "drawtypes/label.hpp"
POLYBAR_NS
namespace modules {
// module_format {{{
string module_format::decorate(builder* builder, string output) {
if (output.empty()) {
builder->flush();
return "";
}
if (offset != 0) {
builder->offset(offset);
}
if (margin > 0) {
builder->space(margin);
}
if (bg.has_color()) {
builder->background(bg);
}
if (fg.has_color()) {
builder->color(fg);
}
if (ul.has_color()) {
builder->underline(ul);
}
if (ol.has_color()) {
builder->overline(ol);
}
if (font > 0) {
builder->font(font);
}
if (padding > 0) {
builder->space(padding);
}
builder->node(prefix);
if (bg.has_color()) {
builder->background(bg);
}
if (fg.has_color()) {
builder->color(fg);
}
if (ul.has_color()) {
builder->underline(ul);
}
if (ol.has_color()) {
builder->overline(ol);
}
builder->append(move(output));
builder->node(suffix);
if (padding > 0) {
builder->space(padding);
}
if (font > 0) {
builder->font_close();
}
if (ol.has_color()) {
builder->overline_close();
}
if (ul.has_color()) {
builder->underline_close();
}
if (fg.has_color()) {
builder->color_close();
}
if (bg.has_color()) {
builder->background_close();
}
if (margin > 0) {
builder->space(margin);
}
return builder->flush();
}
// }}}
// module_formatter {{{
void module_formatter::add_value(string&& name, string&& value, vector<string>&& tags, vector<string>&& whitelist) {
const auto formatdef = [&](
const string& param, const auto& fallback) { return m_conf.get("settings", "format-" + param, fallback); };
auto format = make_unique<module_format>();
format->value = move(value);
format->fg = m_conf.get(m_modname, name + "-foreground", formatdef("foreground", format->fg));
format->bg = m_conf.get(m_modname, name + "-background", formatdef("background", format->bg));
format->ul = m_conf.get(m_modname, name + "-underline", formatdef("underline", format->ul));
format->ol = m_conf.get(m_modname, name + "-overline", formatdef("overline", format->ol));
format->ulsize = m_conf.get(m_modname, name + "-underline-size", formatdef("underline-size", format->ulsize));
format->olsize = m_conf.get(m_modname, name + "-overline-size", formatdef("overline-size", format->olsize));
format->spacing = m_conf.get(m_modname, name + "-spacing", formatdef("spacing", format->spacing));
format->padding = m_conf.get(m_modname, name + "-padding", formatdef("padding", format->padding));
format->margin = m_conf.get(m_modname, name + "-margin", formatdef("margin", format->margin));
format->offset = m_conf.get(m_modname, name + "-offset", formatdef("offset", format->offset));
format->font = m_conf.get(m_modname, name + "-font", formatdef("font", format->font));
format->tags.swap(tags);
try {
format->prefix = load_label(m_conf, m_modname, name + "-prefix");
} catch (const key_error& err) {
// prefix not defined
}
try {
format->suffix = load_label(m_conf, m_modname, name + "-suffix");
} catch (const key_error& err) {
// suffix not defined
}
vector<string> tag_collection;
tag_collection.reserve(format->tags.size() + whitelist.size());
tag_collection.insert(tag_collection.end(), format->tags.begin(), format->tags.end());
tag_collection.insert(tag_collection.end(), whitelist.begin(), whitelist.end());
size_t start, end;
while ((start = value.find('<')) != string::npos && (end = value.find('>', start)) != string::npos) {
if (start > 0) {
value.erase(0, start);
end -= start;
start = 0;
}
string tag{value.substr(start, end + 1)};
if (find(tag_collection.begin(), tag_collection.end(), tag) == tag_collection.end()) {
throw undefined_format_tag(tag + " is not a valid format tag for \"" + name + "\"");
}
value.erase(0, tag.size());
}
m_formats.insert(make_pair(move(name), move(format)));
}
void module_formatter::add(string name, string fallback, vector<string>&& tags, vector<string>&& whitelist) {
add_value(move(name), m_conf.get(m_modname, move(name), move(fallback)), forward<vector<string>>(tags), forward<vector<string>>(whitelist));
}
void module_formatter::add_optional(string name, vector<string>&& tags, vector<string>&& whitelist) {
if (m_conf.has(m_modname, name)) {
add_value(move(name), m_conf.get(m_modname, move(name)), move(tags), move(whitelist));
}
}
bool module_formatter::has(const string& tag, const string& format_name) {
auto format = m_formats.find(format_name);
if (format == m_formats.end()) {
throw undefined_format(format_name);
}
return format->second->value.find(tag) != string::npos;
}
bool module_formatter::has(const string& tag) {
for (auto&& format : m_formats) {
if (format.second->value.find(tag) != string::npos) {
return true;
}
}
return false;
}
bool module_formatter::has_format(const string& format_name) {
return m_formats.find(format_name) != m_formats.end();
}
shared_ptr<module_format> module_formatter::get(const string& format_name) {
auto format = m_formats.find(format_name);
if (format == m_formats.end()) {
throw undefined_format("Format \"" + format_name + "\" has not been added");
}
return format->second;
}
// }}}
} // namespace modules
POLYBAR_NS_END
<commit_msg>fix(battery): Crash when `format-low` not defined<commit_after>#include "modules/meta/base.hpp"
#include <utility>
#include "components/builder.hpp"
#include "drawtypes/label.hpp"
POLYBAR_NS
namespace modules {
// module_format {{{
string module_format::decorate(builder* builder, string output) {
if (output.empty()) {
builder->flush();
return "";
}
if (offset != 0) {
builder->offset(offset);
}
if (margin > 0) {
builder->space(margin);
}
if (bg.has_color()) {
builder->background(bg);
}
if (fg.has_color()) {
builder->color(fg);
}
if (ul.has_color()) {
builder->underline(ul);
}
if (ol.has_color()) {
builder->overline(ol);
}
if (font > 0) {
builder->font(font);
}
if (padding > 0) {
builder->space(padding);
}
builder->node(prefix);
if (bg.has_color()) {
builder->background(bg);
}
if (fg.has_color()) {
builder->color(fg);
}
if (ul.has_color()) {
builder->underline(ul);
}
if (ol.has_color()) {
builder->overline(ol);
}
builder->append(move(output));
builder->node(suffix);
if (padding > 0) {
builder->space(padding);
}
if (font > 0) {
builder->font_close();
}
if (ol.has_color()) {
builder->overline_close();
}
if (ul.has_color()) {
builder->underline_close();
}
if (fg.has_color()) {
builder->color_close();
}
if (bg.has_color()) {
builder->background_close();
}
if (margin > 0) {
builder->space(margin);
}
return builder->flush();
}
// }}}
// module_formatter {{{
void module_formatter::add_value(string&& name, string&& value, vector<string>&& tags, vector<string>&& whitelist) {
const auto formatdef = [&](
const string& param, const auto& fallback) { return m_conf.get("settings", "format-" + param, fallback); };
auto format = make_unique<module_format>();
format->value = move(value);
format->fg = m_conf.get(m_modname, name + "-foreground", formatdef("foreground", format->fg));
format->bg = m_conf.get(m_modname, name + "-background", formatdef("background", format->bg));
format->ul = m_conf.get(m_modname, name + "-underline", formatdef("underline", format->ul));
format->ol = m_conf.get(m_modname, name + "-overline", formatdef("overline", format->ol));
format->ulsize = m_conf.get(m_modname, name + "-underline-size", formatdef("underline-size", format->ulsize));
format->olsize = m_conf.get(m_modname, name + "-overline-size", formatdef("overline-size", format->olsize));
format->spacing = m_conf.get(m_modname, name + "-spacing", formatdef("spacing", format->spacing));
format->padding = m_conf.get(m_modname, name + "-padding", formatdef("padding", format->padding));
format->margin = m_conf.get(m_modname, name + "-margin", formatdef("margin", format->margin));
format->offset = m_conf.get(m_modname, name + "-offset", formatdef("offset", format->offset));
format->font = m_conf.get(m_modname, name + "-font", formatdef("font", format->font));
format->tags.swap(tags);
try {
format->prefix = load_label(m_conf, m_modname, name + "-prefix");
} catch (const key_error& err) {
// prefix not defined
}
try {
format->suffix = load_label(m_conf, m_modname, name + "-suffix");
} catch (const key_error& err) {
// suffix not defined
}
vector<string> tag_collection;
tag_collection.reserve(format->tags.size() + whitelist.size());
tag_collection.insert(tag_collection.end(), format->tags.begin(), format->tags.end());
tag_collection.insert(tag_collection.end(), whitelist.begin(), whitelist.end());
size_t start, end;
while ((start = value.find('<')) != string::npos && (end = value.find('>', start)) != string::npos) {
if (start > 0) {
value.erase(0, start);
end -= start;
start = 0;
}
string tag{value.substr(start, end + 1)};
if (find(tag_collection.begin(), tag_collection.end(), tag) == tag_collection.end()) {
throw undefined_format_tag(tag + " is not a valid format tag for \"" + name + "\"");
}
value.erase(0, tag.size());
}
m_formats.insert(make_pair(move(name), move(format)));
}
void module_formatter::add(string name, string fallback, vector<string>&& tags, vector<string>&& whitelist) {
add_value(move(name), m_conf.get(m_modname, move(name), move(fallback)), forward<vector<string>>(tags), forward<vector<string>>(whitelist));
}
void module_formatter::add_optional(string name, vector<string>&& tags, vector<string>&& whitelist) {
if (m_conf.has(m_modname, name)) {
add_value(move(name), m_conf.get(m_modname, move(name)), move(tags), move(whitelist));
}
}
bool module_formatter::has(const string& tag, const string& format_name) {
auto format = m_formats.find(format_name);
if (format == m_formats.end()) {
return false;
}
return format->second->value.find(tag) != string::npos;
}
bool module_formatter::has(const string& tag) {
for (auto&& format : m_formats) {
if (format.second->value.find(tag) != string::npos) {
return true;
}
}
return false;
}
bool module_formatter::has_format(const string& format_name) {
return m_formats.find(format_name) != m_formats.end();
}
shared_ptr<module_format> module_formatter::get(const string& format_name) {
auto format = m_formats.find(format_name);
if (format == m_formats.end()) {
throw undefined_format("Format \"" + format_name + "\" has not been added");
}
return format->second;
}
// }}}
} // namespace modules
POLYBAR_NS_END
<|endoftext|>
|
<commit_before>//*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// 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.
//*****************************************************************************
#pragma once
#include "ngraph/op/op.hpp"
#include "ngraph/runtime/host_tensor.hpp"
namespace ngraph
{
namespace op
{
namespace v0
{
/// \brief Elementwise type conversion operation.
class NGRAPH_API Convert : public Op
{
public:
static constexpr NodeTypeInfo type_info{"Convert", 0};
const NodeTypeInfo& get_type_info() const override { return type_info; }
/// \brief Constructs a conversion operation.
Convert() = default;
/// \brief Constructs a conversion operation.
///
/// \param arg Node that produces the input tensor.
/// \param destination_type Element type for the output tensor.
Convert(const Output<Node>& arg, const ngraph::element::Type& destination_type);
void validate_and_infer_types() override;
bool visit_attributes(AttributeVisitor& visitor) override;
virtual std::shared_ptr<Node>
clone_with_new_inputs(const OutputVector& new_args) const override;
const element::Type& get_destination_type() const { return m_destination_type; }
void set_destination_type(const element::Type& destination_type)
{
m_destination_type = destination_type;
}
const element::Type& get_convert_element_type() const { return m_destination_type; }
void set_convert_element_type(const element::Type& destination_type)
{
m_destination_type = destination_type;
}
size_t get_version() const override { return 0; }
bool evaluate(const HostTensorVector& outputs,
const HostTensorVector& inputs) override;
protected:
ngraph::element::Type m_destination_type;
virtual void generate_adjoints(autodiff::Adjoints& adjoints,
const OutputVector& deltas) override;
};
}
using v0::Convert;
}
}
<commit_msg>Remove version api<commit_after>//*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// 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.
//*****************************************************************************
#pragma once
#include "ngraph/op/op.hpp"
#include "ngraph/runtime/host_tensor.hpp"
namespace ngraph
{
namespace op
{
namespace v0
{
/// \brief Elementwise type conversion operation.
class NGRAPH_API Convert : public Op
{
public:
static constexpr NodeTypeInfo type_info{"Convert", 0};
const NodeTypeInfo& get_type_info() const override { return type_info; }
/// \brief Constructs a conversion operation.
Convert() = default;
/// \brief Constructs a conversion operation.
///
/// \param arg Node that produces the input tensor.
/// \param destination_type Element type for the output tensor.
Convert(const Output<Node>& arg, const ngraph::element::Type& destination_type);
void validate_and_infer_types() override;
bool visit_attributes(AttributeVisitor& visitor) override;
virtual std::shared_ptr<Node>
clone_with_new_inputs(const OutputVector& new_args) const override;
const element::Type& get_destination_type() const { return m_destination_type; }
void set_destination_type(const element::Type& destination_type)
{
m_destination_type = destination_type;
}
const element::Type& get_convert_element_type() const { return m_destination_type; }
void set_convert_element_type(const element::Type& destination_type)
{
m_destination_type = destination_type;
}
bool evaluate(const HostTensorVector& outputs,
const HostTensorVector& inputs) override;
protected:
ngraph::element::Type m_destination_type;
virtual void generate_adjoints(autodiff::Adjoints& adjoints,
const OutputVector& deltas) override;
};
}
using v0::Convert;
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011-2021 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 <node/blockstorage.h>
#include <chain.h>
#include <chainparams.h>
#include <flatfile.h>
#include <fs.h>
#include <pow.h>
#include <shutdown.h>
#include <signet.h>
#include <streams.h>
#include <util/system.h>
#include <validation.h>
// From validation. TODO move here
bool FindBlockPos(FlatFilePos& pos, unsigned int nAddSize, unsigned int nHeight, CChain& active_chain, uint64_t nTime, bool fKnown = false);
static bool WriteBlockToDisk(const CBlock& block, FlatFilePos& pos, const CMessageHeader::MessageStartChars& messageStart)
{
// Open history file to append
CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
if (fileout.IsNull())
return error("WriteBlockToDisk: OpenBlockFile failed");
// Write index header
unsigned int nSize = GetSerializeSize(block, fileout.GetVersion());
fileout << messageStart << nSize;
// Write block
long fileOutPos = ftell(fileout.Get());
if (fileOutPos < 0)
return error("WriteBlockToDisk: ftell failed");
pos.nPos = (unsigned int)fileOutPos;
fileout << block;
return true;
}
bool ReadBlockFromDisk(CBlock& block, const FlatFilePos& pos, const Consensus::Params& consensusParams)
{
block.SetNull();
// Open history file to read
CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
if (filein.IsNull())
return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
// Read block
try {
filein >> block;
}
catch (const std::exception& e) {
return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
}
// Check the header
if (!CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))
return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
// Signet only: check block solution
if (consensusParams.signet_blocks && !CheckSignetBlockSolution(block, consensusParams)) {
return error("ReadBlockFromDisk: Errors in block solution at %s", pos.ToString());
}
return true;
}
bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
{
FlatFilePos blockPos;
{
LOCK(cs_main);
blockPos = pindex->GetBlockPos();
}
if (!ReadBlockFromDisk(block, blockPos, consensusParams))
return false;
if (block.GetHash() != pindex->GetBlockHash())
return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
pindex->ToString(), pindex->GetBlockPos().ToString());
return true;
}
bool ReadRawBlockFromDisk(std::vector<uint8_t>& block, const FlatFilePos& pos, const CMessageHeader::MessageStartChars& message_start)
{
FlatFilePos hpos = pos;
hpos.nPos -= 8; // Seek back 8 bytes for meta header
CAutoFile filein(OpenBlockFile(hpos, true), SER_DISK, CLIENT_VERSION);
if (filein.IsNull()) {
return error("%s: OpenBlockFile failed for %s", __func__, pos.ToString());
}
try {
CMessageHeader::MessageStartChars blk_start;
unsigned int blk_size;
filein >> blk_start >> blk_size;
if (memcmp(blk_start, message_start, CMessageHeader::MESSAGE_START_SIZE)) {
return error("%s: Block magic mismatch for %s: %s versus expected %s", __func__, pos.ToString(),
HexStr(blk_start),
HexStr(message_start));
}
if (blk_size > MAX_SIZE) {
return error("%s: Block data is larger than maximum deserialization size for %s: %s versus %s", __func__, pos.ToString(),
blk_size, MAX_SIZE);
}
block.resize(blk_size); // Zeroing of memory is intentional here
filein.read((char*)block.data(), blk_size);
} catch (const std::exception& e) {
return error("%s: Read from block file failed: %s for %s", __func__, e.what(), pos.ToString());
}
return true;
}
bool ReadRawBlockFromDisk(std::vector<uint8_t>& block, const CBlockIndex* pindex, const CMessageHeader::MessageStartChars& message_start)
{
FlatFilePos block_pos;
{
LOCK(cs_main);
block_pos = pindex->GetBlockPos();
}
return ReadRawBlockFromDisk(block, block_pos, message_start);
}
/** Store block on disk. If dbp is non-nullptr, the file is known to already reside on disk */
FlatFilePos SaveBlockToDisk(const CBlock& block, int nHeight, CChain& active_chain, const CChainParams& chainparams, const FlatFilePos* dbp)
{
unsigned int nBlockSize = ::GetSerializeSize(block, CLIENT_VERSION);
FlatFilePos blockPos;
if (dbp != nullptr)
blockPos = *dbp;
if (!FindBlockPos(blockPos, nBlockSize + 8, nHeight, active_chain, block.GetBlockTime(), dbp != nullptr)) {
error("%s: FindBlockPos failed", __func__);
return FlatFilePos();
}
if (dbp == nullptr) {
if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) {
AbortNode("Failed to write block");
return FlatFilePos();
}
}
return blockPos;
}
struct CImportingNow {
CImportingNow()
{
assert(fImporting == false);
fImporting = true;
}
~CImportingNow()
{
assert(fImporting == true);
fImporting = false;
}
};
void ThreadImport(ChainstateManager& chainman, std::vector<fs::path> vImportFiles, const ArgsManager& args)
{
const CChainParams& chainparams = Params();
ScheduleBatchPriority();
{
CImportingNow imp;
// -reindex
if (fReindex) {
int nFile = 0;
while (true) {
FlatFilePos pos(nFile, 0);
if (!fs::exists(GetBlockPosFilename(pos)))
break; // No block files left to reindex
FILE* file = OpenBlockFile(pos, true);
if (!file)
break; // This error is logged in OpenBlockFile
LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
::ChainstateActive().LoadExternalBlockFile(chainparams, file, &pos);
if (ShutdownRequested()) {
LogPrintf("Shutdown requested. Exit %s\n", __func__);
return;
}
nFile++;
}
pblocktree->WriteReindexing(false);
fReindex = false;
LogPrintf("Reindexing finished\n");
// To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
::ChainstateActive().LoadGenesisBlock(chainparams);
}
// -loadblock=
for (const fs::path& path : vImportFiles) {
FILE* file = fsbridge::fopen(path, "rb");
if (file) {
LogPrintf("Importing blocks file %s...\n", path.string());
::ChainstateActive().LoadExternalBlockFile(chainparams, file);
if (ShutdownRequested()) {
LogPrintf("Shutdown requested. Exit %s\n", __func__);
return;
}
} else {
LogPrintf("Warning: Could not open blocks file %s\n", path.string());
}
}
// scan for better chains in the block chain database, that are not yet connected in the active best chain
// We can't hold cs_main during ActivateBestChain even though we're accessing
// the chainman unique_ptrs since ABC requires us not to be holding cs_main, so retrieve
// the relevant pointers before the ABC call.
for (CChainState* chainstate : WITH_LOCK(::cs_main, return chainman.GetAll())) {
BlockValidationState state;
if (!chainstate->ActivateBestChain(state, chainparams, nullptr)) {
LogPrintf("Failed to connect best block (%s)\n", state.ToString());
StartShutdown();
return;
}
}
if (args.GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) {
LogPrintf("Stopping after block import\n");
StartShutdown();
return;
}
} // End scope of CImportingNow
chainman.ActiveChainstate().LoadMempool(args);
}
<commit_msg>blockstorage: [refactor] Use chainman reference where possible<commit_after>// Copyright (c) 2011-2021 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 <node/blockstorage.h>
#include <chain.h>
#include <chainparams.h>
#include <flatfile.h>
#include <fs.h>
#include <pow.h>
#include <shutdown.h>
#include <signet.h>
#include <streams.h>
#include <util/system.h>
#include <validation.h>
// From validation. TODO move here
bool FindBlockPos(FlatFilePos& pos, unsigned int nAddSize, unsigned int nHeight, CChain& active_chain, uint64_t nTime, bool fKnown = false);
static bool WriteBlockToDisk(const CBlock& block, FlatFilePos& pos, const CMessageHeader::MessageStartChars& messageStart)
{
// Open history file to append
CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
if (fileout.IsNull()) {
return error("WriteBlockToDisk: OpenBlockFile failed");
}
// Write index header
unsigned int nSize = GetSerializeSize(block, fileout.GetVersion());
fileout << messageStart << nSize;
// Write block
long fileOutPos = ftell(fileout.Get());
if (fileOutPos < 0) {
return error("WriteBlockToDisk: ftell failed");
}
pos.nPos = (unsigned int)fileOutPos;
fileout << block;
return true;
}
bool ReadBlockFromDisk(CBlock& block, const FlatFilePos& pos, const Consensus::Params& consensusParams)
{
block.SetNull();
// Open history file to read
CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
if (filein.IsNull()) {
return error("ReadBlockFromDisk: OpenBlockFile failed for %s", pos.ToString());
}
// Read block
try {
filein >> block;
} catch (const std::exception& e) {
return error("%s: Deserialize or I/O error - %s at %s", __func__, e.what(), pos.ToString());
}
// Check the header
if (!CheckProofOfWork(block.GetHash(), block.nBits, consensusParams)) {
return error("ReadBlockFromDisk: Errors in block header at %s", pos.ToString());
}
// Signet only: check block solution
if (consensusParams.signet_blocks && !CheckSignetBlockSolution(block, consensusParams)) {
return error("ReadBlockFromDisk: Errors in block solution at %s", pos.ToString());
}
return true;
}
bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams)
{
FlatFilePos blockPos;
{
LOCK(cs_main);
blockPos = pindex->GetBlockPos();
}
if (!ReadBlockFromDisk(block, blockPos, consensusParams)) {
return false;
}
if (block.GetHash() != pindex->GetBlockHash()) {
return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() doesn't match index for %s at %s",
pindex->ToString(), pindex->GetBlockPos().ToString());
}
return true;
}
bool ReadRawBlockFromDisk(std::vector<uint8_t>& block, const FlatFilePos& pos, const CMessageHeader::MessageStartChars& message_start)
{
FlatFilePos hpos = pos;
hpos.nPos -= 8; // Seek back 8 bytes for meta header
CAutoFile filein(OpenBlockFile(hpos, true), SER_DISK, CLIENT_VERSION);
if (filein.IsNull()) {
return error("%s: OpenBlockFile failed for %s", __func__, pos.ToString());
}
try {
CMessageHeader::MessageStartChars blk_start;
unsigned int blk_size;
filein >> blk_start >> blk_size;
if (memcmp(blk_start, message_start, CMessageHeader::MESSAGE_START_SIZE)) {
return error("%s: Block magic mismatch for %s: %s versus expected %s", __func__, pos.ToString(),
HexStr(blk_start),
HexStr(message_start));
}
if (blk_size > MAX_SIZE) {
return error("%s: Block data is larger than maximum deserialization size for %s: %s versus %s", __func__, pos.ToString(),
blk_size, MAX_SIZE);
}
block.resize(blk_size); // Zeroing of memory is intentional here
filein.read((char*)block.data(), blk_size);
} catch (const std::exception& e) {
return error("%s: Read from block file failed: %s for %s", __func__, e.what(), pos.ToString());
}
return true;
}
bool ReadRawBlockFromDisk(std::vector<uint8_t>& block, const CBlockIndex* pindex, const CMessageHeader::MessageStartChars& message_start)
{
FlatFilePos block_pos;
{
LOCK(cs_main);
block_pos = pindex->GetBlockPos();
}
return ReadRawBlockFromDisk(block, block_pos, message_start);
}
/** Store block on disk. If dbp is non-nullptr, the file is known to already reside on disk */
FlatFilePos SaveBlockToDisk(const CBlock& block, int nHeight, CChain& active_chain, const CChainParams& chainparams, const FlatFilePos* dbp)
{
unsigned int nBlockSize = ::GetSerializeSize(block, CLIENT_VERSION);
FlatFilePos blockPos;
if (dbp != nullptr) {
blockPos = *dbp;
}
if (!FindBlockPos(blockPos, nBlockSize + 8, nHeight, active_chain, block.GetBlockTime(), dbp != nullptr)) {
error("%s: FindBlockPos failed", __func__);
return FlatFilePos();
}
if (dbp == nullptr) {
if (!WriteBlockToDisk(block, blockPos, chainparams.MessageStart())) {
AbortNode("Failed to write block");
return FlatFilePos();
}
}
return blockPos;
}
struct CImportingNow {
CImportingNow()
{
assert(fImporting == false);
fImporting = true;
}
~CImportingNow()
{
assert(fImporting == true);
fImporting = false;
}
};
void ThreadImport(ChainstateManager& chainman, std::vector<fs::path> vImportFiles, const ArgsManager& args)
{
const CChainParams& chainparams = Params();
ScheduleBatchPriority();
{
CImportingNow imp;
// -reindex
if (fReindex) {
int nFile = 0;
while (true) {
FlatFilePos pos(nFile, 0);
if (!fs::exists(GetBlockPosFilename(pos))) {
break; // No block files left to reindex
}
FILE* file = OpenBlockFile(pos, true);
if (!file) {
break; // This error is logged in OpenBlockFile
}
LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
chainman.ActiveChainstate().LoadExternalBlockFile(chainparams, file, &pos);
if (ShutdownRequested()) {
LogPrintf("Shutdown requested. Exit %s\n", __func__);
return;
}
nFile++;
}
pblocktree->WriteReindexing(false);
fReindex = false;
LogPrintf("Reindexing finished\n");
// To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
chainman.ActiveChainstate().LoadGenesisBlock(chainparams);
}
// -loadblock=
for (const fs::path& path : vImportFiles) {
FILE* file = fsbridge::fopen(path, "rb");
if (file) {
LogPrintf("Importing blocks file %s...\n", path.string());
chainman.ActiveChainstate().LoadExternalBlockFile(chainparams, file);
if (ShutdownRequested()) {
LogPrintf("Shutdown requested. Exit %s\n", __func__);
return;
}
} else {
LogPrintf("Warning: Could not open blocks file %s\n", path.string());
}
}
// scan for better chains in the block chain database, that are not yet connected in the active best chain
// We can't hold cs_main during ActivateBestChain even though we're accessing
// the chainman unique_ptrs since ABC requires us not to be holding cs_main, so retrieve
// the relevant pointers before the ABC call.
for (CChainState* chainstate : WITH_LOCK(::cs_main, return chainman.GetAll())) {
BlockValidationState state;
if (!chainstate->ActivateBestChain(state, chainparams, nullptr)) {
LogPrintf("Failed to connect best block (%s)\n", state.ToString());
StartShutdown();
return;
}
}
if (args.GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) {
LogPrintf("Stopping after block import\n");
StartShutdown();
return;
}
} // End scope of CImportingNow
chainman.ActiveChainstate().LoadMempool(args);
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkOpts.h"
#define SK_OPTS_NS sk_sse41
#include "SkBlurImageFilter_opts.h"
namespace SkOpts {
void Init_sse41() {
box_blur_xx = sk_sse41::box_blur_xx;
box_blur_xy = sk_sse41::box_blur_xy;
box_blur_yx = sk_sse41::box_blur_yx;
}
}
<commit_msg>SSE 4.1 SrcOver blits: color32, blitmask.<commit_after>/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkOpts.h"
#define SK_OPTS_NS sk_sse41
#include "SkBlurImageFilter_opts.h"
#ifndef SK_SUPPORT_LEGACY_X86_BLITS
// This file deals mostly with unpacked 8-bit values,
// i.e. values between 0 and 255, but in 16-bit lanes with 0 at the top.
// So __m128i typically represents 1 or 2 pixels, and m128ix2 represents 4.
struct m128ix2 { __m128i lo, hi; };
// unpack{lo,hi}() get our raw pixels unpacked, from half of 4 packed pixels to 2 unpacked pixels.
static inline __m128i unpacklo(__m128i x) { return _mm_cvtepu8_epi16(x); }
static inline __m128i unpackhi(__m128i x) { return _mm_unpackhi_epi8(x, _mm_setzero_si128()); }
// pack() converts back, from 4 unpacked pixels to 4 packed pixels.
static inline __m128i pack(__m128i lo, __m128i hi) { return _mm_packus_epi16(lo, hi); }
// These nextN() functions abstract over the difference between iterating over
// an array of values and returning a constant value, for uint8_t and uint32_t.
// The nextN() taking pointers increment that pointer past where they read.
//
// nextN() returns N unpacked pixels or 4N unpacked coverage values.
static inline __m128i next1(uint8_t val) { return _mm_set1_epi16(val); }
static inline __m128i next2(uint8_t val) { return _mm_set1_epi16(val); }
static inline m128ix2 next4(uint8_t val) { return { next2(val), next2(val) }; }
static inline __m128i next1(uint32_t val) { return unpacklo(_mm_cvtsi32_si128(val)); }
static inline __m128i next2(uint32_t val) { return unpacklo(_mm_set1_epi32(val)); }
static inline m128ix2 next4(uint32_t val) { return { next2(val), next2(val) }; }
static inline __m128i next1(const uint8_t*& ptr) { return _mm_set1_epi16(*ptr++); }
static inline __m128i next2(const uint8_t*& ptr) {
auto r = _mm_cvtsi32_si128(*(const uint16_t*)ptr);
ptr += 2;
const int _ = ~0;
return _mm_shuffle_epi8(r, _mm_setr_epi8(0,_,0,_,0,_,0,_, 1,_,1,_,1,_,1,_));
}
static inline m128ix2 next4(const uint8_t*& ptr) {
auto r = _mm_cvtsi32_si128(*(const uint32_t*)ptr);
ptr += 4;
const int _ = ~0;
auto lo = _mm_shuffle_epi8(r, _mm_setr_epi8(0,_,0,_,0,_,0,_, 1,_,1,_,1,_,1,_)),
hi = _mm_shuffle_epi8(r, _mm_setr_epi8(2,_,2,_,2,_,2,_, 3,_,3,_,3,_,3,_));
return { lo, hi };
}
static inline __m128i next1(const uint32_t*& ptr) { return unpacklo(_mm_cvtsi32_si128(*ptr++)); }
static inline __m128i next2(const uint32_t*& ptr) {
auto r = unpacklo(_mm_loadl_epi64((const __m128i*)ptr));
ptr += 2;
return r;
}
static inline m128ix2 next4(const uint32_t*& ptr) {
auto packed = _mm_loadu_si128((const __m128i*)ptr);
ptr += 4;
return { unpacklo(packed), unpackhi(packed) };
}
// Divide by 255 with rounding.
// (x+127)/255 == ((x+128)*257)>>16.
// Sometimes we can be more efficient by breaking this into two parts.
static inline __m128i div255_part1(__m128i x) { return _mm_add_epi16(x, _mm_set1_epi16(128)); }
static inline __m128i div255_part2(__m128i x) { return _mm_mulhi_epu16(x, _mm_set1_epi16(257)); }
static inline __m128i div255(__m128i x) { return div255_part2(div255_part1(x)); }
// (x*y+127)/255, a byte multiply.
static inline __m128i scale(__m128i x, __m128i y) {
return div255(_mm_mullo_epi16(x, y));
}
// (255 - x).
static inline __m128i inv(__m128i x) {
return _mm_xor_si128(_mm_set1_epi16(0x00ff), x); // This seems a bit faster than _mm_sub_epi16.
}
// ARGB argb -> AAAA aaaa
static inline __m128i alphas(__m128i px) {
const int a = 2 * (SK_A32_SHIFT/8); // SK_A32_SHIFT is typically 24, so this is typically 6.
const int _ = ~0;
return _mm_shuffle_epi8(px, _mm_setr_epi8(a+0,_,a+0,_,a+0,_,a+0,_, a+8,_,a+8,_,a+8,_,a+8,_));
}
// For i = 0...n, tgt = fn(dst,src,cov), where Dst,Src,and Cov can be constants or arrays.
template <typename Dst, typename Src, typename Cov, typename Fn>
static inline void loop(int n, uint32_t* t, const Dst dst, const Src src, const Cov cov, Fn&& fn) {
// We don't want to muck with the callers' pointers, so we make them const and copy here.
Dst d = dst;
Src s = src;
Cov c = cov;
// Writing this as a single while-loop helps hoist loop invariants from fn.
while (n) {
if (n >= 4) {
auto d4 = next4(d),
s4 = next4(s),
c4 = next4(c);
auto lo = fn(d4.lo, s4.lo, c4.lo),
hi = fn(d4.hi, s4.hi, c4.hi);
_mm_storeu_si128((__m128i*)t, pack(lo,hi));
t += 4;
n -= 4;
continue;
}
if (n & 2) {
auto r = fn(next2(d), next2(s), next2(c));
_mm_storel_epi64((__m128i*)t, pack(r,r));
t += 2;
}
if (n & 1) {
auto r = fn(next1(d), next1(s), next1(c));
*t = _mm_cvtsi128_si32(pack(r,r));
}
return;
}
}
namespace sk_sse41 {
// SrcOver, with a constant source and full coverage.
static void blit_row_color32(SkPMColor* tgt, const SkPMColor* dst, int n, SkPMColor src) {
// We want to calculate s + (d * inv(alphas(s)) + 127)/255.
// We'd generally do that div255 as s + ((d * inv(alphas(s)) + 128)*257)>>16.
// But we can go one step further to ((s*255 + 128 + d*inv(alphas(s)))*257)>>16.
// This lets us hoist (s*255+128) and inv(alphas(s)) out of the loop.
__m128i s = next2(src),
s_255_128 = div255_part1(_mm_mullo_epi16(s, _mm_set1_epi16(255))),
A = inv(alphas(s));
const uint8_t cov = 0xff;
loop(n, tgt, dst, src, cov, [=](__m128i d, __m128i, __m128i) {
return div255_part2(_mm_add_epi16(s_255_128, _mm_mullo_epi16(d, A)));
});
}
// SrcOver, with a constant source and variable coverage.
// If the source is opaque, SrcOver becomes Src.
static void blit_mask_d32_a8(SkPMColor* dst, size_t dstRB,
const SkAlpha* cov, size_t covRB,
SkColor color, int w, int h) {
if (SkColorGetA(color) == 0xFF) {
const SkPMColor src = SkSwizzle_BGRA_to_PMColor(color);
while (h --> 0) {
loop(w, dst, (const SkPMColor*)dst, src, cov, [](__m128i d, __m128i s, __m128i c) {
// Src blend mode: a simple lerp from d to s by c.
// TODO: try a pmaddubsw version?
return div255(_mm_add_epi16(_mm_mullo_epi16(inv(c),d), _mm_mullo_epi16(c,s)));
});
dst += dstRB / sizeof(*dst);
cov += covRB / sizeof(*cov);
}
} else {
const SkPMColor src = SkPreMultiplyColor(color);
while (h --> 0) {
loop(w, dst, (const SkPMColor*)dst, src, cov, [](__m128i d, __m128i s, __m128i c) {
// SrcOver blend mode, with coverage folded into source alpha.
__m128i sc = scale(s,c),
AC = inv(alphas(sc));
return _mm_add_epi16(sc, scale(d,AC));
});
dst += dstRB / sizeof(*dst);
cov += covRB / sizeof(*cov);
}
}
}
} // namespace sk_sse41
#endif
namespace SkOpts {
void Init_sse41() {
box_blur_xx = sk_sse41::box_blur_xx;
box_blur_xy = sk_sse41::box_blur_xy;
box_blur_yx = sk_sse41::box_blur_yx;
#ifndef SK_SUPPORT_LEGACY_X86_BLITS
blit_row_color32 = sk_sse41::blit_row_color32;
blit_mask_d32_a8 = sk_sse41::blit_mask_d32_a8;
#endif
}
}
<|endoftext|>
|
<commit_before>#include <fstream>
#include <iostream>
#include <string>
#include <stack>
#include "create_dot.h"
struct Date {
uint32_t call_id = 0;
std::string region;
uint32_t invocations = 0;
uint32_t num_children = 0;
double min_incl_time = std::numeric_limits<uint64_t>::max();
double min_excl_time = std::numeric_limits<uint64_t>::max();
double max_incl_time = 0;
double max_excl_time = 0;
double sum_incl_time = 0;
double sum_excl_time = 0;
};
typedef std::vector<Date> Data;
Data data;
Data read_data(AllData& alldata){
Date date;
for (auto& region : alldata.call_path_tree) {
std::string func_name;
func_name = alldata.definitions.regions.get(region.function_id)->name;
date.region = func_name;
++date.call_id;
date.num_children = region.children.size();
// acumulate data over all locations
for (auto& location : region.node_data) {
date.invocations += location.second.f_data.count;
double incl_time = location.second.f_data.incl_time;
if (date.min_incl_time > incl_time)
date.min_incl_time = incl_time;
if (date.max_incl_time < incl_time)
date.max_incl_time = incl_time;
date.sum_incl_time += incl_time;
double excl_time = location.second.f_data.excl_time;
if (date.min_excl_time > excl_time)
date.min_excl_time = excl_time;
if (date.max_excl_time < excl_time)
date.max_excl_time = excl_time;
date.sum_excl_time += excl_time;
}
data.push_back(date);
}
return data;
};
void write_dot(Data data) {
std::stack<uint32_t> tmp;
std::ofstream result_file;
result_file.open ("result.dot");
result_file
<< "digraph call_tree {\n"
<< "graph [splines=ortho];\n"
<< "node [shape = record];\n"
<< "edge [];\n"
<< std::endl;
for ( auto& region : data ){
uint32_t call_id = region.call_id;
result_file
<< "\"" << call_id << "\" [\n"
<< "label = \""
<< "" << region.region << "\\l\n"
<< "invocations:" << region.invocations << "\\l\n"
<< "include time:" << "\\l\n"
<< "min: " << region.min_incl_time << "\\l\n"
<< "max: " << region.max_incl_time << "\\l\n"
<< "sum: " << region.sum_incl_time << "\\l\n"
<< "avg: " << region.sum_incl_time / region.invocations << "\\l\n"
<< "exclude time:" << "\\l\n"
<< "min: " << region.min_excl_time << "\\l\n"
<< "max: " << region.max_excl_time << "\\l\n"
<< "sum: " << region.sum_excl_time << "\\l\n"
<< "avg: " << region.sum_excl_time / region.invocations << "\\l\n"
<< "\"\n"
<< "];"
<< std::endl;
// if parent set connection
if( call_id != 1){
result_file
<< tmp.top()
<< " -> "
<< call_id
<< ";"
<< std::endl;
tmp.pop();
}
// trick to remember parents
for (int i = 0; i < region.num_children; ++i)
tmp.push(call_id);
}
result_file << "}" << std::endl;
};
bool CreateDot(AllData& alldata){
alldata.verbosePrint(1, true, "producing dot output");
Data data = read_data(alldata);
write_dot(data);
return true;
};<commit_msg>correct include and exclude time, add timerresolution<commit_after>#include <fstream>
#include <iostream>
#include <string>
#include <stack>
#include "create_dot.h"
struct Node {
uint32_t call_id = 0;
std::string region;
uint32_t invocations = 0;
uint32_t num_children = 0;
double min_incl_time = std::numeric_limits<uint64_t>::max();
double max_incl_time = 0;
double sum_incl_time = 0;
double min_excl_time = std::numeric_limits<uint64_t>::max();
double max_excl_time = 0;
double sum_excl_time = 0;
};
typedef std::vector<Node> Data;
Data read_data(AllData& alldata){
Data data;
for (auto& region : alldata.call_path_tree) {
Node node;
std::string region_name = alldata.definitions.regions.get(region.function_id)->name;
node.region = region_name;
node.num_children = region.children.size();
double timerResolution = (double)alldata.metaData.timerResolution;
// acumulate data over all locations
for (auto& location : region.node_data) {
node.invocations += location.second.f_data.count;
double incl_time = location.second.f_data.incl_time / timerResolution;
if (node.min_incl_time > incl_time)
node.min_incl_time = incl_time;
if (node.max_incl_time < incl_time)
node.max_incl_time = incl_time;
node.sum_incl_time += incl_time;
double excl_time = location.second.f_data.excl_time / timerResolution;
if (node.min_excl_time > excl_time)
node.min_excl_time = excl_time;
if (node.max_excl_time < excl_time)
node.max_excl_time = excl_time;
node.sum_excl_time += excl_time;
}
data.push_back(node);
}
return data;
};
void write_dot(Data data) {
std::stack<uint32_t> tmp;
int call_id = 0;
std::ofstream result_file;
result_file.open ("result.dot");
result_file
<< "digraph call_tree {\n"
<< "graph [splines=ortho];\n"
<< "node [shape = record];\n"
<< "edge [];\n"
<< std::endl;
for ( auto& region : data ){
result_file
<< "\"" << call_id << "\" [\n"
<< "label = \""
<< "" << region.region << "\\l\n"
<< "invocations:" << region.invocations << "\\l\n"
<< "include time:" << "\\l\n"
<< "min: " << region.min_incl_time << "\\l\n"
<< "max: " << region.max_incl_time << "\\l\n"
<< "sum: " << region.sum_incl_time << "\\l\n"
<< "avg: " << region.sum_incl_time / region.invocations << "\\l\n"
<< "exclude time:" << "\\l\n"
<< "min: " << region.min_excl_time << "\\l\n"
<< "max: " << region.max_excl_time << "\\l\n"
<< "sum: " << region.sum_excl_time << "\\l\n"
<< "avg: " << region.sum_excl_time / region.invocations << "\\l\n"
<< "\"\n"
<< "];"
<< std::endl;
// if parent set connection
if( call_id != 1){
result_file
<< tmp.top()
<< " -> "
<< call_id
<< ";"
<< std::endl;
tmp.pop();
}
// trick to remember parents
for (int i = 0; i < region.num_children; ++i)
tmp.push(call_id);
++call_id;
}
result_file << "}" << std::endl;
};
bool CreateDot(AllData& alldata){
alldata.verbosePrint(1, true, "producing dot output");
Data data = read_data(alldata);
write_dot(data);
return true;
};<|endoftext|>
|
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "common.h"
#ifdef HAVE_SDL
#include "SDLMedia.h"
#include "ErrorHandler.h"
#ifdef HALF_RATE_AUDIO
static const int defaultAudioRate=11025;
#else
static const int defaultAudioRate=22050;
#endif
//
// SDLMedia
//
SDLMedia::SDLMedia() : BzfMedia()
{
cmdFill = 0;
sndMutex = SDL_CreateMutex();
cmdMutex = SDL_CreateMutex();
fillCond = SDL_CreateCond();
wakeCond = SDL_CreateCond();
filledBuffer = false;
audioReady = false;
waitingData = false;
waitingWake = false;
}
SDLMedia::~SDLMedia()
{
SDL_DestroyCond(fillCond);
SDL_DestroyCond(wakeCond);
SDL_DestroyMutex(sndMutex);
}
double SDLMedia::stopwatch(bool start)
{
Uint32 currentTick = SDL_GetTicks(); //msec
if (start) {
stopwatchTime = currentTick;
return 0.0;
}
if (currentTick >= stopwatchTime)
return (double) (currentTick - stopwatchTime) * 0.001; // sec
else
//Clock is wrapped : happens after 49 days
//Should be "wrap value" - stopwatchtime. Now approx.
return (double) currentTick * 0.001;
}
void SDLMedia::sleep(float timeInSeconds)
{
// Not used ... however ... here it is
SDL_Delay((Uint32) (timeInSeconds * 1000.0));
}
bool SDLMedia::openAudio()
{
// don't re-initialize
if (audioReady) return false;
if (SDL_InitSubSystem(SDL_INIT_AUDIO) == -1) {
printFatalError("Could not initialize SDL-Audio: %s.\n", SDL_GetError());
exit(-1);
};
static SDL_AudioSpec desired;
// what the frequency?
audioOutputRate = defaultAudioRate;
// how big a fragment to use? we want to hold at around 1/10th of
// a second.
int fragmentSize = (int)(0.08f * (float)audioOutputRate);
int n;
n = 0;
while ((1 << n) < fragmentSize)
++n;
// samples are two bytes each so double the size
audioBufferSize = 1 << (n + 1);
desired.freq = audioOutputRate;
desired.format = AUDIO_S16SYS;
desired.channels = 2;
desired.samples = audioBufferSize >> 1; // In stereo samples
desired.callback = &fillAudioWrapper;
desired.userdata = (void *) this; // To handle Wrap of func
/* Open the audio device, forcing the desired format */
if (SDL_OpenAudio(&desired, NULL) < 0) {
fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError());
return false;
}
// make an output buffer
outputBuffer = new short[audioBufferSize];
// Stop sending silence and start calling audio callback
SDL_PauseAudio(0);
// ready to go
audioReady = true;
return true;
}
void SDLMedia::closeAudio()
{
// Stop Audio to avoid callback
SDL_PauseAudio(1);
// Trying to cleanly wake up and exit the eventually running callback
if (SDL_mutexP(sndMutex) == -1) {
fprintf(stderr, "Couldn't lock mutex\n");
exit(-1);
}
filledBuffer = true;
if (waitingData)
// Signal data are there - fake data but who cares
if (SDL_CondSignal(fillCond) == -1) {
fprintf(stderr, "Couldn't Cond Signal\n");
exit(-1);
};
if (SDL_mutexV(sndMutex) == -1) {
fprintf(stderr, "Couldn't unlock mutex\n");
exit(-1);
}
SDL_CloseAudio();
delete [] outputBuffer;
outputBuffer = 0;
SDL_QuitSubSystem(SDL_INIT_AUDIO);
audioReady = false;
}
bool SDLMedia::startAudioThread(
void (*proc)(void*), void* data)
{
ThreadId = SDL_CreateThread( (int (*) (void *))proc, data);
return ThreadId != NULL;
}
void SDLMedia::stopAudioThread()
{
SDL_KillThread(ThreadId);
}
bool SDLMedia::hasAudioThread() const
{
return true;
}
void SDLMedia::writeSoundCommand(const void* cmd, int len)
{
if (!audioReady) return;
if (SDL_mutexP(cmdMutex) == -1) {
fprintf(stderr, "Couldn't lock mutex\n");
exit(-1);
}
// Discard command if full
if ((cmdFill + len) < 2048) {
memcpy(&cmdQueue[cmdFill], cmd, len);
// We should awake audioSleep - but game become unplayable
// using here an SDL_CondSignal(wakeCond)
cmdFill += len;
}
if (SDL_mutexV(cmdMutex) == -1) {
fprintf(stderr, "Couldn't unlock mutex\n");
exit(-1);
}
}
bool SDLMedia::readSoundCommand(void* cmd, int len)
{
bool result = false;
if (SDL_mutexP(cmdMutex) == -1) {
fprintf(stderr, "Couldn't lock mutex\n");
exit(-1);
}
if (cmdFill >= len) {
memcpy(cmd, cmdQueue, len);
// repack list of command waiting to be processed
memmove(cmdQueue, &cmdQueue[len], cmdFill - len);
cmdFill -= len;
result = true;
}
if (SDL_mutexV(cmdMutex) == -1) {
fprintf(stderr, "Couldn't unlock mutex\n");
exit(-1);
}
return result;
}
int SDLMedia::getAudioOutputRate() const
{
return audioOutputRate;
}
int SDLMedia::getAudioBufferSize() const
{
return audioBufferSize;
}
int SDLMedia::getAudioBufferChunkSize() const
{
return audioBufferSize>>1;
}
bool SDLMedia::isAudioTooEmpty() const
{
return !filledBuffer;
}
void SDLMedia::fillAudio (Uint8 * stream, int len)
{
Uint8* soundBuffer = stream;
if (SDL_mutexP(sndMutex) == -1) {
fprintf(stderr, "Couldn't lock mutex\n");
exit(-1);
}
while (!filledBuffer) {
// Hurry up. We need data soon
waitingData = true;
if (waitingWake)
// Signal we are waiting for data and
if (SDL_CondSignal(wakeCond) == -1) {
fprintf(stderr, "Couldn't Cond Signal\n");
exit(-1);
};
// wait for someone to fill data
while (SDL_CondWait(fillCond, sndMutex) == -1) ;
}
waitingData = false;
if (SDL_mutexV(sndMutex) == -1) {
fprintf(stderr, "Couldn't unlock mutex\n");
exit(-1);
}
int transferSize = (audioBufferSize - sampleToSend) * 2;
if (transferSize > len)
transferSize = len;
// just copying into the soundBuffer is enough, SDL is looking for
// something different from silence sample
memcpy(soundBuffer,
(Uint8 *) &outputBuffer[sampleToSend],
transferSize);
sampleToSend += transferSize / 2;
soundBuffer += transferSize;
len -= transferSize;
if (sampleToSend == audioBufferSize) {
filledBuffer = false;
}
}
void SDLMedia::fillAudioWrapper (void * userdata, Uint8 * stream, int len)
{
SDLMedia * me = (SDLMedia *) userdata;
me->fillAudio(stream, len);
};
void SDLMedia::writeAudioFrames(
const float* samples, int numFrames)
{
int numSamples = 2 * numFrames;
int limit;
if (filledBuffer) {
fprintf(stderr, "Called but buffer is already filled\n");
return;
}
while (numSamples > 0) {
if (numSamples>audioBufferSize)
limit=audioBufferSize;
else
limit=numSamples;
for (int j = 0; j < limit; j++) {
if (samples[j] < -32767.0)
outputBuffer[j] = -32767;
else
if (samples[j] > 32767.0)
outputBuffer[j] = 32767;
else
outputBuffer[j] = short(samples[j]);
}
// fill out the chunk (we never write a partial chunk)
if (limit < audioBufferSize) {
for (int j = limit; j < audioBufferSize; ++j)
outputBuffer[j] = 0;
}
if (SDL_mutexP(sndMutex) == -1) {
fprintf(stderr, "Couldn't lock mutex\n");
exit(-1);
}
filledBuffer = true;
sampleToSend = 0;
if (waitingData)
if (SDL_CondSignal(fillCond) == -1) {
fprintf(stderr, "Couldn't Cond Signal\n");
exit(-1);
};
if (SDL_mutexV(sndMutex) == -1) {
fprintf(stderr, "Couldn't unlock mutex\n");
exit(-1);
}
samples += audioBufferSize;
numSamples -= audioBufferSize;
}
}
void SDLMedia::audioSleep(bool, double endTime)
{
if (SDL_mutexP(sndMutex) == -1) {
fprintf(stderr, "Couldn't lock mutex\n");
exit(-1);
}
if ((cmdFill <= 0) && filledBuffer) {
waitingWake = true;
if (endTime < 0.0) {
if (SDL_CondWait(wakeCond, sndMutex) == -1) {
fprintf(stderr, "Couldn't CondWait on wakeCond\n");
exit(-1);
};
} else {
if (SDL_CondWaitTimeout(wakeCond,
sndMutex,
(int) (1.0e3 * endTime)) == -1) {
fprintf(stderr, "Couldn't CondWaitTimeout on wakeCond\n");
exit(-1);
};
}
waitingWake = false;
}
if (SDL_mutexV(sndMutex) == -1) {
fprintf(stderr, "Couldn't unlock mutex\n");
exit(-1);
}
}
// Setting Audio Driver
void SDLMedia::setDriver(std::string driverName) {
setenv("SDL_AUDIODRIVER", driverName.c_str(), 0);
};
// Setting Audio Device
void SDLMedia::setDevice(std::string) {
};
#endif //HAVE_SDL
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>Changing KillThread to WaitThread to avoid lock on exit<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "common.h"
#ifdef HAVE_SDL
#include "SDLMedia.h"
#include "ErrorHandler.h"
#ifdef HALF_RATE_AUDIO
static const int defaultAudioRate=11025;
#else
static const int defaultAudioRate=22050;
#endif
//
// SDLMedia
//
SDLMedia::SDLMedia() : BzfMedia()
{
cmdFill = 0;
sndMutex = SDL_CreateMutex();
cmdMutex = SDL_CreateMutex();
fillCond = SDL_CreateCond();
wakeCond = SDL_CreateCond();
filledBuffer = false;
audioReady = false;
waitingData = false;
waitingWake = false;
}
SDLMedia::~SDLMedia()
{
SDL_DestroyCond(fillCond);
SDL_DestroyCond(wakeCond);
SDL_DestroyMutex(sndMutex);
}
double SDLMedia::stopwatch(bool start)
{
Uint32 currentTick = SDL_GetTicks(); //msec
if (start) {
stopwatchTime = currentTick;
return 0.0;
}
if (currentTick >= stopwatchTime)
return (double) (currentTick - stopwatchTime) * 0.001; // sec
else
//Clock is wrapped : happens after 49 days
//Should be "wrap value" - stopwatchtime. Now approx.
return (double) currentTick * 0.001;
}
void SDLMedia::sleep(float timeInSeconds)
{
// Not used ... however ... here it is
SDL_Delay((Uint32) (timeInSeconds * 1000.0));
}
bool SDLMedia::openAudio()
{
// don't re-initialize
if (audioReady) return false;
if (SDL_InitSubSystem(SDL_INIT_AUDIO) == -1) {
printFatalError("Could not initialize SDL-Audio: %s.\n", SDL_GetError());
exit(-1);
};
static SDL_AudioSpec desired;
// what the frequency?
audioOutputRate = defaultAudioRate;
// how big a fragment to use? we want to hold at around 1/10th of
// a second.
int fragmentSize = (int)(0.08f * (float)audioOutputRate);
int n;
n = 0;
while ((1 << n) < fragmentSize)
++n;
// samples are two bytes each so double the size
audioBufferSize = 1 << (n + 1);
desired.freq = audioOutputRate;
desired.format = AUDIO_S16SYS;
desired.channels = 2;
desired.samples = audioBufferSize >> 1; // In stereo samples
desired.callback = &fillAudioWrapper;
desired.userdata = (void *) this; // To handle Wrap of func
/* Open the audio device, forcing the desired format */
if (SDL_OpenAudio(&desired, NULL) < 0) {
fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError());
return false;
}
// make an output buffer
outputBuffer = new short[audioBufferSize];
// Stop sending silence and start calling audio callback
SDL_PauseAudio(0);
// ready to go
audioReady = true;
return true;
}
void SDLMedia::closeAudio()
{
// Stop Audio to avoid callback
SDL_PauseAudio(1);
// Trying to cleanly wake up and exit the eventually running callback
if (SDL_mutexP(sndMutex) == -1) {
fprintf(stderr, "Couldn't lock mutex\n");
exit(-1);
}
filledBuffer = true;
if (waitingData)
// Signal data are there - fake data but who cares
if (SDL_CondSignal(fillCond) == -1) {
fprintf(stderr, "Couldn't Cond Signal\n");
exit(-1);
};
if (SDL_mutexV(sndMutex) == -1) {
fprintf(stderr, "Couldn't unlock mutex\n");
exit(-1);
}
SDL_CloseAudio();
delete [] outputBuffer;
outputBuffer = 0;
SDL_QuitSubSystem(SDL_INIT_AUDIO);
audioReady = false;
}
bool SDLMedia::startAudioThread(
void (*proc)(void*), void* data)
{
ThreadId = SDL_CreateThread( (int (*) (void *))proc, data);
return ThreadId != NULL;
}
void SDLMedia::stopAudioThread()
{
SDL_WaitThread(ThreadId, NULL);
}
bool SDLMedia::hasAudioThread() const
{
return true;
}
void SDLMedia::writeSoundCommand(const void* cmd, int len)
{
if (!audioReady) return;
if (SDL_mutexP(cmdMutex) == -1) {
fprintf(stderr, "Couldn't lock mutex\n");
exit(-1);
}
// Discard command if full
if ((cmdFill + len) < 2048) {
memcpy(&cmdQueue[cmdFill], cmd, len);
// We should awake audioSleep - but game become unplayable
// using here an SDL_CondSignal(wakeCond)
cmdFill += len;
}
if (SDL_mutexV(cmdMutex) == -1) {
fprintf(stderr, "Couldn't unlock mutex\n");
exit(-1);
}
}
bool SDLMedia::readSoundCommand(void* cmd, int len)
{
bool result = false;
if (SDL_mutexP(cmdMutex) == -1) {
fprintf(stderr, "Couldn't lock mutex\n");
exit(-1);
}
if (cmdFill >= len) {
memcpy(cmd, cmdQueue, len);
// repack list of command waiting to be processed
memmove(cmdQueue, &cmdQueue[len], cmdFill - len);
cmdFill -= len;
result = true;
}
if (SDL_mutexV(cmdMutex) == -1) {
fprintf(stderr, "Couldn't unlock mutex\n");
exit(-1);
}
return result;
}
int SDLMedia::getAudioOutputRate() const
{
return audioOutputRate;
}
int SDLMedia::getAudioBufferSize() const
{
return audioBufferSize;
}
int SDLMedia::getAudioBufferChunkSize() const
{
return audioBufferSize>>1;
}
bool SDLMedia::isAudioTooEmpty() const
{
return !filledBuffer;
}
void SDLMedia::fillAudio (Uint8 * stream, int len)
{
Uint8* soundBuffer = stream;
if (SDL_mutexP(sndMutex) == -1) {
fprintf(stderr, "Couldn't lock mutex\n");
exit(-1);
}
while (!filledBuffer) {
// Hurry up. We need data soon
waitingData = true;
if (waitingWake)
// Signal we are waiting for data and
if (SDL_CondSignal(wakeCond) == -1) {
fprintf(stderr, "Couldn't Cond Signal\n");
exit(-1);
};
// wait for someone to fill data
while (SDL_CondWait(fillCond, sndMutex) == -1) ;
}
waitingData = false;
if (SDL_mutexV(sndMutex) == -1) {
fprintf(stderr, "Couldn't unlock mutex\n");
exit(-1);
}
int transferSize = (audioBufferSize - sampleToSend) * 2;
if (transferSize > len)
transferSize = len;
// just copying into the soundBuffer is enough, SDL is looking for
// something different from silence sample
memcpy(soundBuffer,
(Uint8 *) &outputBuffer[sampleToSend],
transferSize);
sampleToSend += transferSize / 2;
soundBuffer += transferSize;
len -= transferSize;
if (sampleToSend == audioBufferSize) {
filledBuffer = false;
}
}
void SDLMedia::fillAudioWrapper (void * userdata, Uint8 * stream, int len)
{
SDLMedia * me = (SDLMedia *) userdata;
me->fillAudio(stream, len);
};
void SDLMedia::writeAudioFrames(
const float* samples, int numFrames)
{
int numSamples = 2 * numFrames;
int limit;
if (filledBuffer) {
fprintf(stderr, "Called but buffer is already filled\n");
return;
}
while (numSamples > 0) {
if (numSamples>audioBufferSize)
limit=audioBufferSize;
else
limit=numSamples;
for (int j = 0; j < limit; j++) {
if (samples[j] < -32767.0)
outputBuffer[j] = -32767;
else
if (samples[j] > 32767.0)
outputBuffer[j] = 32767;
else
outputBuffer[j] = short(samples[j]);
}
// fill out the chunk (we never write a partial chunk)
if (limit < audioBufferSize) {
for (int j = limit; j < audioBufferSize; ++j)
outputBuffer[j] = 0;
}
if (SDL_mutexP(sndMutex) == -1) {
fprintf(stderr, "Couldn't lock mutex\n");
exit(-1);
}
filledBuffer = true;
sampleToSend = 0;
if (waitingData)
if (SDL_CondSignal(fillCond) == -1) {
fprintf(stderr, "Couldn't Cond Signal\n");
exit(-1);
};
if (SDL_mutexV(sndMutex) == -1) {
fprintf(stderr, "Couldn't unlock mutex\n");
exit(-1);
}
samples += audioBufferSize;
numSamples -= audioBufferSize;
}
}
void SDLMedia::audioSleep(bool, double endTime)
{
if (SDL_mutexP(sndMutex) == -1) {
fprintf(stderr, "Couldn't lock mutex\n");
exit(-1);
}
if ((cmdFill <= 0) && filledBuffer) {
waitingWake = true;
if (endTime < 0.0) {
if (SDL_CondWait(wakeCond, sndMutex) == -1) {
fprintf(stderr, "Couldn't CondWait on wakeCond\n");
exit(-1);
};
} else {
if (SDL_CondWaitTimeout(wakeCond,
sndMutex,
(int) (1.0e3 * endTime)) == -1) {
fprintf(stderr, "Couldn't CondWaitTimeout on wakeCond\n");
exit(-1);
};
}
waitingWake = false;
}
if (SDL_mutexV(sndMutex) == -1) {
fprintf(stderr, "Couldn't unlock mutex\n");
exit(-1);
}
}
// Setting Audio Driver
void SDLMedia::setDriver(std::string driverName) {
setenv("SDL_AUDIODRIVER", driverName.c_str(), 0);
};
// Setting Audio Device
void SDLMedia::setDevice(std::string) {
};
#endif //HAVE_SDL
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before>// Copyright (c) 2011-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "lookuptxdialog.h"
#include "ui_lookuptxdialog.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include "wallet.h"
#include "base58.h"
#include "ui_interface.h"
#include <boost/filesystem.hpp>
#include "leveldb/db.h"
#include "leveldb/write_batch.h"
// potentially overzealous includes here
#include "base58.h"
#include "rpcserver.h"
#include "init.h"
#include "util.h"
#include <fstream>
#include <algorithm>
#include <vector>
#include <utility>
#include <string>
#include <boost/assign/list_of.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/find.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/format.hpp>
#include <boost/filesystem.hpp>
#include "json/json_spirit_utils.h"
#include "json/json_spirit_value.h"
#include "leveldb/db.h"
#include "leveldb/write_batch.h"
// end potentially overzealous includes
using namespace json_spirit;
#include "mastercore.h"
using namespace mastercore;
// potentially overzealous using here
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace leveldb;
// end potentially overzealous using
#include "mastercore_dex.h"
#include "mastercore_tx.h"
#include "mastercore_sp.h"
#include "mastercore_rpc.h"
#include <QMessageBox>
#include <QScrollBar>
#include <QTextDocument>
#include <QClipboard>
#include <QDrag>
#include <QMimeData>
#include <QMouseEvent>
#include <QPixmap>
#include <QMenu>
#if QT_VERSION < 0x050000
#include <QUrl>
#endif
LookupTXDialog::LookupTXDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::LookupTXDialog),
model(0)
{
ui->setupUi(this);
this->model = model;
#if QT_VERSION >= 0x040700
// populate placeholder text
ui->searchLineEdit->setPlaceholderText("Search transaction");
#endif
// connect actions
connect(ui->searchButton, SIGNAL(clicked()), this, SLOT(searchButtonClicked()));
}
void LookupTXDialog::searchTX()
{
// search function to lookup address
string searchText = ui->searchLineEdit->text().toStdString();
// first let's check if we have a searchText, if not do nothing
if (searchText.empty()) return;
uint256 hash;
hash.SetHex(searchText);
Object txobj;
// make a request to new RPC populator function to populate a transaction object
int populateResult = populateRPCTransactionObject(hash, &txobj, "");
if (0<=populateResult)
{
std::string strTXText = write_string(Value(txobj), false) + "\n";
// clean up
string from = ",";
string to = ",\n ";
size_t start_pos = 0;
while((start_pos = strTXText.find(from, start_pos)) != std::string::npos)
{
strTXText.replace(start_pos, from.length(), to);
start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
}
from = ":";
to = " : ";
start_pos = 0;
while((start_pos = strTXText.find(from, start_pos)) != std::string::npos)
{
strTXText.replace(start_pos, from.length(), to);
start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
}
from = "{";
to = "{\n ";
start_pos = 0;
while((start_pos = strTXText.find(from, start_pos)) != std::string::npos)
{
strTXText.replace(start_pos, from.length(), to);
start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
}
from = "}";
to = "\n}";
start_pos = 0;
while((start_pos = strTXText.find(from, start_pos)) != std::string::npos)
{
strTXText.replace(start_pos, from.length(), to);
start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
}
QString txText = QString::fromStdString(strTXText);
QDialog *txDlg = new QDialog;
QLayout *dlgLayout = new QVBoxLayout;
dlgLayout->setSpacing(12);
dlgLayout->setMargin(12);
QTextEdit *dlgTextEdit = new QTextEdit;
dlgTextEdit->setText(txText);
dlgTextEdit->setStatusTip("Transaction Information");
dlgLayout->addWidget(dlgTextEdit);
txDlg->setWindowTitle("Transaction Information");
QPushButton *closeButton = new QPushButton(tr("&Close"));
closeButton->setDefault(true);
QDialogButtonBox *buttonBox = new QDialogButtonBox;
buttonBox->addButton(closeButton, QDialogButtonBox::AcceptRole);
dlgLayout->addWidget(buttonBox);
txDlg->setLayout(dlgLayout);
txDlg->resize(700, 360);
connect(buttonBox, SIGNAL(accepted()), txDlg, SLOT(accept()));
txDlg->setAttribute(Qt::WA_DeleteOnClose); //delete once it's closed
if (txDlg->exec() == QDialog::Accepted) { } else { } //do nothing but close
}
else
{
// show error message
string strText = "The transaction ID entered is either not valid Omni transaction or has not yet been confirmed.";
QString strQText = QString::fromStdString(strText);
QMessageBox errorDialog;
errorDialog.setIcon(QMessageBox::Critical);
errorDialog.setWindowTitle("TXID error");
errorDialog.setText(strQText);
errorDialog.setStandardButtons(QMessageBox::Ok);
errorDialog.setDefaultButton(QMessageBox::Ok);
if(errorDialog.exec() == QMessageBox::Ok) { } // no other button to choose, acknowledged
}
}
void LookupTXDialog::searchButtonClicked()
{
searchTX();
}
<commit_msg>Be more descriptive with transaction lookup errors<commit_after>// Copyright (c) 2011-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "lookuptxdialog.h"
#include "ui_lookuptxdialog.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include "wallet.h"
#include "base58.h"
#include "ui_interface.h"
#include <boost/filesystem.hpp>
#include "leveldb/db.h"
#include "leveldb/write_batch.h"
// potentially overzealous includes here
#include "base58.h"
#include "rpcserver.h"
#include "init.h"
#include "util.h"
#include <fstream>
#include <algorithm>
#include <vector>
#include <utility>
#include <string>
#include <boost/assign/list_of.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/find.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/format.hpp>
#include <boost/filesystem.hpp>
#include "json/json_spirit_utils.h"
#include "json/json_spirit_value.h"
#include "leveldb/db.h"
#include "leveldb/write_batch.h"
// end potentially overzealous includes
using namespace json_spirit;
#include "mastercore.h"
using namespace mastercore;
// potentially overzealous using here
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace leveldb;
// end potentially overzealous using
#include "mastercore_dex.h"
#include "mastercore_tx.h"
#include "mastercore_sp.h"
#include "mastercore_rpc.h"
#include "mastercore_errors.h"
#include <QMessageBox>
#include <QScrollBar>
#include <QTextDocument>
#include <QClipboard>
#include <QDrag>
#include <QMimeData>
#include <QMouseEvent>
#include <QPixmap>
#include <QMenu>
#if QT_VERSION < 0x050000
#include <QUrl>
#endif
LookupTXDialog::LookupTXDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::LookupTXDialog),
model(0)
{
ui->setupUi(this);
this->model = model;
#if QT_VERSION >= 0x040700
// populate placeholder text
ui->searchLineEdit->setPlaceholderText("Search transaction");
#endif
// connect actions
connect(ui->searchButton, SIGNAL(clicked()), this, SLOT(searchButtonClicked()));
}
void LookupTXDialog::searchTX()
{
// search function to lookup address
string searchText = ui->searchLineEdit->text().toStdString();
// first let's check if we have a searchText, if not do nothing
if (searchText.empty()) return;
uint256 hash;
hash.SetHex(searchText);
Object txobj;
// make a request to new RPC populator function to populate a transaction object
int populateResult = populateRPCTransactionObject(hash, &txobj, "");
if (0<=populateResult)
{
std::string strTXText = write_string(Value(txobj), false) + "\n";
// clean up
string from = ",";
string to = ",\n ";
size_t start_pos = 0;
while((start_pos = strTXText.find(from, start_pos)) != std::string::npos)
{
strTXText.replace(start_pos, from.length(), to);
start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
}
from = ":";
to = " : ";
start_pos = 0;
while((start_pos = strTXText.find(from, start_pos)) != std::string::npos)
{
strTXText.replace(start_pos, from.length(), to);
start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
}
from = "{";
to = "{\n ";
start_pos = 0;
while((start_pos = strTXText.find(from, start_pos)) != std::string::npos)
{
strTXText.replace(start_pos, from.length(), to);
start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
}
from = "}";
to = "\n}";
start_pos = 0;
while((start_pos = strTXText.find(from, start_pos)) != std::string::npos)
{
strTXText.replace(start_pos, from.length(), to);
start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
}
QString txText = QString::fromStdString(strTXText);
QDialog *txDlg = new QDialog;
QLayout *dlgLayout = new QVBoxLayout;
dlgLayout->setSpacing(12);
dlgLayout->setMargin(12);
QTextEdit *dlgTextEdit = new QTextEdit;
dlgTextEdit->setText(txText);
dlgTextEdit->setStatusTip("Transaction Information");
dlgLayout->addWidget(dlgTextEdit);
txDlg->setWindowTitle("Transaction Information");
QPushButton *closeButton = new QPushButton(tr("&Close"));
closeButton->setDefault(true);
QDialogButtonBox *buttonBox = new QDialogButtonBox;
buttonBox->addButton(closeButton, QDialogButtonBox::AcceptRole);
dlgLayout->addWidget(buttonBox);
txDlg->setLayout(dlgLayout);
txDlg->resize(700, 360);
connect(buttonBox, SIGNAL(accepted()), txDlg, SLOT(accept()));
txDlg->setAttribute(Qt::WA_DeleteOnClose); //delete once it's closed
if (txDlg->exec() == QDialog::Accepted) { } else { } //do nothing but close
}
else
{
// show error message
string strText = "The transaction hash entered is ";
switch(populateResult) {
case MP_TX_NOT_FOUND:
strText += "not a valid Bitcoin or Omni transaction. Please check the transaction hash "
"entered and try again.";
break;
case MP_TX_UNCONFIRMED:
strText += "unconfirmed. Toolbox lookup of transactions is currently only available for "
"confirmed transactions.\n\nTip: You can view your own outgoing unconfirmed "
"transactions in the transactions tab.";
break;
case MP_TX_IS_NOT_MASTER_PROTOCOL:
strText += "a Bitcoin transaction only.\n\nTip: You can use the debug console "
"'gettransaction' command to lookup specific Bitcoin transactions.";
break;
}
QString strQText = QString::fromStdString(strText);
QMessageBox errorDialog;
errorDialog.setIcon(QMessageBox::Critical);
errorDialog.setWindowTitle("TXID error");
errorDialog.setText(strQText);
errorDialog.setStandardButtons(QMessageBox::Ok);
errorDialog.setDefaultButton(QMessageBox::Ok);
if(errorDialog.exec() == QMessageBox::Ok) { } // no other button to choose, acknowledged
}
}
void LookupTXDialog::searchButtonClicked()
{
searchTX();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "sendcoinsentry.h"
#include "ui_sendcoinsentry.h"
#include "addressbookpage.h"
#include "addresstablemodel.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include <QApplication>
#include <QClipboard>
SendCoinsEntry::SendCoinsEntry(QWidget *parent) :
QStackedWidget(parent),
ui(new Ui::SendCoinsEntry),
model(0)
{
ui->setupUi(this);
setCurrentWidget(ui->SendCoins);
#ifdef Q_OS_MAC
ui->payToLayout->setSpacing(4);
#endif
#if QT_VERSION >= 0x040700
ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
#endif
// normal bitcoin address field
GUIUtil::setupAddressWidget(ui->payTo, this);
// just a label for displaying bitcoin address(es)
ui->payTo_is->setFont(GUIUtil::bitcoinAddressFont());
}
SendCoinsEntry::~SendCoinsEntry()
{
delete ui;
}
void SendCoinsEntry::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void SendCoinsEntry::on_addressBookButton_clicked()
{
if(!model)
return;
AddressBookPage dlg(AddressBookPage::ForSelection, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}
}
void SendCoinsEntry::on_payTo_textChanged(const QString &address)
{
updateLabel(address);
}
void SendCoinsEntry::setModel(WalletModel *model)
{
this->model = model;
if (model && model->getOptionsModel())
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
connect(ui->payAmount, SIGNAL(textChanged()), this, SIGNAL(payAmountChanged()));
connect(ui->deleteButton, SIGNAL(clicked()), this, SLOT(deleteClicked()));
connect(ui->deleteButton_is, SIGNAL(clicked()), this, SLOT(deleteClicked()));
connect(ui->deleteButton_s, SIGNAL(clicked()), this, SLOT(deleteClicked()));
clear();
}
void SendCoinsEntry::clear()
{
// clear UI elements for normal payment
ui->payTo->clear();
ui->addAsLabel->clear();
ui->payAmount->clear();
ui->messageTextLabel->clear();
ui->messageTextLabel->hide();
ui->messageLabel->hide();
// clear UI elements for insecure payment request
ui->payTo_is->clear();
ui->memoTextLabel_is->clear();
ui->payAmount_is->clear();
// clear UI elements for secure payment request
ui->payTo_s->clear();
ui->memoTextLabel_s->clear();
ui->payAmount_s->clear();
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void SendCoinsEntry::deleteClicked()
{
emit removeEntry(this);
}
bool SendCoinsEntry::validate()
{
if (!model)
return false;
// Check input validity
bool retval = true;
// Skip checks for payment request
if (recipient.paymentRequest.IsInitialized())
return retval;
if (!model->validateAddress(ui->payTo->text()))
{
ui->payTo->setValid(false);
retval = false;
}
if (!ui->payAmount->validate())
{
retval = false;
}
// Reject dust outputs:
if (retval && GUIUtil::isDust(ui->payTo->text(), ui->payAmount->value())) {
ui->payAmount->setValid(false);
retval = false;
}
return retval;
}
SendCoinsRecipient SendCoinsEntry::getValue()
{
// Payment request
if (recipient.paymentRequest.IsInitialized())
return recipient;
// Normal payment
recipient.address = ui->payTo->text();
recipient.label = ui->addAsLabel->text();
recipient.amount = ui->payAmount->value();
recipient.message = ui->messageTextLabel->text();
return recipient;
}
QWidget *SendCoinsEntry::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, ui->payTo);
QWidget::setTabOrder(ui->payTo, ui->addAsLabel);
QWidget *w = ui->payAmount->setupTabChain(ui->addAsLabel);
QWidget::setTabOrder(w, ui->addressBookButton);
QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);
QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);
return ui->deleteButton;
}
void SendCoinsEntry::setValue(const SendCoinsRecipient &value)
{
recipient = value;
if (recipient.paymentRequest.IsInitialized()) // payment request
{
if (recipient.authenticatedMerchant.isEmpty()) // insecure
{
ui->payTo_is->setText(recipient.address);
ui->memoTextLabel_is->setText(recipient.message);
ui->payAmount_is->setValue(recipient.amount);
ui->payAmount_is->setReadOnly(true);
setCurrentWidget(ui->SendCoins_InsecurePaymentRequest);
}
else // secure
{
ui->payTo_s->setText(recipient.authenticatedMerchant);
ui->memoTextLabel_s->setText(recipient.message);
ui->payAmount_s->setValue(recipient.amount);
ui->payAmount_s->setReadOnly(true);
setCurrentWidget(ui->SendCoins_SecurePaymentRequest);
}
}
else // normal payment
{
// message
ui->messageTextLabel->setText(recipient.message);
ui->messageTextLabel->setVisible(!recipient.message.isEmpty());
ui->messageLabel->setVisible(!recipient.message.isEmpty());
ui->payTo->setText(recipient.address);
ui->addAsLabel->setText(recipient.label);
ui->payAmount->setValue(recipient.amount);
}
}
void SendCoinsEntry::setAddress(const QString &address)
{
ui->payTo->setText(address);
ui->payAmount->setFocus();
}
bool SendCoinsEntry::isClear()
{
return ui->payTo->text().isEmpty() && ui->payTo_is->text().isEmpty() && ui->payTo_s->text().isEmpty();
}
void SendCoinsEntry::setFocus()
{
ui->payTo->setFocus();
}
void SendCoinsEntry::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update payAmount with the current unit
ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
ui->payAmount_is->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
ui->payAmount_s->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
bool SendCoinsEntry::updateLabel(const QString &address)
{
if(!model)
return false;
// Fill in label from address book, if address has an associated label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);
if(!associatedLabel.isEmpty())
{
ui->addAsLabel->setText(associatedLabel);
return true;
}
return false;
}
<commit_msg>[Qt] Fill in label from address book also for URIs<commit_after>// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "sendcoinsentry.h"
#include "ui_sendcoinsentry.h"
#include "addressbookpage.h"
#include "addresstablemodel.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include <QApplication>
#include <QClipboard>
SendCoinsEntry::SendCoinsEntry(QWidget *parent) :
QStackedWidget(parent),
ui(new Ui::SendCoinsEntry),
model(0)
{
ui->setupUi(this);
setCurrentWidget(ui->SendCoins);
#ifdef Q_OS_MAC
ui->payToLayout->setSpacing(4);
#endif
#if QT_VERSION >= 0x040700
ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
#endif
// normal bitcoin address field
GUIUtil::setupAddressWidget(ui->payTo, this);
// just a label for displaying bitcoin address(es)
ui->payTo_is->setFont(GUIUtil::bitcoinAddressFont());
}
SendCoinsEntry::~SendCoinsEntry()
{
delete ui;
}
void SendCoinsEntry::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void SendCoinsEntry::on_addressBookButton_clicked()
{
if(!model)
return;
AddressBookPage dlg(AddressBookPage::ForSelection, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}
}
void SendCoinsEntry::on_payTo_textChanged(const QString &address)
{
updateLabel(address);
}
void SendCoinsEntry::setModel(WalletModel *model)
{
this->model = model;
if (model && model->getOptionsModel())
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
connect(ui->payAmount, SIGNAL(textChanged()), this, SIGNAL(payAmountChanged()));
connect(ui->deleteButton, SIGNAL(clicked()), this, SLOT(deleteClicked()));
connect(ui->deleteButton_is, SIGNAL(clicked()), this, SLOT(deleteClicked()));
connect(ui->deleteButton_s, SIGNAL(clicked()), this, SLOT(deleteClicked()));
clear();
}
void SendCoinsEntry::clear()
{
// clear UI elements for normal payment
ui->payTo->clear();
ui->addAsLabel->clear();
ui->payAmount->clear();
ui->messageTextLabel->clear();
ui->messageTextLabel->hide();
ui->messageLabel->hide();
// clear UI elements for insecure payment request
ui->payTo_is->clear();
ui->memoTextLabel_is->clear();
ui->payAmount_is->clear();
// clear UI elements for secure payment request
ui->payTo_s->clear();
ui->memoTextLabel_s->clear();
ui->payAmount_s->clear();
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void SendCoinsEntry::deleteClicked()
{
emit removeEntry(this);
}
bool SendCoinsEntry::validate()
{
if (!model)
return false;
// Check input validity
bool retval = true;
// Skip checks for payment request
if (recipient.paymentRequest.IsInitialized())
return retval;
if (!model->validateAddress(ui->payTo->text()))
{
ui->payTo->setValid(false);
retval = false;
}
if (!ui->payAmount->validate())
{
retval = false;
}
// Reject dust outputs:
if (retval && GUIUtil::isDust(ui->payTo->text(), ui->payAmount->value())) {
ui->payAmount->setValid(false);
retval = false;
}
return retval;
}
SendCoinsRecipient SendCoinsEntry::getValue()
{
// Payment request
if (recipient.paymentRequest.IsInitialized())
return recipient;
// Normal payment
recipient.address = ui->payTo->text();
recipient.label = ui->addAsLabel->text();
recipient.amount = ui->payAmount->value();
recipient.message = ui->messageTextLabel->text();
return recipient;
}
QWidget *SendCoinsEntry::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, ui->payTo);
QWidget::setTabOrder(ui->payTo, ui->addAsLabel);
QWidget *w = ui->payAmount->setupTabChain(ui->addAsLabel);
QWidget::setTabOrder(w, ui->addressBookButton);
QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);
QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);
return ui->deleteButton;
}
void SendCoinsEntry::setValue(const SendCoinsRecipient &value)
{
recipient = value;
if (recipient.paymentRequest.IsInitialized()) // payment request
{
if (recipient.authenticatedMerchant.isEmpty()) // insecure
{
ui->payTo_is->setText(recipient.address);
ui->memoTextLabel_is->setText(recipient.message);
ui->payAmount_is->setValue(recipient.amount);
ui->payAmount_is->setReadOnly(true);
setCurrentWidget(ui->SendCoins_InsecurePaymentRequest);
}
else // secure
{
ui->payTo_s->setText(recipient.authenticatedMerchant);
ui->memoTextLabel_s->setText(recipient.message);
ui->payAmount_s->setValue(recipient.amount);
ui->payAmount_s->setReadOnly(true);
setCurrentWidget(ui->SendCoins_SecurePaymentRequest);
}
}
else // normal payment
{
// message
ui->messageTextLabel->setText(recipient.message);
ui->messageTextLabel->setVisible(!recipient.message.isEmpty());
ui->messageLabel->setVisible(!recipient.message.isEmpty());
ui->addAsLabel->clear();
ui->payTo->setText(recipient.address); // this may set a label from addressbook
if (!recipient.label.isEmpty()) // if a label had been set from the addressbook, dont overwrite with an empty label
ui->addAsLabel->setText(recipient.label);
ui->payAmount->setValue(recipient.amount);
}
}
void SendCoinsEntry::setAddress(const QString &address)
{
ui->payTo->setText(address);
ui->payAmount->setFocus();
}
bool SendCoinsEntry::isClear()
{
return ui->payTo->text().isEmpty() && ui->payTo_is->text().isEmpty() && ui->payTo_s->text().isEmpty();
}
void SendCoinsEntry::setFocus()
{
ui->payTo->setFocus();
}
void SendCoinsEntry::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update payAmount with the current unit
ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
ui->payAmount_is->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
ui->payAmount_s->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
bool SendCoinsEntry::updateLabel(const QString &address)
{
if(!model)
return false;
// Fill in label from address book, if address has an associated label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);
if(!associatedLabel.isEmpty())
{
ui->addAsLabel->setText(associatedLabel);
return true;
}
return false;
}
<|endoftext|>
|
<commit_before>/*===========================================================================*\
* *
* OpenMesh *
* Copyright (C) 2001-2012 by Computer Graphics Group, RWTH Aachen *
* www.openmesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenMesh. *
* *
* OpenMesh is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version with the *
* following exceptions: *
* *
* If other files instantiate templates or use macros *
* or inline functions from this file, or you compile this file and *
* link it with other files to produce an executable, this file does *
* not by itself cause the resulting executable to be covered by the *
* GNU Lesser General Public License. This exception does not however *
* invalidate any other reasons why the executable file might be *
* covered by the GNU Lesser General Public License. *
* *
* OpenMesh 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 LesserGeneral Public *
* License along with OpenMesh. If not, *
* see <http://www.gnu.org/licenses/>. *
* *
\*===========================================================================*/
/*===========================================================================*\
* *
* $Revision$ *
* $Date$ *
* *
\*===========================================================================*/
/** \file MixedDecimaterT.cc
*/
//=============================================================================
//
// CLASS MixedDecimaterT - IMPLEMENTATION
//
//=============================================================================
#define OPENMESH_MIXED_DECIMATER_DECIMATERT_CC
//== INCLUDES =================================================================
#include <OpenMesh/Tools/Decimater/MixedDecimaterT.hh>
#include <vector>
#if defined(OM_CC_MIPS)
# include <float.h>
#else
# include <cfloat>
#endif
//== NAMESPACE ===============================================================
namespace OpenMesh {
namespace Decimater {
//== IMPLEMENTATION ==========================================================
template<class Mesh>
MixedDecimaterT<Mesh>::MixedDecimaterT(Mesh& _mesh) :
BaseDecimaterT<Mesh>(_mesh),McDecimaterT<Mesh>(_mesh), DecimaterT<Mesh>(_mesh) {
}
//-----------------------------------------------------------------------------
template<class Mesh>
MixedDecimaterT<Mesh>::~MixedDecimaterT() {
}
//-----------------------------------------------------------------------------
template<class Mesh>
size_t MixedDecimaterT<Mesh>::decimate(const size_t _n_collapses, const float _mc_factor) {
if (_mc_factor > 1.0)
return 0;
size_t n_collapses_mc = static_cast<size_t>(_mc_factor*_n_collapses);
size_t n_collapses_inc = static_cast<size_t>(_n_collapses - n_collapses_mc);
size_t r_collapses = 0;
if (_mc_factor > 0.0)
r_collapses = McDecimaterT<Mesh>::decimate(n_collapses_mc);
if (_mc_factor < 1.0)
r_collapses += DecimaterT<Mesh>::decimate(n_collapses_inc);
return r_collapses;
}
template<class Mesh>
size_t MixedDecimaterT<Mesh>::decimate_to_faces(const size_t _n_vertices,const size_t _n_faces, const float _mc_factor ){
if (_mc_factor > 1.0)
return 0;
std::size_t r_collapses = 0;
if (_mc_factor > 0.0)
{
bool constraintsOnly = (_n_vertices == 0) && (_n_faces == 1);
if (!constraintsOnly) {
size_t mesh_faces = this->mesh().n_faces();
size_t mesh_vertices = this->mesh().n_vertices();
//reduce the mesh only for _mc_factor
size_t n_vertices_mc = static_cast<size_t>(mesh_vertices - _mc_factor * (mesh_vertices - _n_vertices));
size_t n_faces_mc = static_cast<size_t>(mesh_faces - _mc_factor * (mesh_faces - _n_faces));
r_collapses = McDecimaterT<Mesh>::decimate_to_faces(n_vertices_mc, n_faces_mc);
} else {
const size_t samples = this->samples();
// MinimalSample count for the McDecimater
const size_t min = 2;
// Maximal number of samples for the McDecimater
const size_t max = samples;
// Number of incremental steps
const size_t steps = 7;
for ( size_t i = 0; i < steps; ++i ) {
// Compute number of samples to be used
size_t samples = int (double( min) + double(i)/(double(steps)-1.0) * (max-2) ) ;
// We won't allow 1 here, as this is the last step in the incremental part
double decimaterLevel = (double(i + 1)) * _mc_factor / (double(steps) );
this->set_samples(samples);
r_collapses += McDecimaterT<Mesh>::decimate_constraints_only(decimaterLevel);
}
}
}
//Update the mesh::n_vertices function, otherwise the next Decimater function will delete too much
this->mesh().garbage_collection();
//reduce the rest of the mesh
if (_mc_factor < 1.0) {
r_collapses += DecimaterT<Mesh>::decimate_to_faces(_n_vertices,_n_faces);
}
return r_collapses;
}
//=============================================================================
}// END_NS_MC_DECIMATER
} // END_NS_OPENMESH
//=============================================================================
<commit_msg>Wrong variable type<commit_after>/*===========================================================================*\
* *
* OpenMesh *
* Copyright (C) 2001-2012 by Computer Graphics Group, RWTH Aachen *
* www.openmesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenMesh. *
* *
* OpenMesh is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version with the *
* following exceptions: *
* *
* If other files instantiate templates or use macros *
* or inline functions from this file, or you compile this file and *
* link it with other files to produce an executable, this file does *
* not by itself cause the resulting executable to be covered by the *
* GNU Lesser General Public License. This exception does not however *
* invalidate any other reasons why the executable file might be *
* covered by the GNU Lesser General Public License. *
* *
* OpenMesh 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 LesserGeneral Public *
* License along with OpenMesh. If not, *
* see <http://www.gnu.org/licenses/>. *
* *
\*===========================================================================*/
/*===========================================================================*\
* *
* $Revision$ *
* $Date$ *
* *
\*===========================================================================*/
/** \file MixedDecimaterT.cc
*/
//=============================================================================
//
// CLASS MixedDecimaterT - IMPLEMENTATION
//
//=============================================================================
#define OPENMESH_MIXED_DECIMATER_DECIMATERT_CC
//== INCLUDES =================================================================
#include <OpenMesh/Tools/Decimater/MixedDecimaterT.hh>
#include <vector>
#if defined(OM_CC_MIPS)
# include <float.h>
#else
# include <cfloat>
#endif
//== NAMESPACE ===============================================================
namespace OpenMesh {
namespace Decimater {
//== IMPLEMENTATION ==========================================================
template<class Mesh>
MixedDecimaterT<Mesh>::MixedDecimaterT(Mesh& _mesh) :
BaseDecimaterT<Mesh>(_mesh),McDecimaterT<Mesh>(_mesh), DecimaterT<Mesh>(_mesh) {
}
//-----------------------------------------------------------------------------
template<class Mesh>
MixedDecimaterT<Mesh>::~MixedDecimaterT() {
}
//-----------------------------------------------------------------------------
template<class Mesh>
size_t MixedDecimaterT<Mesh>::decimate(const size_t _n_collapses, const float _mc_factor) {
if (_mc_factor > 1.0)
return 0;
size_t n_collapses_mc = static_cast<size_t>(_mc_factor*_n_collapses);
size_t n_collapses_inc = static_cast<size_t>(_n_collapses - n_collapses_mc);
size_t r_collapses = 0;
if (_mc_factor > 0.0)
r_collapses = McDecimaterT<Mesh>::decimate(n_collapses_mc);
if (_mc_factor < 1.0)
r_collapses += DecimaterT<Mesh>::decimate(n_collapses_inc);
return r_collapses;
}
template<class Mesh>
size_t MixedDecimaterT<Mesh>::decimate_to_faces(const size_t _n_vertices,const size_t _n_faces, const float _mc_factor ){
if (_mc_factor > 1.0)
return 0;
std::size_t r_collapses = 0;
if (_mc_factor > 0.0)
{
bool constraintsOnly = (_n_vertices == 0) && (_n_faces == 1);
if (!constraintsOnly) {
size_t mesh_faces = this->mesh().n_faces();
size_t mesh_vertices = this->mesh().n_vertices();
//reduce the mesh only for _mc_factor
size_t n_vertices_mc = static_cast<size_t>(mesh_vertices - _mc_factor * (mesh_vertices - _n_vertices));
size_t n_faces_mc = static_cast<size_t>(mesh_faces - _mc_factor * (mesh_faces - _n_faces));
r_collapses = McDecimaterT<Mesh>::decimate_to_faces(n_vertices_mc, n_faces_mc);
} else {
const size_t samples = this->samples();
// MinimalSample count for the McDecimater
const size_t min = 2;
// Maximal number of samples for the McDecimater
const size_t max = samples;
// Number of incremental steps
const size_t steps = 7;
for ( size_t i = 0; i < steps; ++i ) {
// Compute number of samples to be used
size_t samples = int (double( min) + double(i)/(double(steps)-1.0) * (max-2) ) ;
// We won't allow 1 here, as this is the last step in the incremental part
float decimaterLevel = (double(i + 1)) * _mc_factor / (double(steps) );
this->set_samples(samples);
r_collapses += McDecimaterT<Mesh>::decimate_constraints_only(decimaterLevel);
}
}
}
//Update the mesh::n_vertices function, otherwise the next Decimater function will delete too much
this->mesh().garbage_collection();
//reduce the rest of the mesh
if (_mc_factor < 1.0) {
r_collapses += DecimaterT<Mesh>::decimate_to_faces(_n_vertices,_n_faces);
}
return r_collapses;
}
//=============================================================================
}// END_NS_MC_DECIMATER
} // END_NS_OPENMESH
//=============================================================================
<|endoftext|>
|
<commit_before>//===------ OrcArchSupport.cpp - Architecture specific support code -------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/Triple.h"
#include "llvm/ExecutionEngine/Orc/OrcArchitectureSupport.h"
#include "llvm/Support/Process.h"
#include <array>
namespace llvm {
namespace orc {
void OrcX86_64::writeResolverCode(uint8_t *ResolverMem, JITReentryFn ReentryFn,
void *CallbackMgr) {
const uint8_t ResolverCode[] = {
// resolver_entry:
0x55, // 0x00: pushq %rbp
0x48, 0x89, 0xe5, // 0x01: movq %rsp, %rbp
0x50, // 0x04: pushq %rax
0x53, // 0x05: pushq %rbx
0x51, // 0x06: pushq %rcx
0x52, // 0x07: pushq %rdx
0x56, // 0x08: pushq %rsi
0x57, // 0x09: pushq %rdi
0x41, 0x50, // 0x0a: pushq %r8
0x41, 0x51, // 0x0c: pushq %r9
0x41, 0x52, // 0x0e: pushq %r10
0x41, 0x53, // 0x10: pushq %r11
0x41, 0x54, // 0x12: pushq %r12
0x41, 0x55, // 0x14: pushq %r13
0x41, 0x56, // 0x16: pushq %r14
0x41, 0x57, // 0x18: pushq %r15
0x48, 0x81, 0xec, 0x08, 0x02, 0x00, 0x00, // 0x1a: subq 20, %rsp
0x48, 0x0f, 0xae, 0x04, 0x24, // 0x21: fxsave64 (%rsp)
0x48, 0x8d, 0x3d, 0x43, 0x00, 0x00, 0x00, // 0x26: leaq 67(%rip), %rdi
0x48, 0x8b, 0x3f, // 0x2d: movq (%rdi), %rdi
0x48, 0x8b, 0x75, 0x08, // 0x30: movq 8(%rbp), %rsi
0x48, 0x83, 0xee, 0x06, // 0x34: subq $6, %rsi
0x48, 0xb8, // 0x38: movabsq $0, %rax
// 0x3a: JIT re-entry fn addr:
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xff, 0xd0, // 0x42: callq *%rax
0x48, 0x89, 0x45, 0x08, // 0x44: movq %rax, 8(%rbp)
0x48, 0x0f, 0xae, 0x0c, 0x24, // 0x48: fxrstor64 (%rsp)
0x48, 0x81, 0xc4, 0x08, 0x02, 0x00, 0x00, // 0x4d: addq 20, %rsp
0x41, 0x5f, // 0x54: popq %r15
0x41, 0x5e, // 0x56: popq %r14
0x41, 0x5d, // 0x58: popq %r13
0x41, 0x5c, // 0x5a: popq %r12
0x41, 0x5b, // 0x5c: popq %r11
0x41, 0x5a, // 0x5e: popq %r10
0x41, 0x59, // 0x60: popq %r9
0x41, 0x58, // 0x62: popq %r8
0x5f, // 0x64: popq %rdi
0x5e, // 0x65: popq %rsi
0x5a, // 0x66: popq %rdx
0x59, // 0x67: popq %rcx
0x5b, // 0x68: popq %rbx
0x58, // 0x69: popq %rax
0x5d, // 0x6a: popq %rbp
0xc3, // 0x6b: retq
0x00, 0x00, 0x00, 0x00, // 0x6c: <padding>
// 0x70: Callback mgr address.
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
const unsigned ReentryFnAddrOffset = 0x3a;
const unsigned CallbackMgrAddrOffset = 0x70;
memcpy(ResolverMem, ResolverCode, sizeof(ResolverCode));
memcpy(ResolverMem + ReentryFnAddrOffset, &ReentryFn, sizeof(ReentryFn));
memcpy(ResolverMem + CallbackMgrAddrOffset, &CallbackMgr,
sizeof(CallbackMgr));
}
void OrcX86_64::writeTrampolines(uint8_t *TrampolineMem, void *ResolverAddr,
unsigned NumTrampolines) {
unsigned OffsetToPtr = NumTrampolines * TrampolineSize;
memcpy(TrampolineMem + OffsetToPtr, &ResolverAddr, sizeof(void*));
uint64_t *Trampolines = reinterpret_cast<uint64_t*>(TrampolineMem);
uint64_t CallIndirPCRel = 0xf1c40000000015ff;
for (unsigned I = 0; I < NumTrampolines; ++I, OffsetToPtr -= TrampolineSize)
Trampolines[I] = CallIndirPCRel | ((OffsetToPtr - 6) << 16);
}
std::error_code OrcX86_64::emitIndirectStubsBlock(IndirectStubsInfo &StubsInfo,
unsigned MinStubs,
void *InitialPtrVal) {
// Stub format is:
//
// .section __orc_stubs
// stub1:
// jmpq *ptr1(%rip)
// .byte 0xC4 ; <- Invalid opcode padding.
// .byte 0xF1
// stub2:
// jmpq *ptr2(%rip)
//
// ...
//
// .section __orc_ptrs
// ptr1:
// .quad 0x0
// ptr2:
// .quad 0x0
//
// ...
const unsigned StubSize = IndirectStubsInfo::StubSize;
// Emit at least MinStubs, rounded up to fill the pages allocated.
unsigned PageSize = sys::Process::getPageSize();
unsigned NumPages = ((MinStubs * StubSize) + (PageSize - 1)) / PageSize;
unsigned NumStubs = (NumPages * PageSize) / StubSize;
// Allocate memory for stubs and pointers in one call.
std::error_code EC;
auto StubsMem =
sys::OwningMemoryBlock(
sys::Memory::allocateMappedMemory(2 * NumPages * PageSize, nullptr,
sys::Memory::MF_READ |
sys::Memory::MF_WRITE,
EC));
if (EC)
return EC;
// Create separate MemoryBlocks representing the stubs and pointers.
sys::MemoryBlock StubsBlock(StubsMem.base(), NumPages * PageSize);
sys::MemoryBlock PtrsBlock(static_cast<char*>(StubsMem.base()) +
NumPages * PageSize,
NumPages * PageSize);
// Populate the stubs page stubs and mark it executable.
uint64_t *Stub = reinterpret_cast<uint64_t*>(StubsBlock.base());
uint64_t PtrOffsetField =
static_cast<uint64_t>(NumPages * PageSize - 6) << 16;
for (unsigned I = 0; I < NumStubs; ++I)
Stub[I] = 0xF1C40000000025ff | PtrOffsetField;
if (auto EC = sys::Memory::protectMappedMemory(StubsBlock,
sys::Memory::MF_READ |
sys::Memory::MF_EXEC))
return EC;
// Initialize all pointers to point at FailureAddress.
void **Ptr = reinterpret_cast<void**>(PtrsBlock.base());
for (unsigned I = 0; I < NumStubs; ++I)
Ptr[I] = InitialPtrVal;
StubsInfo = IndirectStubsInfo(NumStubs, std::move(StubsMem));
return std::error_code();
}
} // End namespace orc.
} // End namespace llvm.
<commit_msg>[Orc] Fix a typo in the comments for the x86_64 resolver block.<commit_after>//===------ OrcArchSupport.cpp - Architecture specific support code -------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/Triple.h"
#include "llvm/ExecutionEngine/Orc/OrcArchitectureSupport.h"
#include "llvm/Support/Process.h"
#include <array>
namespace llvm {
namespace orc {
void OrcX86_64::writeResolverCode(uint8_t *ResolverMem, JITReentryFn ReentryFn,
void *CallbackMgr) {
const uint8_t ResolverCode[] = {
// resolver_entry:
0x55, // 0x00: pushq %rbp
0x48, 0x89, 0xe5, // 0x01: movq %rsp, %rbp
0x50, // 0x04: pushq %rax
0x53, // 0x05: pushq %rbx
0x51, // 0x06: pushq %rcx
0x52, // 0x07: pushq %rdx
0x56, // 0x08: pushq %rsi
0x57, // 0x09: pushq %rdi
0x41, 0x50, // 0x0a: pushq %r8
0x41, 0x51, // 0x0c: pushq %r9
0x41, 0x52, // 0x0e: pushq %r10
0x41, 0x53, // 0x10: pushq %r11
0x41, 0x54, // 0x12: pushq %r12
0x41, 0x55, // 0x14: pushq %r13
0x41, 0x56, // 0x16: pushq %r14
0x41, 0x57, // 0x18: pushq %r15
0x48, 0x81, 0xec, 0x08, 0x02, 0x00, 0x00, // 0x1a: subq 0x208, %rsp
0x48, 0x0f, 0xae, 0x04, 0x24, // 0x21: fxsave64 (%rsp)
0x48, 0x8d, 0x3d, 0x43, 0x00, 0x00, 0x00, // 0x26: leaq 67(%rip), %rdi
0x48, 0x8b, 0x3f, // 0x2d: movq (%rdi), %rdi
0x48, 0x8b, 0x75, 0x08, // 0x30: movq 8(%rbp), %rsi
0x48, 0x83, 0xee, 0x06, // 0x34: subq $6, %rsi
0x48, 0xb8, // 0x38: movabsq $0, %rax
// 0x3a: JIT re-entry fn addr:
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xff, 0xd0, // 0x42: callq *%rax
0x48, 0x89, 0x45, 0x08, // 0x44: movq %rax, 8(%rbp)
0x48, 0x0f, 0xae, 0x0c, 0x24, // 0x48: fxrstor64 (%rsp)
0x48, 0x81, 0xc4, 0x08, 0x02, 0x00, 0x00, // 0x4d: addq 0x208, %rsp
0x41, 0x5f, // 0x54: popq %r15
0x41, 0x5e, // 0x56: popq %r14
0x41, 0x5d, // 0x58: popq %r13
0x41, 0x5c, // 0x5a: popq %r12
0x41, 0x5b, // 0x5c: popq %r11
0x41, 0x5a, // 0x5e: popq %r10
0x41, 0x59, // 0x60: popq %r9
0x41, 0x58, // 0x62: popq %r8
0x5f, // 0x64: popq %rdi
0x5e, // 0x65: popq %rsi
0x5a, // 0x66: popq %rdx
0x59, // 0x67: popq %rcx
0x5b, // 0x68: popq %rbx
0x58, // 0x69: popq %rax
0x5d, // 0x6a: popq %rbp
0xc3, // 0x6b: retq
0x00, 0x00, 0x00, 0x00, // 0x6c: <padding>
// 0x70: Callback mgr address.
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
const unsigned ReentryFnAddrOffset = 0x3a;
const unsigned CallbackMgrAddrOffset = 0x70;
memcpy(ResolverMem, ResolverCode, sizeof(ResolverCode));
memcpy(ResolverMem + ReentryFnAddrOffset, &ReentryFn, sizeof(ReentryFn));
memcpy(ResolverMem + CallbackMgrAddrOffset, &CallbackMgr,
sizeof(CallbackMgr));
}
void OrcX86_64::writeTrampolines(uint8_t *TrampolineMem, void *ResolverAddr,
unsigned NumTrampolines) {
unsigned OffsetToPtr = NumTrampolines * TrampolineSize;
memcpy(TrampolineMem + OffsetToPtr, &ResolverAddr, sizeof(void*));
uint64_t *Trampolines = reinterpret_cast<uint64_t*>(TrampolineMem);
uint64_t CallIndirPCRel = 0xf1c40000000015ff;
for (unsigned I = 0; I < NumTrampolines; ++I, OffsetToPtr -= TrampolineSize)
Trampolines[I] = CallIndirPCRel | ((OffsetToPtr - 6) << 16);
}
std::error_code OrcX86_64::emitIndirectStubsBlock(IndirectStubsInfo &StubsInfo,
unsigned MinStubs,
void *InitialPtrVal) {
// Stub format is:
//
// .section __orc_stubs
// stub1:
// jmpq *ptr1(%rip)
// .byte 0xC4 ; <- Invalid opcode padding.
// .byte 0xF1
// stub2:
// jmpq *ptr2(%rip)
//
// ...
//
// .section __orc_ptrs
// ptr1:
// .quad 0x0
// ptr2:
// .quad 0x0
//
// ...
const unsigned StubSize = IndirectStubsInfo::StubSize;
// Emit at least MinStubs, rounded up to fill the pages allocated.
unsigned PageSize = sys::Process::getPageSize();
unsigned NumPages = ((MinStubs * StubSize) + (PageSize - 1)) / PageSize;
unsigned NumStubs = (NumPages * PageSize) / StubSize;
// Allocate memory for stubs and pointers in one call.
std::error_code EC;
auto StubsMem =
sys::OwningMemoryBlock(
sys::Memory::allocateMappedMemory(2 * NumPages * PageSize, nullptr,
sys::Memory::MF_READ |
sys::Memory::MF_WRITE,
EC));
if (EC)
return EC;
// Create separate MemoryBlocks representing the stubs and pointers.
sys::MemoryBlock StubsBlock(StubsMem.base(), NumPages * PageSize);
sys::MemoryBlock PtrsBlock(static_cast<char*>(StubsMem.base()) +
NumPages * PageSize,
NumPages * PageSize);
// Populate the stubs page stubs and mark it executable.
uint64_t *Stub = reinterpret_cast<uint64_t*>(StubsBlock.base());
uint64_t PtrOffsetField =
static_cast<uint64_t>(NumPages * PageSize - 6) << 16;
for (unsigned I = 0; I < NumStubs; ++I)
Stub[I] = 0xF1C40000000025ff | PtrOffsetField;
if (auto EC = sys::Memory::protectMappedMemory(StubsBlock,
sys::Memory::MF_READ |
sys::Memory::MF_EXEC))
return EC;
// Initialize all pointers to point at FailureAddress.
void **Ptr = reinterpret_cast<void**>(PtrsBlock.base());
for (unsigned I = 0; I < NumStubs; ++I)
Ptr[I] = InitialPtrVal;
StubsInfo = IndirectStubsInfo(NumStubs, std::move(StubsMem));
return std::error_code();
}
} // End namespace orc.
} // End namespace llvm.
<|endoftext|>
|
<commit_before>/**********************************************************************
* Felix Winterstein, Imperial College London
*
* File: filter_it.cpp
*
* Revision 1.01
* Additional Comments: distributed under a BSD license, see LICENSE.txt
*
**********************************************************************/
#include <stdio.h>
#include <stdlib.h>
//#include <stdbool.h>
#include <math.h>
#include "filter_it.h"
#include "dyn_mem_alloc.h"
uint stack_counter;
// push pointer to tree node onto stack
uint push_node(stack_type *stack, uint sp, uint u)
{
//stack_ptr new_node = malloc(sizeof(stack_type)); //new stack_type;
//new_node->u = u;
//new_node->next = sp;
//sp = new_node;
stack[sp].u = u;
return sp+1;
}
// pop pointer to tree node from stack
uint pop_node(stack_type *stack, uint sp, uint *u)
{
//stack_ptr tmp = sp;
*u = stack[sp-1].u;
//sp = sp->next;
//free(tmp); //delete tmp;
//tmp = 0;
return sp-1;
}
// push list pointer onto stack
uint cpush_node(cstack_type *cstack, uint sp, centre_set_ptr l, uint k, bool redundant, centre_set_ptr default_set, uint default_k)
{
if (stack_counter > STACK_BOUND-2) {
cstack[sp].list = default_set;
cstack[sp].k = default_k;
cstack[sp].redundant = false;
} else {
cstack[sp].list = l;
cstack[sp].k = k;
cstack[sp].redundant = redundant;
stack_counter++;
}
/*
cstack_ptr new_entry = malloc(sizeof(cstack_type)); //new cstack_type;
if (stack_counter > bound_index_list_size) {
new_entry->list = default_set;
new_entry->k = k;
} else {
new_entry->list = l;
new_entry->k = k;
}
new_entry->next = sp;
sp = new_entry;
stack_counter++;
*/
return sp+1;
}
// pop list pointer from stack
uint cpop_node(cstack_type *cstack, uint sp, centre_set_ptr *l, uint *k, bool *redundant)
{
*l = cstack[sp-1].list;
*k = cstack[sp-1].k;
*redundant = cstack[sp-1].redundant;
stack_counter--;
/*
cstack_ptr tmp = sp;
*l = tmp->list; // this might be a bit confusing... it is actually a pointer to a pointer
*k = tmp->k;
*redundant = tmp->redundant;
// dispose first
sp = sp->next;
free(tmp); //delete tmp;
stack_counter--;
*/
return sp-1;
}
// kernel function of the filtering algorithm
void filter_it( uint root,
kdTree_type *tree_memory,
centre_type *centres,
uint k,
bool last_run,
data_type_short *output_array)
{
centre_type centre_buffer[KMAX];
stack_type stack[NMAX];
cstack_type cstack[NMAX];
centre_set_type centre_set_heap[CENTRE_SET_HEAP_BOUND];
uint freelist[CENTRE_SET_HEAP_BOUND];
uint next_free_location;
//Initialisation
#ifdef CUSTOM_DYN_ALLOC
init_allocator<uint>(freelist, &next_free_location, CENTRE_SET_HEAP_BOUND-1);
#endif
for(uint i=0; i<k; i++) {
for (uint d=0; d<D; d++) {
centre_buffer[i].wgtCent.value[d] = 0;
}
centre_buffer[i].count_short = 0;
centre_buffer[i].sum_sq = 0;
}
uint visited_nodes = 0;
centre_set_ptr cntr_idxs;
centre_set_type *cntr_idxs_ptr;
#ifdef CUSTOM_DYN_ALLOC
cntr_idxs = malloc<uint>(freelist, &next_free_location);
cntr_idxs_ptr = make_pointer<centre_set_type>(centre_set_heap, cntr_idxs);
#else
cntr_idxs = new centre_set_type;
cntr_idxs_ptr = cntr_idxs;
#endif
for(uint i=0; i<k; i++) {
centre_buffer[i] = centres[i];
cntr_idxs_ptr->idx[i] = i;
}
uint st = 0;
uint cst = 0;
stack_counter = 0;
uint max_stack_counter = 0;
uint centre_set_counter = 0;
//End of Initialisation
st=push_node(stack,st,root);
cst = cpush_node(cstack, cst, cntr_idxs, k, false, cntr_idxs, k); // first set (default set) never gets freed
while (st != 0) {
// fetch head of stack
uint u;
st = pop_node(stack,st,&u);
centre_set_ptr tmp_cntr_idxs;
centre_set_type *tmp_cntr_idxs_ptr;
uint tmp_k;
bool redundant;
cst = cpop_node(cstack,cst,&tmp_cntr_idxs,&tmp_k,&redundant);
#ifdef CUSTOM_DYN_ALLOC
tmp_cntr_idxs_ptr = make_pointer<centre_set_type>(centre_set_heap, tmp_cntr_idxs);
#else
tmp_cntr_idxs_ptr = tmp_cntr_idxs;
#endif
// buffer tree node
kdTree_type tmp_u;
tmp_u = tree_memory[u];
data_type_short tmp_centre_positions[KMAX];
for (uint i=0; i<tmp_k; i++) {
tmp_centre_positions[i] = centre_buffer[tmp_cntr_idxs_ptr->idx[i]].position_short;
}
// find closest centre to various points
data_type comp_point;
if ( (tmp_u.ileft == 0) && (tmp_u.iright == 0) ) {
comp_point = tmp_u.wgtCent;
} else {
comp_point = conv_short_to_long(tmp_u.midPoint_short);
}
uint tmp_search_idx;
data_type_short tmp_search_centre;
closest_to_point_direct_fi_mixed(comp_point, tmp_centre_positions, tmp_k, &tmp_search_idx, &tmp_search_centre);
data_type_short z_star = tmp_search_centre;
uint idx_closest = tmp_search_idx;
centre_set_ptr new_cntr_idxs;
centre_set_type *new_cntr_idxs_ptr;
bool centre_set_bound_reached = centre_set_counter >= CENTRE_SET_HEAP_BOUND-2;
uint new_k=0;
// allocate a new list
if (!centre_set_bound_reached ) {
#ifdef CUSTOM_DYN_ALLOC
new_cntr_idxs = malloc<uint>(freelist, &next_free_location);
new_cntr_idxs_ptr = make_pointer(centre_set_heap, new_cntr_idxs);
#else
new_cntr_idxs = new centre_set_type;
new_cntr_idxs_ptr = new_cntr_idxs;
#endif
centre_set_counter++;
// and copy candidates that survive pruning into it
// candidate pruning
for (uint i=0; i<tmp_k; i++) {
bool too_far;
tooFar_fi_short(z_star, tmp_centre_positions[i], tmp_u.bnd_lo_short, tmp_u.bnd_hi_short, &too_far);
if ( too_far==false ) {
new_cntr_idxs_ptr->idx[new_k] = tmp_cntr_idxs_ptr->idx[i];
new_k++;
}
}
}
// update sum_sq of centre
//coord_type tmp1_1, tmp2_1;
coord_type tmp1_2, tmp2_2;
data_type tmp_wgtCent = tmp_u.wgtCent;
for (uint d=0; d<D; d++) {
tmp_wgtCent.value[d] = tmp_wgtCent.value[d]>>FRACTIONAL_BITS;
}
// z_star == tmp_centre_positions[idx_closest] !
dot_product_fi_mixed(z_star,tmp_wgtCent,&tmp1_2);
dot_product_fi_short(z_star,z_star,&tmp2_2);
coord_type tmp1, tmp2;
uint tmp_idx;
tmp1 = tmp1_2;
tmp2 = tmp2_2>>FRACTIONAL_BITS;
tmp_idx = idx_closest;
// compute distortion
coord_type_short tmp_count = tmp_u.count_short;
coord_type tmp3 = saturate(tmp2)*saturate(tmp_count);
coord_type tmp_sum_sq = tmp_u.sum_sq+tmp3;
tmp_sum_sq = tmp_sum_sq-2*tmp1;
uint tmp_final_idx = tmp_cntr_idxs_ptr->idx[tmp_idx];
// write back
if ( ((tmp_u.ileft == 0) && (tmp_u.iright == 0)) || ((new_k == 1) && (last_run == false)) ) {
// weighted centroid of this centre
for (uint d=0; d<D; d++) {
centre_buffer[tmp_final_idx].wgtCent.value[d] += tmp_u.wgtCent.value[d];
}
// update number of points assigned to centre
centre_buffer[tmp_final_idx].count_short += tmp_u.count_short;
centre_buffer[tmp_final_idx].sum_sq += tmp_sum_sq;
if (!centre_set_bound_reached ) {
#ifdef CUSTOM_DYN_ALLOC
free<uint>(freelist, &next_free_location, new_cntr_idxs);
#else
delete new_cntr_idxs;
#endif
centre_set_counter--;
}
if (last_run == true) {
//printf("%d: %d\n",tmp_u.pointAddr,tmp_u.sum_sq);
output_array[tmp_u.pointAddr] = z_star;
}
} else {
uint left_child = tmp_u.ileft;
uint right_child = tmp_u.iright;
// push children onto stack
st = push_node(stack,st,right_child);
st = push_node(stack,st,left_child);
// push centre lists for both children onto stack
if (!centre_set_bound_reached) {
cst = cpush_node(cstack,cst,new_cntr_idxs,new_k,true, cntr_idxs,k);
cst = cpush_node(cstack,cst,new_cntr_idxs,new_k,false, cntr_idxs,k);
} else {
cst = cpush_node(cstack,cst,cntr_idxs,k,true, cntr_idxs,k);
cst = cpush_node(cstack,cst,cntr_idxs,k,false, cntr_idxs,k);
}
}
// delete if centre set was used twice
if (redundant == true) {
#ifdef CUSTOM_DYN_ALLOC
free<uint>(freelist, &next_free_location, tmp_cntr_idxs);
#else
delete tmp_cntr_idxs;
#endif
centre_set_counter--;
}
if (stack_counter > max_stack_counter)
max_stack_counter = stack_counter;
visited_nodes++;
}
#ifdef VERBOSE
printf("Visited nodes: %d\n",visited_nodes);
#endif
for(uint i=0; i<k; i++) {
centres[i] = centre_buffer[i];
}
}
<commit_msg>include node-centre pairs stats<commit_after>/**********************************************************************
* Felix Winterstein, Imperial College London
*
* File: filter_it.cpp
*
* Revision 1.01
* Additional Comments: distributed under a BSD license, see LICENSE.txt
*
**********************************************************************/
#include <stdio.h>
#include <stdlib.h>
//#include <stdbool.h>
#include <math.h>
#include "filter_it.h"
#include "dyn_mem_alloc.h"
uint stack_counter;
// push pointer to tree node onto stack
uint push_node(stack_type *stack, uint sp, uint u)
{
//stack_ptr new_node = malloc(sizeof(stack_type)); //new stack_type;
//new_node->u = u;
//new_node->next = sp;
//sp = new_node;
stack[sp].u = u;
return sp+1;
}
// pop pointer to tree node from stack
uint pop_node(stack_type *stack, uint sp, uint *u)
{
//stack_ptr tmp = sp;
*u = stack[sp-1].u;
//sp = sp->next;
//free(tmp); //delete tmp;
//tmp = 0;
return sp-1;
}
// push list pointer onto stack
uint cpush_node(cstack_type *cstack, uint sp, centre_set_ptr l, uint k, bool redundant, centre_set_ptr default_set, uint default_k)
{
if (stack_counter > STACK_BOUND-2) {
cstack[sp].list = default_set;
cstack[sp].k = default_k;
cstack[sp].redundant = false;
} else {
cstack[sp].list = l;
cstack[sp].k = k;
cstack[sp].redundant = redundant;
stack_counter++;
}
/*
cstack_ptr new_entry = malloc(sizeof(cstack_type)); //new cstack_type;
if (stack_counter > bound_index_list_size) {
new_entry->list = default_set;
new_entry->k = k;
} else {
new_entry->list = l;
new_entry->k = k;
}
new_entry->next = sp;
sp = new_entry;
stack_counter++;
*/
return sp+1;
}
// pop list pointer from stack
uint cpop_node(cstack_type *cstack, uint sp, centre_set_ptr *l, uint *k, bool *redundant)
{
*l = cstack[sp-1].list;
*k = cstack[sp-1].k;
*redundant = cstack[sp-1].redundant;
stack_counter--;
/*
cstack_ptr tmp = sp;
*l = tmp->list; // this might be a bit confusing... it is actually a pointer to a pointer
*k = tmp->k;
*redundant = tmp->redundant;
// dispose first
sp = sp->next;
free(tmp); //delete tmp;
stack_counter--;
*/
return sp-1;
}
// kernel function of the filtering algorithm
void filter_it( uint root,
kdTree_type *tree_memory,
centre_type *centres,
uint k,
bool last_run,
data_type_short *output_array)
{
centre_type centre_buffer[KMAX];
stack_type stack[NMAX];
cstack_type cstack[NMAX];
centre_set_type centre_set_heap[CENTRE_SET_HEAP_BOUND];
uint freelist[CENTRE_SET_HEAP_BOUND];
uint next_free_location;
//Initialisation
#ifdef CUSTOM_DYN_ALLOC
init_allocator<uint>(freelist, &next_free_location, CENTRE_SET_HEAP_BOUND-1);
#endif
for(uint i=0; i<k; i++) {
for (uint d=0; d<D; d++) {
centre_buffer[i].wgtCent.value[d] = 0;
}
centre_buffer[i].count_short = 0;
centre_buffer[i].sum_sq = 0;
}
uint visited_nodes = 0;
uint node_centre_pairs = 0;
centre_set_ptr cntr_idxs;
centre_set_type *cntr_idxs_ptr;
#ifdef CUSTOM_DYN_ALLOC
cntr_idxs = malloc<uint>(freelist, &next_free_location);
cntr_idxs_ptr = make_pointer<centre_set_type>(centre_set_heap, cntr_idxs);
#else
cntr_idxs = new centre_set_type;
cntr_idxs_ptr = cntr_idxs;
#endif
for(uint i=0; i<k; i++) {
centre_buffer[i] = centres[i];
cntr_idxs_ptr->idx[i] = i;
}
uint st = 0;
uint cst = 0;
stack_counter = 0;
uint max_stack_counter = 0;
uint centre_set_counter = 0;
//End of Initialisation
st=push_node(stack,st,root);
cst = cpush_node(cstack, cst, cntr_idxs, k, false, cntr_idxs, k); // first set (default set) never gets freed
while (st != 0) {
// fetch head of stack
uint u;
st = pop_node(stack,st,&u);
centre_set_ptr tmp_cntr_idxs;
centre_set_type *tmp_cntr_idxs_ptr;
uint tmp_k;
bool redundant;
cst = cpop_node(cstack,cst,&tmp_cntr_idxs,&tmp_k,&redundant);
#ifdef CUSTOM_DYN_ALLOC
tmp_cntr_idxs_ptr = make_pointer<centre_set_type>(centre_set_heap, tmp_cntr_idxs);
#else
tmp_cntr_idxs_ptr = tmp_cntr_idxs;
#endif
// buffer tree node
kdTree_type tmp_u;
tmp_u = tree_memory[u];
data_type_short tmp_centre_positions[KMAX];
for (uint i=0; i<tmp_k; i++) {
tmp_centre_positions[i] = centre_buffer[tmp_cntr_idxs_ptr->idx[i]].position_short;
}
// find closest centre to various points
data_type comp_point;
if ( (tmp_u.ileft == 0) && (tmp_u.iright == 0) ) {
comp_point = tmp_u.wgtCent;
} else {
comp_point = conv_short_to_long(tmp_u.midPoint_short);
}
uint tmp_search_idx;
data_type_short tmp_search_centre;
closest_to_point_direct_fi_mixed(comp_point, tmp_centre_positions, tmp_k, &tmp_search_idx, &tmp_search_centre);
data_type_short z_star = tmp_search_centre;
uint idx_closest = tmp_search_idx;
centre_set_ptr new_cntr_idxs;
centre_set_type *new_cntr_idxs_ptr;
bool centre_set_bound_reached = centre_set_counter >= CENTRE_SET_HEAP_BOUND-2;
uint new_k=0;
// allocate a new list
if (!centre_set_bound_reached ) {
#ifdef CUSTOM_DYN_ALLOC
new_cntr_idxs = malloc<uint>(freelist, &next_free_location);
new_cntr_idxs_ptr = make_pointer(centre_set_heap, new_cntr_idxs);
#else
new_cntr_idxs = new centre_set_type;
new_cntr_idxs_ptr = new_cntr_idxs;
#endif
centre_set_counter++;
// and copy candidates that survive pruning into it
// candidate pruning
for (uint i=0; i<tmp_k; i++) {
bool too_far;
tooFar_fi_short(z_star, tmp_centre_positions[i], tmp_u.bnd_lo_short, tmp_u.bnd_hi_short, &too_far);
if ( too_far==false ) {
new_cntr_idxs_ptr->idx[new_k] = tmp_cntr_idxs_ptr->idx[i];
new_k++;
}
}
}
// update sum_sq of centre
//coord_type tmp1_1, tmp2_1;
coord_type tmp1_2, tmp2_2;
data_type tmp_wgtCent = tmp_u.wgtCent;
for (uint d=0; d<D; d++) {
tmp_wgtCent.value[d] = tmp_wgtCent.value[d]>>FRACTIONAL_BITS;
}
// z_star == tmp_centre_positions[idx_closest] !
dot_product_fi_mixed(z_star,tmp_wgtCent,&tmp1_2);
dot_product_fi_short(z_star,z_star,&tmp2_2);
coord_type tmp1, tmp2;
uint tmp_idx;
tmp1 = tmp1_2;
tmp2 = tmp2_2>>FRACTIONAL_BITS;
tmp_idx = idx_closest;
// compute distortion
coord_type_short tmp_count = tmp_u.count_short;
coord_type tmp3 = saturate(tmp2)*saturate(tmp_count);
coord_type tmp_sum_sq = tmp_u.sum_sq+tmp3;
tmp_sum_sq = tmp_sum_sq-2*tmp1;
uint tmp_final_idx = tmp_cntr_idxs_ptr->idx[tmp_idx];
// write back
if ( ((tmp_u.ileft == 0) && (tmp_u.iright == 0)) || ((new_k == 1) && (last_run == false)) ) {
// weighted centroid of this centre
for (uint d=0; d<D; d++) {
centre_buffer[tmp_final_idx].wgtCent.value[d] += tmp_u.wgtCent.value[d];
}
// update number of points assigned to centre
centre_buffer[tmp_final_idx].count_short += tmp_u.count_short;
centre_buffer[tmp_final_idx].sum_sq += tmp_sum_sq;
if (!centre_set_bound_reached ) {
#ifdef CUSTOM_DYN_ALLOC
free<uint>(freelist, &next_free_location, new_cntr_idxs);
#else
delete new_cntr_idxs;
#endif
centre_set_counter--;
}
if (last_run == true) {
//printf("%d: %d\n",tmp_u.pointAddr,tmp_u.sum_sq);
output_array[tmp_u.pointAddr] = z_star;
}
} else {
uint left_child = tmp_u.ileft;
uint right_child = tmp_u.iright;
// push children onto stack
st = push_node(stack,st,right_child);
st = push_node(stack,st,left_child);
// push centre lists for both children onto stack
if (!centre_set_bound_reached) {
cst = cpush_node(cstack,cst,new_cntr_idxs,new_k,true, cntr_idxs,k);
cst = cpush_node(cstack,cst,new_cntr_idxs,new_k,false, cntr_idxs,k);
} else {
cst = cpush_node(cstack,cst,cntr_idxs,k,true, cntr_idxs,k);
cst = cpush_node(cstack,cst,cntr_idxs,k,false, cntr_idxs,k);
}
}
// delete if centre set was used twice
if (redundant == true) {
#ifdef CUSTOM_DYN_ALLOC
free<uint>(freelist, &next_free_location, tmp_cntr_idxs);
#else
delete tmp_cntr_idxs;
#endif
centre_set_counter--;
}
if (stack_counter > max_stack_counter)
max_stack_counter = stack_counter;
visited_nodes++;
node_centre_pairs += tmp_k;
}
#ifdef VERBOSE
printf("Visited nodes: %d, node-centre pairs: %d\n",visited_nodes,node_centre_pairs);
#endif
for(uint i=0; i<k; i++) {
centres[i] = centre_buffer[i];
}
}
<|endoftext|>
|
<commit_before><commit_msg>ATO-525 - using dynamic cast for the tree loading - fix problems with non tree keys<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2017 The Energi Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/energi-config.h"
#endif
#include "util.h"
#include "uritests.h"
#include "compattests.h"
#include "trafficgraphdatatests.h"
#ifdef ENABLE_WALLET
#include "paymentservertests.h"
#endif
#include <QCoreApplication>
#include <QObject>
#include <QTest>
#include <openssl/ssl.h>
#if defined(QT_STATICPLUGIN) && QT_VERSION < 0x050000
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
#endif
// This is all you need to run all the tests
int main(int argc, char *argv[])
{
SetupEnvironment();
bool fInvalid = false;
// Don't remove this, it's needed to access
// QCoreApplication:: in the tests
QCoreApplication app(argc, argv);
app.setApplicationName("Energi-Qt-test");
SSL_library_init();
URITests test1;
if (QTest::qExec(&test1, app.arguments()) != 0)
fInvalid = true;
#ifdef ENABLE_WALLET
PaymentServerTests test2;
if (QTest::qExec(&test2, app.arguments()) != 0)
fInvalid = true;
#endif
CompatTests test4;
if (QTest::qExec(&test4, app.arguments()) != 0)
fInvalid = true;
TrafficGraphDataTests test5;
if (QTest::qExec(&test5, app.arguments()) != 0)
fInvalid = true;
return fInvalid;
}
<commit_msg>generate unique filenames for test outputs<commit_after>// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2017 The Energi Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/energi-config.h"
#endif
#include "util.h"
#include "uritests.h"
#include "compattests.h"
#include "trafficgraphdatatests.h"
#ifdef ENABLE_WALLET
#include "paymentservertests.h"
#endif
#include <QCoreApplication>
#include <QObject>
#include <QTest>
#include <openssl/ssl.h>
#if defined(QT_STATICPLUGIN) && QT_VERSION < 0x050000
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
#endif
// append the test case name to the output file name to allow running multiple test suites without overwriting the output file
QStringList getArguments(QStringList const & app_args, QString objectName)
{
QStringList result(app_args);
result.replaceInStrings(QRegExp("^(.*)\\.(.+)$"), QString("\\1_") + objectName + QString(".\\2"));
return result;
}
// This is all you need to run all the tests
int main(int argc, char *argv[])
{
SetupEnvironment();
bool fInvalid = false;
// Don't remove this, it's needed to access
// QCoreApplication:: in the tests
QCoreApplication app(argc, argv);
app.setApplicationName("Energi-Qt-test");
SSL_library_init();
auto const & app_args = app.arguments();
URITests test1;
test1.setObjectName("URITests");
if (QTest::qExec(&test1, getArguments(app_args, test1.objectName())) != 0)
fInvalid = true;
#ifdef ENABLE_WALLET
PaymentServerTests test2;
test2.setObjectName("PaymentServerTests");
if (QTest::qExec(&test2, getArguments(app_args, test2.objectName())) != 0)
fInvalid = true;
#endif
CompatTests test4;
test4.setObjectName("CompatTests");
if (QTest::qExec(&test4, getArguments(app_args, test4.objectName())) != 0)
fInvalid = true;
TrafficGraphDataTests test5;
test5.setObjectName("TrafficGraphDataTests");
if (QTest::qExec(&test5, getArguments(app_args, test5.objectName())) != 0)
fInvalid = true;
return fInvalid;
}
<|endoftext|>
|
<commit_before>//===-- sanitizer_procmaps_mac.cc -----------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Information about the process mappings (Mac-specific parts).
//===----------------------------------------------------------------------===//
#include "sanitizer_platform.h"
#if SANITIZER_MAC
#include "sanitizer_common.h"
#include "sanitizer_placement_new.h"
#include "sanitizer_procmaps.h"
#include <mach-o/dyld.h>
#include <mach-o/loader.h>
namespace __sanitizer {
MemoryMappingLayout::MemoryMappingLayout(bool cache_enabled) {
Reset();
}
MemoryMappingLayout::~MemoryMappingLayout() {
}
// More information about Mach-O headers can be found in mach-o/loader.h
// Each Mach-O image has a header (mach_header or mach_header_64) starting with
// a magic number, and a list of linker load commands directly following the
// header.
// A load command is at least two 32-bit words: the command type and the
// command size in bytes. We're interested only in segment load commands
// (LC_SEGMENT and LC_SEGMENT_64), which tell that a part of the file is mapped
// into the task's address space.
// The |vmaddr|, |vmsize| and |fileoff| fields of segment_command or
// segment_command_64 correspond to the memory address, memory size and the
// file offset of the current memory segment.
// Because these fields are taken from the images as is, one needs to add
// _dyld_get_image_vmaddr_slide() to get the actual addresses at runtime.
void MemoryMappingLayout::Reset() {
// Count down from the top.
// TODO(glider): as per man 3 dyld, iterating over the headers with
// _dyld_image_count is thread-unsafe. We need to register callbacks for
// adding and removing images which will invalidate the MemoryMappingLayout
// state.
current_image_ = _dyld_image_count();
current_load_cmd_count_ = -1;
current_load_cmd_addr_ = 0;
current_magic_ = 0;
current_filetype_ = 0;
}
// static
void MemoryMappingLayout::CacheMemoryMappings() {
// No-op on Mac for now.
}
void MemoryMappingLayout::LoadFromCache() {
// No-op on Mac for now.
}
// Next and NextSegmentLoad were inspired by base/sysinfo.cc in
// Google Perftools, http://code.google.com/p/google-perftools.
// NextSegmentLoad scans the current image for the next segment load command
// and returns the start and end addresses and file offset of the corresponding
// segment.
// Note that the segment addresses are not necessarily sorted.
template<u32 kLCSegment, typename SegmentCommand>
bool MemoryMappingLayout::NextSegmentLoad(
uptr *start, uptr *end, uptr *offset,
char filename[], uptr filename_size, uptr *protection) {
if (protection)
UNIMPLEMENTED();
const char* lc = current_load_cmd_addr_;
current_load_cmd_addr_ += ((const load_command *)lc)->cmdsize;
if (((const load_command *)lc)->cmd == kLCSegment) {
const sptr dlloff = _dyld_get_image_vmaddr_slide(current_image_);
const SegmentCommand* sc = (const SegmentCommand *)lc;
if (start) *start = sc->vmaddr + dlloff;
if (end) *end = sc->vmaddr + sc->vmsize + dlloff;
if (offset) {
if (current_filetype_ == /*MH_EXECUTE*/ 0x2) {
*offset = sc->vmaddr;
} else {
*offset = sc->fileoff;
}
}
if (filename) {
internal_strncpy(filename, _dyld_get_image_name(current_image_),
filename_size);
}
return true;
}
return false;
}
bool MemoryMappingLayout::Next(uptr *start, uptr *end, uptr *offset,
char filename[], uptr filename_size,
uptr *protection) {
for (; current_image_ >= 0; current_image_--) {
const mach_header* hdr = _dyld_get_image_header(current_image_);
if (!hdr) continue;
if (current_load_cmd_count_ < 0) {
// Set up for this image;
current_load_cmd_count_ = hdr->ncmds;
current_magic_ = hdr->magic;
current_filetype_ = hdr->filetype;
switch (current_magic_) {
#ifdef MH_MAGIC_64
case MH_MAGIC_64: {
current_load_cmd_addr_ = (char*)hdr + sizeof(mach_header_64);
break;
}
#endif
case MH_MAGIC: {
current_load_cmd_addr_ = (char*)hdr + sizeof(mach_header);
break;
}
default: {
continue;
}
}
}
for (; current_load_cmd_count_ >= 0; current_load_cmd_count_--) {
switch (current_magic_) {
// current_magic_ may be only one of MH_MAGIC, MH_MAGIC_64.
#ifdef MH_MAGIC_64
case MH_MAGIC_64: {
if (NextSegmentLoad<LC_SEGMENT_64, struct segment_command_64>(
start, end, offset, filename, filename_size, protection))
return true;
break;
}
#endif
case MH_MAGIC: {
if (NextSegmentLoad<LC_SEGMENT, struct segment_command>(
start, end, offset, filename, filename_size, protection))
return true;
break;
}
}
}
// If we get here, no more load_cmd's in this image talk about
// segments. Go on to the next image.
}
return false;
}
uptr MemoryMappingLayout::DumpListOfModules(LoadedModule *modules,
uptr max_modules,
string_predicate_t filter) {
Reset();
uptr cur_beg, cur_end, prot;
InternalScopedBuffer<char> module_name(kMaxPathLength);
uptr n_modules = 0;
for (uptr i = 0; n_modules < max_modules &&
Next(&cur_beg, &cur_end, 0, module_name.data(),
module_name.size(), &prot);
i++) {
const char *cur_name = module_name.data();
if (cur_name[0] == '\0')
continue;
if (filter && !filter(cur_name))
continue;
LoadedModule *cur_module = 0;
if (n_modules > 0 &&
0 == internal_strcmp(cur_name, modules[n_modules - 1].full_name())) {
cur_module = &modules[n_modules - 1];
} else {
void *mem = &modules[n_modules];
cur_module = new(mem) LoadedModule(cur_name, cur_beg);
n_modules++;
}
cur_module->addAddressRange(cur_beg, cur_end, prot & kProtectionExecute);
}
return n_modules;
}
} // namespace __sanitizer
#endif // SANITIZER_MAC
<commit_msg>[ASan] When iterating over segments on OSX, treat the segments' initial protection level as their current protection level. This fixes the UNIMPLEMENTED check that started to fire on OSX after r210649.<commit_after>//===-- sanitizer_procmaps_mac.cc -----------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Information about the process mappings (Mac-specific parts).
//===----------------------------------------------------------------------===//
#include "sanitizer_platform.h"
#if SANITIZER_MAC
#include "sanitizer_common.h"
#include "sanitizer_placement_new.h"
#include "sanitizer_procmaps.h"
#include <mach-o/dyld.h>
#include <mach-o/loader.h>
namespace __sanitizer {
MemoryMappingLayout::MemoryMappingLayout(bool cache_enabled) {
Reset();
}
MemoryMappingLayout::~MemoryMappingLayout() {
}
// More information about Mach-O headers can be found in mach-o/loader.h
// Each Mach-O image has a header (mach_header or mach_header_64) starting with
// a magic number, and a list of linker load commands directly following the
// header.
// A load command is at least two 32-bit words: the command type and the
// command size in bytes. We're interested only in segment load commands
// (LC_SEGMENT and LC_SEGMENT_64), which tell that a part of the file is mapped
// into the task's address space.
// The |vmaddr|, |vmsize| and |fileoff| fields of segment_command or
// segment_command_64 correspond to the memory address, memory size and the
// file offset of the current memory segment.
// Because these fields are taken from the images as is, one needs to add
// _dyld_get_image_vmaddr_slide() to get the actual addresses at runtime.
void MemoryMappingLayout::Reset() {
// Count down from the top.
// TODO(glider): as per man 3 dyld, iterating over the headers with
// _dyld_image_count is thread-unsafe. We need to register callbacks for
// adding and removing images which will invalidate the MemoryMappingLayout
// state.
current_image_ = _dyld_image_count();
current_load_cmd_count_ = -1;
current_load_cmd_addr_ = 0;
current_magic_ = 0;
current_filetype_ = 0;
}
// static
void MemoryMappingLayout::CacheMemoryMappings() {
// No-op on Mac for now.
}
void MemoryMappingLayout::LoadFromCache() {
// No-op on Mac for now.
}
// Next and NextSegmentLoad were inspired by base/sysinfo.cc in
// Google Perftools, http://code.google.com/p/google-perftools.
// NextSegmentLoad scans the current image for the next segment load command
// and returns the start and end addresses and file offset of the corresponding
// segment.
// Note that the segment addresses are not necessarily sorted.
template<u32 kLCSegment, typename SegmentCommand>
bool MemoryMappingLayout::NextSegmentLoad(
uptr *start, uptr *end, uptr *offset,
char filename[], uptr filename_size, uptr *protection) {
const char* lc = current_load_cmd_addr_;
current_load_cmd_addr_ += ((const load_command *)lc)->cmdsize;
if (((const load_command *)lc)->cmd == kLCSegment) {
const sptr dlloff = _dyld_get_image_vmaddr_slide(current_image_);
const SegmentCommand* sc = (const SegmentCommand *)lc;
if (start) *start = sc->vmaddr + dlloff;
if (protection) {
// Return the initial protection.
*protection = sc->initprot;
}
if (end) *end = sc->vmaddr + sc->vmsize + dlloff;
if (offset) {
if (current_filetype_ == /*MH_EXECUTE*/ 0x2) {
*offset = sc->vmaddr;
} else {
*offset = sc->fileoff;
}
}
if (filename) {
internal_strncpy(filename, _dyld_get_image_name(current_image_),
filename_size);
}
return true;
}
return false;
}
bool MemoryMappingLayout::Next(uptr *start, uptr *end, uptr *offset,
char filename[], uptr filename_size,
uptr *protection) {
for (; current_image_ >= 0; current_image_--) {
const mach_header* hdr = _dyld_get_image_header(current_image_);
if (!hdr) continue;
if (current_load_cmd_count_ < 0) {
// Set up for this image;
current_load_cmd_count_ = hdr->ncmds;
current_magic_ = hdr->magic;
current_filetype_ = hdr->filetype;
switch (current_magic_) {
#ifdef MH_MAGIC_64
case MH_MAGIC_64: {
current_load_cmd_addr_ = (char*)hdr + sizeof(mach_header_64);
break;
}
#endif
case MH_MAGIC: {
current_load_cmd_addr_ = (char*)hdr + sizeof(mach_header);
break;
}
default: {
continue;
}
}
}
for (; current_load_cmd_count_ >= 0; current_load_cmd_count_--) {
switch (current_magic_) {
// current_magic_ may be only one of MH_MAGIC, MH_MAGIC_64.
#ifdef MH_MAGIC_64
case MH_MAGIC_64: {
if (NextSegmentLoad<LC_SEGMENT_64, struct segment_command_64>(
start, end, offset, filename, filename_size, protection))
return true;
break;
}
#endif
case MH_MAGIC: {
if (NextSegmentLoad<LC_SEGMENT, struct segment_command>(
start, end, offset, filename, filename_size, protection))
return true;
break;
}
}
}
// If we get here, no more load_cmd's in this image talk about
// segments. Go on to the next image.
}
return false;
}
uptr MemoryMappingLayout::DumpListOfModules(LoadedModule *modules,
uptr max_modules,
string_predicate_t filter) {
Reset();
uptr cur_beg, cur_end, prot;
InternalScopedBuffer<char> module_name(kMaxPathLength);
uptr n_modules = 0;
for (uptr i = 0; n_modules < max_modules &&
Next(&cur_beg, &cur_end, 0, module_name.data(),
module_name.size(), &prot);
i++) {
const char *cur_name = module_name.data();
if (cur_name[0] == '\0')
continue;
if (filter && !filter(cur_name))
continue;
LoadedModule *cur_module = 0;
if (n_modules > 0 &&
0 == internal_strcmp(cur_name, modules[n_modules - 1].full_name())) {
cur_module = &modules[n_modules - 1];
} else {
void *mem = &modules[n_modules];
cur_module = new(mem) LoadedModule(cur_name, cur_beg);
n_modules++;
}
cur_module->addAddressRange(cur_beg, cur_end, prot & kProtectionExecute);
}
return n_modules;
}
} // namespace __sanitizer
#endif // SANITIZER_MAC
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2010-2014 Jeremy Lainé
* Contact: https://github.com/jlaine/qdjango
*
* This file is part of the QDjango Library.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
#include <QLocalSocket>
#include <QTcpSocket>
#include <QtTest>
#include <QUrl>
#include "QDjangoFastCgiServer.h"
#include "QDjangoFastCgiServer_p.h"
#include "QDjangoHttpController.h"
#include "QDjangoHttpRequest.h"
#include "QDjangoHttpResponse.h"
#include "QDjangoFastCgiServer.h"
#include "QDjangoUrlResolver.h"
#define ERROR_DATA QByteArray("Status: 500 Internal Server Error\r\n" \
"Content-Length: 107\r\n" \
"Content-Type: text/html; charset=utf-8\r\n" \
"\r\n" \
"<html><head><title>Error</title></head><body><p>An internal server error was encountered.</p></body></html>")
#define NOT_FOUND_DATA QByteArray("Status: 404 Not Found\r\n" \
"Content-Length: 107\r\n" \
"Content-Type: text/html; charset=utf-8\r\n" \
"\r\n" \
"<html><head><title>Error</title></head><body><p>The document you requested was not found.</p></body></html>")
#define POST_DATA QByteArray("Status: 200 OK\r\n" \
"Content-Length: 27\r\n" \
"Content-Type: text/plain\r\n" \
"\r\n" \
"method=POST|path=/|post=bar")
#define ROOT_DATA QByteArray("Status: 200 OK\r\n" \
"Content-Length: 17\r\n" \
"Content-Type: text/plain\r\n" \
"\r\n" \
"method=GET|path=/")
#define QUERY_STRING_DATA QByteArray("Status: 200 OK\r\n" \
"Content-Length: 25\r\n" \
"Content-Type: text/plain\r\n" \
"\r\n" \
"method=GET|path=/|get=bar")
class QDjangoFastCgiReply : public QObject
{
Q_OBJECT
public:
QDjangoFastCgiReply(QObject *parent = 0)
: QObject(parent) {};
QByteArray data;
signals:
void finished();
};
class QDjangoFastCgiClient : public QObject
{
Q_OBJECT
public:
QDjangoFastCgiClient(QIODevice *socket);
QDjangoFastCgiReply* request(const QString &method, const QUrl &url, const QByteArray &data);
private slots:
void _q_readyRead();
private:
QIODevice *m_device;
QMap<quint16, QDjangoFastCgiReply*> m_replies;
quint16 m_requestId;
};
QDjangoFastCgiClient::QDjangoFastCgiClient(QIODevice *socket)
: m_device(socket)
, m_requestId(0)
{
connect(socket, SIGNAL(readyRead()), this, SLOT(_q_readyRead()));
};
QDjangoFastCgiReply* QDjangoFastCgiClient::request(const QString &method, const QUrl &url, const QByteArray &data)
{
const quint16 requestId = ++m_requestId;
QDjangoFastCgiReply *reply = new QDjangoFastCgiReply(this);
m_replies[requestId] = reply;
QByteArray headerBuffer(FCGI_HEADER_LEN, '\0');
FCGI_Header *header = (FCGI_Header*)headerBuffer.data();
QByteArray ba;
// BEGIN REQUEST
ba = QByteArray("\x01\x00\x00\x00\x00\x00\x00\x00", 8);
header->version = 1;
FCGI_Header_setRequestId(header, requestId);
header->type = FCGI_BEGIN_REQUEST;
FCGI_Header_setContentLength(header, ba.size());
m_device->write(headerBuffer + ba);
QMap<QByteArray, QByteArray> params;
params["PATH_INFO"] = url.path().toUtf8();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
params["QUERY_STRING"] = url.query().toUtf8();
#else
params["QUERY_STRING"] = url.encodedQuery();
#endif
params["REQUEST_URI"] = url.toString().toUtf8();
params["REQUEST_METHOD"] = method.toUtf8();
ba.clear();
foreach (const QByteArray &key, params.keys()) {
const QByteArray value = params.value(key);
ba.append(char(key.size()));
ba.append(char(value.size()));
ba.append(key);
ba.append(value);
}
// FAST CGI PARAMS
header->type = FCGI_PARAMS;
FCGI_Header_setContentLength(header, ba.size());
m_device->write(headerBuffer + ba);
// STDIN
if (data.size() > 0) {
header->type = FCGI_STDIN;
FCGI_Header_setContentLength(header, data.size());
m_device->write(headerBuffer + data);
}
header->type = FCGI_STDIN;
FCGI_Header_setContentLength(header, 0);
m_device->write(headerBuffer);
return reply;
}
void QDjangoFastCgiClient::_q_readyRead()
{
char inputBuffer[FCGI_RECORD_SIZE];
FCGI_Header *header = (FCGI_Header*)inputBuffer;
while (m_device->bytesAvailable()) {
if (m_device->read(inputBuffer, FCGI_HEADER_LEN) != FCGI_HEADER_LEN) {
qWarning("header read fail");
return;
}
const quint16 contentLength = FCGI_Header_contentLength(header);
const quint16 requestId = FCGI_Header_requestId(header);
const quint16 bodyLength = contentLength + header->paddingLength;
if (m_device->read(inputBuffer + FCGI_HEADER_LEN, bodyLength) != bodyLength) {
qWarning("body read fail");
return;
}
if (!m_replies.contains(requestId)) {
qWarning() << "unknown request" << requestId;
return;
}
if (header->type == FCGI_STDOUT) {
const QByteArray data = QByteArray(inputBuffer + FCGI_HEADER_LEN, contentLength);
m_replies[requestId]->data += data;
} else if (header->type == FCGI_END_REQUEST) {
QMetaObject::invokeMethod(m_replies[requestId], "finished");
}
}
}
/** Test QDjangoFastCgiServer class.
*/
class tst_QDjangoFastCgiServer : public QObject
{
Q_OBJECT
private slots:
void cleanup();
void init();
void testLocal_data();
void testLocal();
void testTcp_data();
void testTcp();
QDjangoHttpResponse* _q_index(const QDjangoHttpRequest &request);
QDjangoHttpResponse* _q_error(const QDjangoHttpRequest &request);
private:
QDjangoFastCgiServer *server;
};
void tst_QDjangoFastCgiServer::cleanup()
{
server->close();
delete server;
}
void tst_QDjangoFastCgiServer::init()
{
server = new QDjangoFastCgiServer;
server->urls()->set(QRegExp(QLatin1String(QLatin1String("^$"))), this, "_q_index");
server->urls()->set(QRegExp(QLatin1String("^internal-server-error$")), this, "_q_error");
}
void tst_QDjangoFastCgiServer::testLocal_data()
{
QTest::addColumn<QString>("method");
QTest::addColumn<QString>("path");
QTest::addColumn<QByteArray>("data");
QTest::addColumn<QByteArray>("response");
QTest::newRow("root") << "GET" << "/" << QByteArray() << ROOT_DATA;
QTest::newRow("query-string") << "GET" << "/?message=bar" << QByteArray() << QUERY_STRING_DATA;
QTest::newRow("not-found") << "GET" << "/not-found" << QByteArray() << NOT_FOUND_DATA;
QTest::newRow("internal-server-error") << "GET" << "/internal-server-error" << QByteArray() << ERROR_DATA;
QTest::newRow("post") << "POST" << "/" << QByteArray("message=bar") << POST_DATA;
}
void tst_QDjangoFastCgiServer::testLocal()
{
QFETCH(QString, method);
QFETCH(QString, path);
QFETCH(QByteArray, data);
QFETCH(QByteArray, response);
const QString name("/tmp/qdjangofastcgi.socket");
QCOMPARE(server->listen(name), true);
QLocalSocket socket;
socket.connectToServer(name);
QEventLoop loop;
QDjangoFastCgiClient client(&socket);
// check socket is connected
QCOMPARE(socket.state(), QLocalSocket::ConnectedState);
// wait for reply
QDjangoFastCgiReply *reply = client.request(method, path, data);
QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QCOMPARE(socket.state(), QLocalSocket::ConnectedState);
QCOMPARE(reply->data, response);
// wait for connection to close
QObject::connect(&socket, SIGNAL(disconnected()), &loop, SLOT(quit()));
loop.exec();
QCOMPARE(socket.state(), QLocalSocket::UnconnectedState);
}
void tst_QDjangoFastCgiServer::testTcp_data()
{
QTest::addColumn<QString>("method");
QTest::addColumn<QString>("path");
QTest::addColumn<QByteArray>("data");
QTest::addColumn<QByteArray>("response");
QTest::newRow("root") << "GET" << "/" << QByteArray() << ROOT_DATA;
QTest::newRow("query-string") << "GET" << "/?message=bar" << QByteArray() << QUERY_STRING_DATA;
QTest::newRow("not-found") << "GET" << "/not-found" << QByteArray() << NOT_FOUND_DATA;
QTest::newRow("internal-server-error") << "GET" << "/internal-server-error" << QByteArray() << ERROR_DATA;
QTest::newRow("post") << "POST" << "/" << QByteArray("message=bar") << POST_DATA;
}
void tst_QDjangoFastCgiServer::testTcp()
{
QFETCH(QString, method);
QFETCH(QString, path);
QFETCH(QByteArray, data);
QFETCH(QByteArray, response);
QCOMPARE(server->listen(QHostAddress::LocalHost, 8123), true);
QTcpSocket socket;
socket.connectToHost("127.0.0.1", 8123);
QEventLoop loop;
QDjangoFastCgiClient client(&socket);
// wait for socket to connect
QObject::connect(&socket, SIGNAL(connected()), &loop, SLOT(quit()));
loop.exec();
QCOMPARE(socket.state(), QAbstractSocket::ConnectedState);
// wait for reply
QDjangoFastCgiReply *reply = client.request(method, path, data);
QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QCOMPARE(socket.state(), QAbstractSocket::ConnectedState);
QCOMPARE(reply->data, response);
// wait for connection to close
QObject::connect(&socket, SIGNAL(disconnected()), &loop, SLOT(quit()));
loop.exec();
QCOMPARE(socket.state(), QAbstractSocket::UnconnectedState);
}
QDjangoHttpResponse *tst_QDjangoFastCgiServer::_q_index(const QDjangoHttpRequest &request)
{
QDjangoHttpResponse *response = new QDjangoHttpResponse;
response->setHeader(QLatin1String("Content-Type"), QLatin1String("text/plain"));
QString output = QLatin1String("method=") + request.method();
output += QLatin1String("|path=") + request.path();
const QString getValue = request.get(QLatin1String("message"));
if (!getValue.isEmpty())
output += QLatin1String("|get=") + getValue;
const QString postValue = request.post(QLatin1String("message"));
if (!postValue.isEmpty())
output += QLatin1String("|post=") + postValue;
response->setBody(output.toUtf8());
return response;
}
QDjangoHttpResponse *tst_QDjangoFastCgiServer::_q_error(const QDjangoHttpRequest &request)
{
Q_UNUSED(request);
return QDjangoHttpController::serveInternalServerError(request);
}
QTEST_MAIN(tst_QDjangoFastCgiServer)
#include "tst_qdjangofastcgiserver.moc"
<commit_msg>improve fastcgi tests<commit_after>/*
* Copyright (C) 2010-2014 Jeremy Lainé
* Contact: https://github.com/jlaine/qdjango
*
* This file is part of the QDjango Library.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
#include <QLocalSocket>
#include <QTcpSocket>
#include <QtTest>
#include <QUrl>
#include "QDjangoFastCgiServer.h"
#include "QDjangoFastCgiServer_p.h"
#include "QDjangoHttpController.h"
#include "QDjangoHttpRequest.h"
#include "QDjangoHttpResponse.h"
#include "QDjangoFastCgiServer.h"
#include "QDjangoUrlResolver.h"
#define ERROR_DATA QByteArray("Status: 500 Internal Server Error\r\n" \
"Content-Length: 107\r\n" \
"Content-Type: text/html; charset=utf-8\r\n" \
"\r\n" \
"<html><head><title>Error</title></head><body><p>An internal server error was encountered.</p></body></html>")
#define NOT_FOUND_DATA QByteArray("Status: 404 Not Found\r\n" \
"Content-Length: 107\r\n" \
"Content-Type: text/html; charset=utf-8\r\n" \
"\r\n" \
"<html><head><title>Error</title></head><body><p>The document you requested was not found.</p></body></html>")
#define POST_DATA QByteArray("Status: 200 OK\r\n" \
"Content-Length: 27\r\n" \
"Content-Type: text/plain\r\n" \
"\r\n" \
"method=POST|path=/|post=bar")
#define ROOT_DATA QByteArray("Status: 200 OK\r\n" \
"Content-Length: 17\r\n" \
"Content-Type: text/plain\r\n" \
"\r\n" \
"method=GET|path=/")
#define QUERY_STRING_DATA QByteArray("Status: 200 OK\r\n" \
"Content-Length: 25\r\n" \
"Content-Type: text/plain\r\n" \
"\r\n" \
"method=GET|path=/|get=bar")
class QDjangoFastCgiReply : public QObject
{
Q_OBJECT
public:
QDjangoFastCgiReply(QObject *parent = 0)
: QObject(parent) {};
QByteArray data;
signals:
void finished();
};
class QDjangoFastCgiClient : public QObject
{
Q_OBJECT
public:
QDjangoFastCgiClient(QIODevice *socket);
QDjangoFastCgiReply* request(const QString &method, const QUrl &url, const QByteArray &data);
private slots:
void _q_readyRead();
private:
QIODevice *m_device;
QMap<quint16, QDjangoFastCgiReply*> m_replies;
quint16 m_requestId;
};
QDjangoFastCgiClient::QDjangoFastCgiClient(QIODevice *socket)
: m_device(socket)
, m_requestId(0)
{
connect(socket, SIGNAL(readyRead()), this, SLOT(_q_readyRead()));
};
QDjangoFastCgiReply* QDjangoFastCgiClient::request(const QString &method, const QUrl &url, const QByteArray &data)
{
const quint16 requestId = ++m_requestId;
QDjangoFastCgiReply *reply = new QDjangoFastCgiReply(this);
m_replies[requestId] = reply;
QByteArray headerBuffer(FCGI_HEADER_LEN, '\0');
FCGI_Header *header = (FCGI_Header*)headerBuffer.data();
QByteArray ba;
// BEGIN REQUEST
ba = QByteArray("\x01\x00\x00\x00\x00\x00\x00\x00", 8);
header->version = 1;
FCGI_Header_setRequestId(header, requestId);
header->type = FCGI_BEGIN_REQUEST;
FCGI_Header_setContentLength(header, ba.size());
m_device->write(headerBuffer + ba);
QMap<QByteArray, QByteArray> params;
params["PATH_INFO"] = url.path().toUtf8();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
params["QUERY_STRING"] = url.query().toUtf8();
#else
params["QUERY_STRING"] = url.encodedQuery();
#endif
params["REQUEST_URI"] = url.toString().toUtf8();
params["REQUEST_METHOD"] = method.toUtf8();
ba.clear();
foreach (const QByteArray &key, params.keys()) {
const QByteArray value = params.value(key);
ba.append(char(key.size()));
ba.append(char(value.size()));
ba.append(key);
ba.append(value);
}
// FAST CGI PARAMS
header->type = FCGI_PARAMS;
FCGI_Header_setContentLength(header, ba.size());
m_device->write(headerBuffer + ba);
// STDIN
if (data.size() > 0) {
header->type = FCGI_STDIN;
FCGI_Header_setContentLength(header, data.size());
m_device->write(headerBuffer + data);
}
header->type = FCGI_STDIN;
FCGI_Header_setContentLength(header, 0);
m_device->write(headerBuffer);
return reply;
}
void QDjangoFastCgiClient::_q_readyRead()
{
char inputBuffer[FCGI_RECORD_SIZE];
FCGI_Header *header = (FCGI_Header*)inputBuffer;
while (m_device->bytesAvailable()) {
if (m_device->read(inputBuffer, FCGI_HEADER_LEN) != FCGI_HEADER_LEN) {
qWarning("header read fail");
return;
}
const quint16 contentLength = FCGI_Header_contentLength(header);
const quint16 requestId = FCGI_Header_requestId(header);
const quint16 bodyLength = contentLength + header->paddingLength;
if (m_device->read(inputBuffer + FCGI_HEADER_LEN, bodyLength) != bodyLength) {
qWarning("body read fail");
return;
}
if (!m_replies.contains(requestId)) {
qWarning() << "unknown request" << requestId;
return;
}
if (header->type == FCGI_STDOUT) {
const QByteArray data = QByteArray(inputBuffer + FCGI_HEADER_LEN, contentLength);
m_replies[requestId]->data += data;
} else if (header->type == FCGI_END_REQUEST) {
QMetaObject::invokeMethod(m_replies[requestId], "finished");
}
}
}
/** Test QDjangoFastCgiServer class.
*/
class tst_QDjangoFastCgiServer : public QObject
{
Q_OBJECT
private slots:
void cleanup();
void init();
void testAbort();
void testBadBegin();
void testBadRequestId();
void testBadRequestType();
void testLocal_data();
void testLocal();
void testTcp_data();
void testTcp();
QDjangoHttpResponse* _q_index(const QDjangoHttpRequest &request);
QDjangoHttpResponse* _q_error(const QDjangoHttpRequest &request);
private:
QDjangoFastCgiServer *server;
};
void tst_QDjangoFastCgiServer::cleanup()
{
server->close();
delete server;
}
void tst_QDjangoFastCgiServer::init()
{
server = new QDjangoFastCgiServer;
server->urls()->set(QRegExp(QLatin1String(QLatin1String("^$"))), this, "_q_index");
server->urls()->set(QRegExp(QLatin1String("^internal-server-error$")), this, "_q_error");
}
void tst_QDjangoFastCgiServer::testAbort()
{
const QString name("/tmp/qdjangofastcgi.socket");
QCOMPARE(server->listen(name), true);
QLocalSocket socket;
socket.connectToServer(name);
QByteArray headerBuffer(FCGI_HEADER_LEN, '\0');
FCGI_Header *header = (FCGI_Header*)headerBuffer.data();
header->version = 1;
FCGI_Header_setRequestId(header, 1);
// check socket is connected
QCOMPARE(socket.state(), QLocalSocket::ConnectedState);
// BEGIN REQUEST
const QByteArray ba("\x01\x00\x00\x00\x00\x00\x00\x00", 8);
header->type = FCGI_BEGIN_REQUEST;
FCGI_Header_setContentLength(header, ba.size());
socket.write(headerBuffer + ba);
// ABORT REQUEST
header->type = FCGI_ABORT_REQUEST;
FCGI_Header_setContentLength(header, 0);
socket.write(headerBuffer);
// wait for connection to close
QEventLoop loop;
QObject::connect(&socket, SIGNAL(disconnected()), &loop, SLOT(quit()));
loop.exec();
QCOMPARE(socket.state(), QLocalSocket::UnconnectedState);
}
void tst_QDjangoFastCgiServer::testBadBegin()
{
const QString name("/tmp/qdjangofastcgi.socket");
QCOMPARE(server->listen(name), true);
QLocalSocket socket;
socket.connectToServer(name);
QByteArray headerBuffer(FCGI_HEADER_LEN, '\0');
FCGI_Header *header = (FCGI_Header*)headerBuffer.data();
header->version = 1;
FCGI_Header_setRequestId(header, 1);
// check socket is connected
QCOMPARE(socket.state(), QLocalSocket::ConnectedState);
// BEGIN REQUEST
const QByteArray ba("\x01\x00\x00\x00\x00\x00\x00\x00", 8);
header->type = FCGI_BEGIN_REQUEST;
FCGI_Header_setContentLength(header, ba.size());
socket.write(headerBuffer + ba);
// BEGIN REQUEST again
header->type = FCGI_BEGIN_REQUEST;
FCGI_Header_setContentLength(header, ba.size());
socket.write(headerBuffer + ba);
// wait for connection to close
QEventLoop loop;
QObject::connect(&socket, SIGNAL(disconnected()), &loop, SLOT(quit()));
loop.exec();
QCOMPARE(socket.state(), QLocalSocket::UnconnectedState);
}
void tst_QDjangoFastCgiServer::testBadRequestId()
{
const QString name("/tmp/qdjangofastcgi.socket");
QCOMPARE(server->listen(name), true);
QLocalSocket socket;
socket.connectToServer(name);
QByteArray headerBuffer(FCGI_HEADER_LEN, '\0');
FCGI_Header *header = (FCGI_Header*)headerBuffer.data();
header->version = 1;
FCGI_Header_setRequestId(header, 1);
// check socket is connected
QCOMPARE(socket.state(), QLocalSocket::ConnectedState);
// ABORT REQUEST
header->type = FCGI_ABORT_REQUEST;
FCGI_Header_setContentLength(header, 0);
socket.write(headerBuffer);
// wait for connection to close
QEventLoop loop;
QObject::connect(&socket, SIGNAL(disconnected()), &loop, SLOT(quit()));
loop.exec();
QCOMPARE(socket.state(), QLocalSocket::UnconnectedState);
}
void tst_QDjangoFastCgiServer::testBadRequestType()
{
const QString name("/tmp/qdjangofastcgi.socket");
QCOMPARE(server->listen(name), true);
QLocalSocket socket;
socket.connectToServer(name);
QByteArray headerBuffer(FCGI_HEADER_LEN, '\0');
FCGI_Header *header = (FCGI_Header*)headerBuffer.data();
header->version = 1;
FCGI_Header_setRequestId(header, 1);
// check socket is connected
QCOMPARE(socket.state(), QLocalSocket::ConnectedState);
// BEGIN REQUEST
const QByteArray ba("\x01\x00\x00\x00\x00\x00\x00\x00", 8);
header->type = FCGI_BEGIN_REQUEST;
FCGI_Header_setContentLength(header, ba.size());
socket.write(headerBuffer + ba);
// bogus request type
header->type = 7;
FCGI_Header_setContentLength(header, 0);
socket.write(headerBuffer);
// wait for connection to close
QEventLoop loop;
QObject::connect(&socket, SIGNAL(disconnected()), &loop, SLOT(quit()));
loop.exec();
QCOMPARE(socket.state(), QLocalSocket::UnconnectedState);
}
void tst_QDjangoFastCgiServer::testLocal_data()
{
QTest::addColumn<QString>("method");
QTest::addColumn<QString>("path");
QTest::addColumn<QByteArray>("data");
QTest::addColumn<QByteArray>("response");
QTest::newRow("root") << "GET" << "/" << QByteArray() << ROOT_DATA;
QTest::newRow("query-string") << "GET" << "/?message=bar" << QByteArray() << QUERY_STRING_DATA;
QTest::newRow("not-found") << "GET" << "/not-found" << QByteArray() << NOT_FOUND_DATA;
QTest::newRow("internal-server-error") << "GET" << "/internal-server-error" << QByteArray() << ERROR_DATA;
QTest::newRow("post") << "POST" << "/" << QByteArray("message=bar") << POST_DATA;
}
void tst_QDjangoFastCgiServer::testLocal()
{
QFETCH(QString, method);
QFETCH(QString, path);
QFETCH(QByteArray, data);
QFETCH(QByteArray, response);
const QString name("/tmp/qdjangofastcgi.socket");
QCOMPARE(server->listen(name), true);
QLocalSocket socket;
socket.connectToServer(name);
QEventLoop loop;
QDjangoFastCgiClient client(&socket);
// check socket is connected
QCOMPARE(socket.state(), QLocalSocket::ConnectedState);
// wait for reply
QDjangoFastCgiReply *reply = client.request(method, path, data);
QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QCOMPARE(socket.state(), QLocalSocket::ConnectedState);
QCOMPARE(reply->data, response);
// wait for connection to close
QObject::connect(&socket, SIGNAL(disconnected()), &loop, SLOT(quit()));
loop.exec();
QCOMPARE(socket.state(), QLocalSocket::UnconnectedState);
}
void tst_QDjangoFastCgiServer::testTcp_data()
{
QTest::addColumn<QString>("method");
QTest::addColumn<QString>("path");
QTest::addColumn<QByteArray>("data");
QTest::addColumn<QByteArray>("response");
QTest::newRow("root") << "GET" << "/" << QByteArray() << ROOT_DATA;
QTest::newRow("query-string") << "GET" << "/?message=bar" << QByteArray() << QUERY_STRING_DATA;
QTest::newRow("not-found") << "GET" << "/not-found" << QByteArray() << NOT_FOUND_DATA;
QTest::newRow("internal-server-error") << "GET" << "/internal-server-error" << QByteArray() << ERROR_DATA;
QTest::newRow("post") << "POST" << "/" << QByteArray("message=bar") << POST_DATA;
}
void tst_QDjangoFastCgiServer::testTcp()
{
QFETCH(QString, method);
QFETCH(QString, path);
QFETCH(QByteArray, data);
QFETCH(QByteArray, response);
QCOMPARE(server->listen(QHostAddress::LocalHost, 8123), true);
QTcpSocket socket;
socket.connectToHost("127.0.0.1", 8123);
QEventLoop loop;
QDjangoFastCgiClient client(&socket);
// wait for socket to connect
QObject::connect(&socket, SIGNAL(connected()), &loop, SLOT(quit()));
loop.exec();
QCOMPARE(socket.state(), QAbstractSocket::ConnectedState);
// wait for reply
QDjangoFastCgiReply *reply = client.request(method, path, data);
QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QCOMPARE(socket.state(), QAbstractSocket::ConnectedState);
QCOMPARE(reply->data, response);
// wait for connection to close
QObject::connect(&socket, SIGNAL(disconnected()), &loop, SLOT(quit()));
loop.exec();
QCOMPARE(socket.state(), QAbstractSocket::UnconnectedState);
}
QDjangoHttpResponse *tst_QDjangoFastCgiServer::_q_index(const QDjangoHttpRequest &request)
{
QDjangoHttpResponse *response = new QDjangoHttpResponse;
response->setHeader(QLatin1String("Content-Type"), QLatin1String("text/plain"));
QString output = QLatin1String("method=") + request.method();
output += QLatin1String("|path=") + request.path();
const QString getValue = request.get(QLatin1String("message"));
if (!getValue.isEmpty())
output += QLatin1String("|get=") + getValue;
const QString postValue = request.post(QLatin1String("message"));
if (!postValue.isEmpty())
output += QLatin1String("|post=") + postValue;
response->setBody(output.toUtf8());
return response;
}
QDjangoHttpResponse *tst_QDjangoFastCgiServer::_q_error(const QDjangoHttpRequest &request)
{
Q_UNUSED(request);
return QDjangoHttpController::serveInternalServerError(request);
}
QTEST_MAIN(tst_QDjangoFastCgiServer)
#include "tst_qdjangofastcgiserver.moc"
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used 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. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qorganizerasynchprocess.h"
#include "qtorganizer.h"
#include "qorganizermaemo5_p.h"
#include <QtCore/qtimer.h>
#include <QtCore/qcoreapplication.h>
QTM_USE_NAMESPACE
OrganizerRequestTimeoutTimer::OrganizerRequestTimeoutTimer(QOrganizerItemAbstractRequest *req, int msecs)
: m_req(req)
{
m_timeoutTimer = new QTimer();
connect(m_timeoutTimer, SIGNAL(timeout()), this, SLOT(internalTimeout()));
m_timeoutTimer->setSingleShot(true);
m_timeoutTimer->start(msecs);
}
OrganizerRequestTimeoutTimer::~OrganizerRequestTimeoutTimer()
{
delete m_timeoutTimer;
}
QOrganizerItemAbstractRequest* OrganizerRequestTimeoutTimer::request() const
{
return m_req;
}
void OrganizerRequestTimeoutTimer::internalTimeout()
{
emit timeout(this);
}
OrganizerAsynchProcess::OrganizerAsynchProcess(QOrganizerItemMaemo5Engine* engine)
: m_engine(engine)
{
QTimer::singleShot(0, this, SLOT(doStart()));
}
void OrganizerAsynchProcess::doStart()
{
start();
QObject::moveToThread(this);
}
OrganizerAsynchProcess::~OrganizerAsynchProcess()
{
quit();
wait();
}
void OrganizerAsynchProcess::requestDestroyed(QOrganizerItemAbstractRequest *req)
{
qDebug() << "requestDestroyed() run in thread " << (int) QThread::currentThreadId();
bool requestRemoved = false;
if (req->state() != QOrganizerItemAbstractRequest::ActiveState) {
qDebug() << "Request was not active";
m_mainMutex.lock();
m_requestQueue.removeOne(req);
m_mainMutex.unlock();
requestRemoved = true;
qDebug() << "Request removed";
}
if (!requestRemoved) {
qDebug() << "Have to wait for request finished";
waitForRequestFinished(req);
}
}
bool OrganizerAsynchProcess::addRequest(QOrganizerItemAbstractRequest *req)
{
qDebug() << "addRequest() run in thread " << (int) QThread::currentThreadId();
QOrganizerItemManagerEngine::updateRequestState(req, QOrganizerItemAbstractRequest::InactiveState);
m_requestQueue.enqueue(req);
return true; // TODO: Is this ok?
}
bool OrganizerAsynchProcess::cancelRequest(QOrganizerItemAbstractRequest *req)
{
qDebug() << "cancelRequest() run in thread " << (int) QThread::currentThreadId();
m_mainMutex.lock();
if (req->state() != QOrganizerItemAbstractRequest::ActiveState) {
QOrganizerItemManagerEngine::updateRequestState(req, QOrganizerItemAbstractRequest::CanceledState);
m_requestQueue.removeOne(req);
m_mainMutex.unlock();
return true;
}
else {
// cannot cancel active requests
m_mainMutex.unlock();
return false;
}
}
bool OrganizerAsynchProcess::waitForRequestFinished(QOrganizerItemAbstractRequest *req, int msecs)
{
qDebug() << "waitForRequestFinished(time) run in thread " << (int) QThread::currentThreadId();
if (req->state() == QOrganizerItemAbstractRequest::FinishedState)
return true;
else if (req->state() == QOrganizerItemAbstractRequest::CanceledState)
return false;
// Multiple timers are created to make this method thread safe.
// There's a timer for each calling thread.
OrganizerRequestTimeoutTimer* newTimer = new OrganizerRequestTimeoutTimer(req, msecs);
connect(newTimer, SIGNAL(timeout(OrganizerRequestTimeoutTimer*)), this, SLOT(timeout(OrganizerRequestTimeoutTimer*)));
m_timers << newTimer;
return waitForRequestFinished(req);
}
bool OrganizerAsynchProcess::waitForRequestFinished(QOrganizerItemAbstractRequest *req)
{
qDebug() << "waitForRequestFinished() run in thread " << (int) QThread::currentThreadId();
m_activeRequests.insert(req);
qDebug() << "waitForRequestFinished() in thread " << (int) QThread::currentThreadId() << " begin waiting";
do {
yieldCurrentThread();
QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents | QEventLoop::ExcludeSocketNotifiers);
} while(m_activeRequests.contains(req)
&& (req->state() == QOrganizerItemAbstractRequest::InactiveState
|| req->state() == QOrganizerItemAbstractRequest::ActiveState));
qDebug() << "waitForRequestFinished() in thread " << (int) QThread::currentThreadId() << " stop waiting";
m_timeoutMutex.lock();
if (!m_activeRequests.contains(req)) {
// timeout occured
qDebug() << "timeout occured";
m_timeoutMutex.unlock();
return false;
}
else {
// timeout not occured
qDebug() << "timeout not occured";
m_activeRequests.remove(req);
// cancel and remove timer
QList<OrganizerRequestTimeoutTimer *>::iterator timer;
for (timer = m_timers.begin(); timer != m_timers.end(); ++timer)
if ((*timer)->request() == req)
break;
if (timer != m_timers.end()) {
qDebug() << "timer remover";
m_timers.removeOne(*timer);
delete *timer;
}
m_timeoutMutex.unlock();
return false;
}
}
void OrganizerAsynchProcess::timeout(OrganizerRequestTimeoutTimer *timer)
{
qDebug() << "timeout() run in thread " << (int) QThread::currentThreadId();
m_timeoutMutex.lock();
if (m_activeRequests.contains(timer->request())) {
m_activeRequests.remove(timer->request());
m_timers.removeOne(timer);
delete timer;
}
m_timeoutMutex.unlock();
}
void OrganizerAsynchProcess::processRequest()
{
qDebug() << "processRequest() run in thread " << (int) QThread::currentThreadId();
m_mainMutex.lock();
if (m_requestQueue.isEmpty()) {
m_mainMutex.unlock();
return;
}
QOrganizerItemAbstractRequest *req = m_requestQueue.dequeue();
if (!req->state() == QOrganizerItemAbstractRequest::InactiveState) {
m_mainMutex.unlock();
return;
}
qDebug() << "ok";
QOrganizerItemManagerEngine::updateRequestState(req, QOrganizerItemAbstractRequest::ActiveState);
switch(req->type()) {
case QOrganizerItemAbstractRequest::ItemInstanceFetchRequest:
handleItemInstanceFetchRequest(static_cast<QOrganizerItemInstanceFetchRequest *>(req));
break;
case QOrganizerItemAbstractRequest::ItemFetchRequest:
handleItemFetchRequest(static_cast<QOrganizerItemFetchRequest *>(req));
break;
case QOrganizerItemAbstractRequest::ItemLocalIdFetchRequest:
handleLocalIdFetchRequest(static_cast<QOrganizerItemLocalIdFetchRequest *>(req));
break;
case QOrganizerItemAbstractRequest::ItemRemoveRequest:
handleItemRemoveRequest(static_cast<QOrganizerItemRemoveRequest *>(req));
break;
case QOrganizerItemAbstractRequest::ItemSaveRequest:
handleSaveRequest(static_cast<QOrganizerItemSaveRequest *>(req));
break;
case QOrganizerItemAbstractRequest::DetailDefinitionFetchRequest:
handleDefinitionFetchRequest(static_cast<QOrganizerItemDetailDefinitionFetchRequest *>(req));
break;
case QOrganizerItemAbstractRequest::DetailDefinitionRemoveRequest:
handleDefinitionRemoveRequest(static_cast<QOrganizerItemDetailDefinitionRemoveRequest *>(req));
break;
case QOrganizerItemAbstractRequest::DetailDefinitionSaveRequest:
handleDefinitionSaveRequest(static_cast<QOrganizerItemDetailDefinitionSaveRequest *>(req));
break;
default:
// invalid request
break;
}
m_mainMutex.unlock();
}
void OrganizerAsynchProcess::handleItemInstanceFetchRequest(QOrganizerItemInstanceFetchRequest *req)
{
Q_UNUSED(req);
// TODO
}
void OrganizerAsynchProcess::handleItemFetchRequest(QOrganizerItemFetchRequest *req)
{
QOrganizerItemManager::Error err = QOrganizerItemManager::NoError;
QList<QOrganizerItem> items = m_engine->items(req->filter(), req->sorting(), req->fetchHint(), &err);
QOrganizerItemManagerEngine::updateItemFetchRequest(req, items, err, QOrganizerItemAbstractRequest::FinishedState);
}
void OrganizerAsynchProcess::handleLocalIdFetchRequest(QOrganizerItemLocalIdFetchRequest *req)
{
QOrganizerItemManager::Error err = QOrganizerItemManager::NoError;
QList<QOrganizerItemLocalId> ids = m_engine->itemIds(req->filter(), req->sorting(), &err);
QOrganizerItemManagerEngine::updateItemLocalIdFetchRequest(req, ids, err, QOrganizerItemAbstractRequest::FinishedState);
}
void OrganizerAsynchProcess::handleItemRemoveRequest(QOrganizerItemRemoveRequest *req)
{
QOrganizerItemManager::Error err = QOrganizerItemManager::NoError;
QMap<int, QOrganizerItemManager::Error> errorMap;
m_engine->removeItems(req->itemIds(), &errorMap, &err);
QOrganizerItemManagerEngine::updateItemRemoveRequest(req, err, errorMap, QOrganizerItemAbstractRequest::FinishedState);
}
void OrganizerAsynchProcess::handleSaveRequest(QOrganizerItemSaveRequest *req)
{
QOrganizerItemManager::Error err = QOrganizerItemManager::NoError;
QMap<int, QOrganizerItemManager::Error> errorMap;
QList<QOrganizerItem> items = req->items();
m_engine->saveItems(&items, &errorMap, &err);
QOrganizerItemManagerEngine::updateItemSaveRequest(req, items, err, errorMap, QOrganizerItemAbstractRequest::FinishedState);
}
void OrganizerAsynchProcess::handleDefinitionFetchRequest(QOrganizerItemDetailDefinitionFetchRequest *req)
{
Q_UNUSED(req);
// TODO
}
void OrganizerAsynchProcess::handleDefinitionRemoveRequest(QOrganizerItemDetailDefinitionRemoveRequest *req)
{
Q_UNUSED(req);
// TODO
}
void OrganizerAsynchProcess::handleDefinitionSaveRequest(QOrganizerItemDetailDefinitionSaveRequest *req)
{
Q_UNUSED(req);
// TODO
}
<commit_msg>Maemo5: Added asynchronous item instance fetch request handler.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used 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. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qorganizerasynchprocess.h"
#include "qtorganizer.h"
#include "qorganizermaemo5_p.h"
#include <QtCore/qtimer.h>
#include <QtCore/qcoreapplication.h>
QTM_USE_NAMESPACE
OrganizerRequestTimeoutTimer::OrganizerRequestTimeoutTimer(QOrganizerItemAbstractRequest *req, int msecs)
: m_req(req)
{
m_timeoutTimer = new QTimer();
connect(m_timeoutTimer, SIGNAL(timeout()), this, SLOT(internalTimeout()));
m_timeoutTimer->setSingleShot(true);
m_timeoutTimer->start(msecs);
}
OrganizerRequestTimeoutTimer::~OrganizerRequestTimeoutTimer()
{
delete m_timeoutTimer;
}
QOrganizerItemAbstractRequest* OrganizerRequestTimeoutTimer::request() const
{
return m_req;
}
void OrganizerRequestTimeoutTimer::internalTimeout()
{
emit timeout(this);
}
OrganizerAsynchProcess::OrganizerAsynchProcess(QOrganizerItemMaemo5Engine* engine)
: m_engine(engine)
{
QTimer::singleShot(0, this, SLOT(doStart()));
}
void OrganizerAsynchProcess::doStart()
{
start();
QObject::moveToThread(this);
}
OrganizerAsynchProcess::~OrganizerAsynchProcess()
{
quit();
wait();
}
void OrganizerAsynchProcess::requestDestroyed(QOrganizerItemAbstractRequest *req)
{
qDebug() << "requestDestroyed() run in thread " << (int) QThread::currentThreadId();
bool requestRemoved = false;
if (req->state() != QOrganizerItemAbstractRequest::ActiveState) {
qDebug() << "Request was not active";
m_mainMutex.lock();
m_requestQueue.removeOne(req);
m_mainMutex.unlock();
requestRemoved = true;
qDebug() << "Request removed";
}
if (!requestRemoved) {
qDebug() << "Have to wait for request finished";
waitForRequestFinished(req);
}
}
bool OrganizerAsynchProcess::addRequest(QOrganizerItemAbstractRequest *req)
{
qDebug() << "addRequest() run in thread " << (int) QThread::currentThreadId();
QOrganizerItemManagerEngine::updateRequestState(req, QOrganizerItemAbstractRequest::InactiveState);
m_requestQueue.enqueue(req);
return true; // TODO: Is this ok?
}
bool OrganizerAsynchProcess::cancelRequest(QOrganizerItemAbstractRequest *req)
{
qDebug() << "cancelRequest() run in thread " << (int) QThread::currentThreadId();
m_mainMutex.lock();
if (req->state() != QOrganizerItemAbstractRequest::ActiveState) {
QOrganizerItemManagerEngine::updateRequestState(req, QOrganizerItemAbstractRequest::CanceledState);
m_requestQueue.removeOne(req);
m_mainMutex.unlock();
return true;
}
else {
// cannot cancel active requests
m_mainMutex.unlock();
return false;
}
}
bool OrganizerAsynchProcess::waitForRequestFinished(QOrganizerItemAbstractRequest *req, int msecs)
{
qDebug() << "waitForRequestFinished(time) run in thread " << (int) QThread::currentThreadId();
if (req->state() == QOrganizerItemAbstractRequest::FinishedState)
return true;
else if (req->state() == QOrganizerItemAbstractRequest::CanceledState)
return false;
// Multiple timers are created to make this method thread safe.
// There's a timer for each calling thread.
OrganizerRequestTimeoutTimer* newTimer = new OrganizerRequestTimeoutTimer(req, msecs);
connect(newTimer, SIGNAL(timeout(OrganizerRequestTimeoutTimer*)), this, SLOT(timeout(OrganizerRequestTimeoutTimer*)));
m_timers << newTimer;
return waitForRequestFinished(req);
}
bool OrganizerAsynchProcess::waitForRequestFinished(QOrganizerItemAbstractRequest *req)
{
qDebug() << "waitForRequestFinished() run in thread " << (int) QThread::currentThreadId();
m_activeRequests.insert(req);
qDebug() << "waitForRequestFinished() in thread " << (int) QThread::currentThreadId() << " begin waiting";
do {
yieldCurrentThread();
QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents | QEventLoop::ExcludeSocketNotifiers);
} while(m_activeRequests.contains(req)
&& (req->state() == QOrganizerItemAbstractRequest::InactiveState
|| req->state() == QOrganizerItemAbstractRequest::ActiveState));
qDebug() << "waitForRequestFinished() in thread " << (int) QThread::currentThreadId() << " stop waiting";
m_timeoutMutex.lock();
if (!m_activeRequests.contains(req)) {
// timeout occured
qDebug() << "timeout occured";
m_timeoutMutex.unlock();
return false;
}
else {
// timeout not occured
qDebug() << "timeout not occured";
m_activeRequests.remove(req);
// cancel and remove timer
QList<OrganizerRequestTimeoutTimer *>::iterator timer;
for (timer = m_timers.begin(); timer != m_timers.end(); ++timer)
if ((*timer)->request() == req)
break;
if (timer != m_timers.end()) {
qDebug() << "timer remover";
m_timers.removeOne(*timer);
delete *timer;
}
m_timeoutMutex.unlock();
return false;
}
}
void OrganizerAsynchProcess::timeout(OrganizerRequestTimeoutTimer *timer)
{
qDebug() << "timeout() run in thread " << (int) QThread::currentThreadId();
m_timeoutMutex.lock();
if (m_activeRequests.contains(timer->request())) {
m_activeRequests.remove(timer->request());
m_timers.removeOne(timer);
delete timer;
}
m_timeoutMutex.unlock();
}
void OrganizerAsynchProcess::processRequest()
{
qDebug() << "processRequest() run in thread " << (int) QThread::currentThreadId();
m_mainMutex.lock();
if (m_requestQueue.isEmpty()) {
m_mainMutex.unlock();
return;
}
QOrganizerItemAbstractRequest *req = m_requestQueue.dequeue();
if (!req->state() == QOrganizerItemAbstractRequest::InactiveState) {
m_mainMutex.unlock();
return;
}
qDebug() << "ok";
QOrganizerItemManagerEngine::updateRequestState(req, QOrganizerItemAbstractRequest::ActiveState);
switch(req->type()) {
case QOrganizerItemAbstractRequest::ItemInstanceFetchRequest:
handleItemInstanceFetchRequest(static_cast<QOrganizerItemInstanceFetchRequest *>(req));
break;
case QOrganizerItemAbstractRequest::ItemFetchRequest:
handleItemFetchRequest(static_cast<QOrganizerItemFetchRequest *>(req));
break;
case QOrganizerItemAbstractRequest::ItemLocalIdFetchRequest:
handleLocalIdFetchRequest(static_cast<QOrganizerItemLocalIdFetchRequest *>(req));
break;
case QOrganizerItemAbstractRequest::ItemRemoveRequest:
handleItemRemoveRequest(static_cast<QOrganizerItemRemoveRequest *>(req));
break;
case QOrganizerItemAbstractRequest::ItemSaveRequest:
handleSaveRequest(static_cast<QOrganizerItemSaveRequest *>(req));
break;
case QOrganizerItemAbstractRequest::DetailDefinitionFetchRequest:
handleDefinitionFetchRequest(static_cast<QOrganizerItemDetailDefinitionFetchRequest *>(req));
break;
case QOrganizerItemAbstractRequest::DetailDefinitionRemoveRequest:
handleDefinitionRemoveRequest(static_cast<QOrganizerItemDetailDefinitionRemoveRequest *>(req));
break;
case QOrganizerItemAbstractRequest::DetailDefinitionSaveRequest:
handleDefinitionSaveRequest(static_cast<QOrganizerItemDetailDefinitionSaveRequest *>(req));
break;
default:
// invalid request
break;
}
m_mainMutex.unlock();
}
void OrganizerAsynchProcess::handleItemInstanceFetchRequest(QOrganizerItemInstanceFetchRequest *req)
{
QOrganizerItemManager::Error err = QOrganizerItemManager::NoError;
QList<QOrganizerItem> items = m_engine->itemInstances(req->filter(), req->sorting(), req->fetchHint(), &err);
QOrganizerItemManagerEngine::updateItemInstanceFetchRequest(req, items, err, QOrganizerItemAbstractRequest::FinishedState);
}
void OrganizerAsynchProcess::handleItemFetchRequest(QOrganizerItemFetchRequest *req)
{
QOrganizerItemManager::Error err = QOrganizerItemManager::NoError;
QList<QOrganizerItem> items = m_engine->items(req->filter(), req->sorting(), req->fetchHint(), &err);
QOrganizerItemManagerEngine::updateItemFetchRequest(req, items, err, QOrganizerItemAbstractRequest::FinishedState);
}
void OrganizerAsynchProcess::handleLocalIdFetchRequest(QOrganizerItemLocalIdFetchRequest *req)
{
QOrganizerItemManager::Error err = QOrganizerItemManager::NoError;
QList<QOrganizerItemLocalId> ids = m_engine->itemIds(req->filter(), req->sorting(), &err);
QOrganizerItemManagerEngine::updateItemLocalIdFetchRequest(req, ids, err, QOrganizerItemAbstractRequest::FinishedState);
}
void OrganizerAsynchProcess::handleItemRemoveRequest(QOrganizerItemRemoveRequest *req)
{
QOrganizerItemManager::Error err = QOrganizerItemManager::NoError;
QMap<int, QOrganizerItemManager::Error> errorMap;
m_engine->removeItems(req->itemIds(), &errorMap, &err);
QOrganizerItemManagerEngine::updateItemRemoveRequest(req, err, errorMap, QOrganizerItemAbstractRequest::FinishedState);
}
void OrganizerAsynchProcess::handleSaveRequest(QOrganizerItemSaveRequest *req)
{
QOrganizerItemManager::Error err = QOrganizerItemManager::NoError;
QMap<int, QOrganizerItemManager::Error> errorMap;
QList<QOrganizerItem> items = req->items();
m_engine->saveItems(&items, &errorMap, &err);
QOrganizerItemManagerEngine::updateItemSaveRequest(req, items, err, errorMap, QOrganizerItemAbstractRequest::FinishedState);
}
void OrganizerAsynchProcess::handleDefinitionFetchRequest(QOrganizerItemDetailDefinitionFetchRequest *req)
{
Q_UNUSED(req);
// TODO
}
void OrganizerAsynchProcess::handleDefinitionRemoveRequest(QOrganizerItemDetailDefinitionRemoveRequest *req)
{
Q_UNUSED(req);
// TODO
}
void OrganizerAsynchProcess::handleDefinitionSaveRequest(QOrganizerItemDetailDefinitionSaveRequest *req)
{
Q_UNUSED(req);
// TODO
}
<|endoftext|>
|
<commit_before>#define FASTLED_INTERNAL
#include "FastLED.h"
#if defined(__SAM3X8E__)
volatile uint32_t fuckit;
#endif
#if defined(ARDUINO) || defined(SPARK)
extern uint32_t millis();
#endif
FASTLED_NAMESPACE_BEGIN
void *pSmartMatrix = NULL;
CFastLED FastLED;
CLEDController *CLEDController::m_pHead = NULL;
CLEDController *CLEDController::m_pTail = NULL;
static uint32_t lastshow = 0;
// uint32_t CRGB::Squant = ((uint32_t)((__TIME__[4]-'0') * 28))<<16 | ((__TIME__[6]-'0')*50)<<8 | ((__TIME__[7]-'0')*28);
CFastLED::CFastLED() {
// clear out the array of led controllers
// m_nControllers = 0;
m_Scale = 255;
m_nFPS = 0;
setMaxRefreshRate(400);
}
CLEDController &CFastLED::addLeds(CLEDController *pLed,
struct CRGB *data,
int nLedsOrOffset, int nLedsIfOffset) {
int nOffset = (nLedsIfOffset > 0) ? nLedsOrOffset : 0;
int nLeds = (nLedsIfOffset > 0) ? nLedsIfOffset : nLedsOrOffset;
pLed->init();
pLed->setLeds(data + nOffset, nLeds);
return *pLed;
}
void CFastLED::show(uint8_t scale) {
// guard against showing too rapidly
while(m_nMinMicros && ((micros()-lastshow) < m_nMinMicros));
lastshow = micros();
CLEDController *pCur = CLEDController::head();
while(pCur) {
uint8_t d = pCur->getDither();
if(m_nFPS < 100) { pCur->setDither(0); }
pCur->showLeds(scale);
pCur->setDither(d);
pCur = pCur->next();
}
countFPS();
}
int CFastLED::count() {
int x = 0;
CLEDController *pCur = CLEDController::head();
while( pCur) {
x++;
pCur = pCur->next();
}
return x;
}
CLEDController & CFastLED::operator[](int x) {
CLEDController *pCur = CLEDController::head();
while(x-- && pCur) {
pCur = pCur->next();
}
if(pCur == NULL) {
return *(CLEDController::head());
} else {
return *pCur;
}
}
void CFastLED::showColor(const struct CRGB & color, uint8_t scale) {
while(m_nMinMicros && ((micros()-lastshow) < m_nMinMicros));
lastshow = micros();
CLEDController *pCur = CLEDController::head();
while(pCur) {
uint8_t d = pCur->getDither();
if(m_nFPS < 100) { pCur->setDither(0); }
pCur->showColor(color, scale);
pCur->setDither(d);
pCur = pCur->next();
}
countFPS();
}
void CFastLED::clear(boolean writeData) {
if(writeData) {
showColor(CRGB(0,0,0), 0);
}
clearData();
}
void CFastLED::clearData() {
CLEDController *pCur = CLEDController::head();
while(pCur) {
pCur->clearLedData();
pCur = pCur->next();
}
}
void CFastLED::delay(unsigned long ms) {
unsigned long start = millis();
while((millis()-start) < ms) {
#ifndef FASTLED_ACCURATE_CLOCK
// make sure to allow at least one ms to pass to ensure the clock moves
// forward
::delay(1);
#endif
show();
}
}
void CFastLED::setTemperature(const struct CRGB & temp) {
CLEDController *pCur = CLEDController::head();
while(pCur) {
pCur->setTemperature(temp);
pCur = pCur->next();
}
}
void CFastLED::setCorrection(const struct CRGB & correction) {
CLEDController *pCur = CLEDController::head();
while(pCur) {
pCur->setCorrection(correction);
pCur = pCur->next();
}
}
void CFastLED::setDither(uint8_t ditherMode) {
CLEDController *pCur = CLEDController::head();
while(pCur) {
pCur->setDither(ditherMode);
pCur = pCur->next();
}
}
//
// template<int m, int n> void transpose8(unsigned char A[8], unsigned char B[8]) {
// uint32_t x, y, t;
//
// // Load the array and pack it into x and y.
// y = *(unsigned int*)(A);
// x = *(unsigned int*)(A+4);
//
// // x = (A[0]<<24) | (A[m]<<16) | (A[2*m]<<8) | A[3*m];
// // y = (A[4*m]<<24) | (A[5*m]<<16) | (A[6*m]<<8) | A[7*m];
//
// // pre-transform x
// t = (x ^ (x >> 7)) & 0x00AA00AA; x = x ^ t ^ (t << 7);
// t = (x ^ (x >>14)) & 0x0000CCCC; x = x ^ t ^ (t <<14);
//
// // pre-transform y
// t = (y ^ (y >> 7)) & 0x00AA00AA; y = y ^ t ^ (t << 7);
// t = (y ^ (y >>14)) & 0x0000CCCC; y = y ^ t ^ (t <<14);
//
// // final transform
// t = (x & 0xF0F0F0F0) | ((y >> 4) & 0x0F0F0F0F);
// y = ((x << 4) & 0xF0F0F0F0) | (y & 0x0F0F0F0F);
// x = t;
//
// B[7*n] = y; y >>= 8;
// B[6*n] = y; y >>= 8;
// B[5*n] = y; y >>= 8;
// B[4*n] = y;
//
// B[3*n] = x; x >>= 8;
// B[2*n] = x; x >>= 8;
// B[n] = x; x >>= 8;
// B[0] = x;
// // B[0]=x>>24; B[n]=x>>16; B[2*n]=x>>8; B[3*n]=x>>0;
// // B[4*n]=y>>24; B[5*n]=y>>16; B[6*n]=y>>8; B[7*n]=y>>0;
// }
//
// void transposeLines(Lines & out, Lines & in) {
// transpose8<1,2>(in.bytes, out.bytes);
// transpose8<1,2>(in.bytes + 8, out.bytes + 1);
// }
extern int noise_min;
extern int noise_max;
void CFastLED::countFPS(int nFrames) {
static int br = 0;
static uint32_t lastframe = 0; // millis();
if(br++ >= nFrames) {
uint32_t now = millis();
now -= lastframe;
m_nFPS = (br * 1000) / now;
br = 0;
lastframe = millis();
}
}
void CFastLED::setMaxRefreshRate(uint16_t refresh) {
if(refresh > 0) {
m_nMinMicros = 1000000 / refresh;
} else {
m_nMinMicros = 0;
}
}
#ifdef NEED_CXX_BITS
namespace __cxxabiv1
{
extern "C" void __cxa_pure_virtual (void) {}
/* guard variables */
/* The ABI requires a 64-bit type. */
__extension__ typedef int __guard __attribute__((mode(__DI__)));
extern "C" int __cxa_guard_acquire (__guard *);
extern "C" void __cxa_guard_release (__guard *);
extern "C" void __cxa_guard_abort (__guard *);
extern "C" int __cxa_guard_acquire (__guard *g)
{
return !*(char *)(g);
}
extern "C" void __cxa_guard_release (__guard *g)
{
*(char *)g = 1;
}
extern "C" void __cxa_guard_abort (__guard *)
{
}
}
#endif
FASTLED_NAMESPACE_END
<commit_msg>Make sure we're getting decently scoped for millis.<commit_after>#define FASTLED_INTERNAL
#include "FastLED.h"
#if defined(__SAM3X8E__)
volatile uint32_t fuckit;
#endif
#if defined(ARDUINO) || defined(SPARK)
extern uint32_t millis();
#endif
FASTLED_NAMESPACE_BEGIN
void *pSmartMatrix = NULL;
CFastLED FastLED;
CLEDController *CLEDController::m_pHead = NULL;
CLEDController *CLEDController::m_pTail = NULL;
static uint32_t lastshow = 0;
// uint32_t CRGB::Squant = ((uint32_t)((__TIME__[4]-'0') * 28))<<16 | ((__TIME__[6]-'0')*50)<<8 | ((__TIME__[7]-'0')*28);
CFastLED::CFastLED() {
// clear out the array of led controllers
// m_nControllers = 0;
m_Scale = 255;
m_nFPS = 0;
setMaxRefreshRate(400);
}
CLEDController &CFastLED::addLeds(CLEDController *pLed,
struct CRGB *data,
int nLedsOrOffset, int nLedsIfOffset) {
int nOffset = (nLedsIfOffset > 0) ? nLedsOrOffset : 0;
int nLeds = (nLedsIfOffset > 0) ? nLedsIfOffset : nLedsOrOffset;
pLed->init();
pLed->setLeds(data + nOffset, nLeds);
return *pLed;
}
void CFastLED::show(uint8_t scale) {
// guard against showing too rapidly
while(m_nMinMicros && ((micros()-lastshow) < m_nMinMicros));
lastshow = micros();
CLEDController *pCur = CLEDController::head();
while(pCur) {
uint8_t d = pCur->getDither();
if(m_nFPS < 100) { pCur->setDither(0); }
pCur->showLeds(scale);
pCur->setDither(d);
pCur = pCur->next();
}
countFPS();
}
int CFastLED::count() {
int x = 0;
CLEDController *pCur = CLEDController::head();
while( pCur) {
x++;
pCur = pCur->next();
}
return x;
}
CLEDController & CFastLED::operator[](int x) {
CLEDController *pCur = CLEDController::head();
while(x-- && pCur) {
pCur = pCur->next();
}
if(pCur == NULL) {
return *(CLEDController::head());
} else {
return *pCur;
}
}
void CFastLED::showColor(const struct CRGB & color, uint8_t scale) {
while(m_nMinMicros && ((micros()-lastshow) < m_nMinMicros));
lastshow = micros();
CLEDController *pCur = CLEDController::head();
while(pCur) {
uint8_t d = pCur->getDither();
if(m_nFPS < 100) { pCur->setDither(0); }
pCur->showColor(color, scale);
pCur->setDither(d);
pCur = pCur->next();
}
countFPS();
}
void CFastLED::clear(boolean writeData) {
if(writeData) {
showColor(CRGB(0,0,0), 0);
}
clearData();
}
void CFastLED::clearData() {
CLEDController *pCur = CLEDController::head();
while(pCur) {
pCur->clearLedData();
pCur = pCur->next();
}
}
void CFastLED::delay(unsigned long ms) {
unsigned long start = ::millis();
while((::millis()-start) < ms) {
#ifndef FASTLED_ACCURATE_CLOCK
// make sure to allow at least one ms to pass to ensure the clock moves
// forward
::delay(1);
#endif
show();
}
}
void CFastLED::setTemperature(const struct CRGB & temp) {
CLEDController *pCur = CLEDController::head();
while(pCur) {
pCur->setTemperature(temp);
pCur = pCur->next();
}
}
void CFastLED::setCorrection(const struct CRGB & correction) {
CLEDController *pCur = CLEDController::head();
while(pCur) {
pCur->setCorrection(correction);
pCur = pCur->next();
}
}
void CFastLED::setDither(uint8_t ditherMode) {
CLEDController *pCur = CLEDController::head();
while(pCur) {
pCur->setDither(ditherMode);
pCur = pCur->next();
}
}
//
// template<int m, int n> void transpose8(unsigned char A[8], unsigned char B[8]) {
// uint32_t x, y, t;
//
// // Load the array and pack it into x and y.
// y = *(unsigned int*)(A);
// x = *(unsigned int*)(A+4);
//
// // x = (A[0]<<24) | (A[m]<<16) | (A[2*m]<<8) | A[3*m];
// // y = (A[4*m]<<24) | (A[5*m]<<16) | (A[6*m]<<8) | A[7*m];
//
// // pre-transform x
// t = (x ^ (x >> 7)) & 0x00AA00AA; x = x ^ t ^ (t << 7);
// t = (x ^ (x >>14)) & 0x0000CCCC; x = x ^ t ^ (t <<14);
//
// // pre-transform y
// t = (y ^ (y >> 7)) & 0x00AA00AA; y = y ^ t ^ (t << 7);
// t = (y ^ (y >>14)) & 0x0000CCCC; y = y ^ t ^ (t <<14);
//
// // final transform
// t = (x & 0xF0F0F0F0) | ((y >> 4) & 0x0F0F0F0F);
// y = ((x << 4) & 0xF0F0F0F0) | (y & 0x0F0F0F0F);
// x = t;
//
// B[7*n] = y; y >>= 8;
// B[6*n] = y; y >>= 8;
// B[5*n] = y; y >>= 8;
// B[4*n] = y;
//
// B[3*n] = x; x >>= 8;
// B[2*n] = x; x >>= 8;
// B[n] = x; x >>= 8;
// B[0] = x;
// // B[0]=x>>24; B[n]=x>>16; B[2*n]=x>>8; B[3*n]=x>>0;
// // B[4*n]=y>>24; B[5*n]=y>>16; B[6*n]=y>>8; B[7*n]=y>>0;
// }
//
// void transposeLines(Lines & out, Lines & in) {
// transpose8<1,2>(in.bytes, out.bytes);
// transpose8<1,2>(in.bytes + 8, out.bytes + 1);
// }
extern int noise_min;
extern int noise_max;
void CFastLED::countFPS(int nFrames) {
static int br = 0;
static uint32_t lastframe = 0; // ::millis();
if(br++ >= nFrames) {
uint32_t now = ::millis();
now -= lastframe;
m_nFPS = (br * 1000) / now;
br = 0;
lastframe = ::millis();
}
}
void CFastLED::setMaxRefreshRate(uint16_t refresh) {
if(refresh > 0) {
m_nMinMicros = 1000000 / refresh;
} else {
m_nMinMicros = 0;
}
}
#ifdef NEED_CXX_BITS
namespace __cxxabiv1
{
extern "C" void __cxa_pure_virtual (void) {}
/* guard variables */
/* The ABI requires a 64-bit type. */
__extension__ typedef int __guard __attribute__((mode(__DI__)));
extern "C" int __cxa_guard_acquire (__guard *);
extern "C" void __cxa_guard_release (__guard *);
extern "C" void __cxa_guard_abort (__guard *);
extern "C" int __cxa_guard_acquire (__guard *g)
{
return !*(char *)(g);
}
extern "C" void __cxa_guard_release (__guard *g)
{
*(char *)g = 1;
}
extern "C" void __cxa_guard_abort (__guard *)
{
}
}
#endif
FASTLED_NAMESPACE_END
<|endoftext|>
|
<commit_before>#ifndef PHYSICSCONTACTLISTENER_H
#define PHYSICSCONTACTLISTENER_H
#include <functional>
#include <Box2D/Box2D.h>
#include <UtH/Engine/GameObject.hpp>
namespace uth
{
class PhysicsContactListener : public b2ContactListener
{
public:
void BeginContact(b2Contact* contact);
void EndContact(b2Contact* contact);
void PreSolve(b2Contact* contact, const b2Manifold* oldManifold);
void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse);
std::function<void(b2Contact* contact, GameObject* a, GameObject* b)> onBeginContact = nullptr;
std::function<void(b2Contact* contact, const b2Manifold* oldManifold, GameObject* a, GameObject* b)> onPreSolve = nullptr;
std::function<void(b2Contact* contact, const b2ContactImpulse* impulse, GameObject* a, GameObject* b)> onPostSolve = nullptr;
std::function<void(b2Contact* contact, GameObject* a, GameObject* b)> onEndContact = nullptr;
};
}
#endif<commit_msg>Made PhysicsContactListener header a bit more clear<commit_after>#ifndef PHYSICSCONTACTLISTENER_H
#define PHYSICSCONTACTLISTENER_H
#include <functional>
#include <Box2D/Box2D.h>
#include <UtH/Engine/GameObject.hpp>
namespace uth
{
class PhysicsContactListener : public b2ContactListener
{
public:
void BeginContact(b2Contact* contact) override;
void EndContact(b2Contact* contact) override;
void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) override;
void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) override;
std::function<void(b2Contact* contact, GameObject* a, GameObject* b)> onBeginContact = nullptr;
std::function<void(b2Contact* contact, const b2Manifold* oldManifold, GameObject* a, GameObject* b)> onPreSolve = nullptr;
std::function<void(b2Contact* contact, const b2ContactImpulse* impulse, GameObject* a, GameObject* b)> onPostSolve = nullptr;
std::function<void(b2Contact* contact, GameObject* a, GameObject* b)> onEndContact = nullptr;
};
}
#endif<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include <cmath>
#include <iostream>
#include <limits>
#include <memory>
#include <vector>
#include <ros/ros.h>
#include "gnss/parser.h"
#include "proto/gnss_raw_observation.pb.h"
#include "rtcm/rtcm_decode.h"
namespace apollo {
namespace drivers {
namespace gnss {
// Anonymous namespace that contains helper constants and functions.
namespace {
template <typename T>
constexpr bool is_zero(T value) {
return value == static_cast<T>(0);
}
} // namespace
class Rtcm3Parser : public Parser {
public:
Rtcm3Parser(bool is_base_satation);
virtual MessageType get_message(MessagePtr &message_ptr);
private:
void set_observation_time();
bool set_station_position();
void fill_keppler_orbit(eph_t &eph,
apollo::drivers::gnss::KepplerOrbit &keppler_orbit);
void fill_glonass_orbit(geph_t &eph,
apollo::drivers::gnss::GlonassOrbit &keppler_orbit);
bool process_observation();
bool process_ephemerides();
bool process_station_parameters();
bool _init_flag;
std::vector<uint8_t> _buffer;
rtcm_t _rtcm;
bool _is_base_station = false;
apollo::drivers::gnss::GnssEphemeris _ephemeris;
apollo::drivers::gnss::EpochObservation _observation;
// std::map<int, adu::common::Point3D> _station_location;
};
Parser *Parser::create_rtcm_v3(bool is_base_station) {
return new Rtcm3Parser(is_base_station);
}
Rtcm3Parser::Rtcm3Parser(bool is_base_station) {
if (1 != init_rtcm(&_rtcm)) {
_init_flag = true;
} else {
_init_flag = false;
}
_ephemeris.Clear();
_observation.Clear();
_is_base_station = is_base_station;
}
bool Rtcm3Parser::set_station_position() {
#if 0
auto iter = _station_location.find(_rtcm.staid);
if (iter == _station_location.end()) {
ROS_WARN("Station %d has no location info.", _rtcm.staid);
return false;
}
_observation.set_position_x(iter->second.x());
_observation.set_position_y(iter->second.y());
_observation.set_position_z(iter->second.z());
#endif
return true;
}
void Rtcm3Parser::fill_keppler_orbit(
eph_t &eph, apollo::drivers::gnss::KepplerOrbit &keppler_orbit) {
keppler_orbit.set_week_num(eph.week);
keppler_orbit.set_af0(eph.f0);
keppler_orbit.set_af1(eph.f1);
keppler_orbit.set_af2(eph.f2);
keppler_orbit.set_iode(eph.iode);
keppler_orbit.set_deltan(eph.deln);
keppler_orbit.set_m0(eph.M0);
keppler_orbit.set_e(eph.e);
keppler_orbit.set_roota(std::sqrt(eph.A));
keppler_orbit.set_toe(eph.toes);
keppler_orbit.set_toc(eph.tocs);
keppler_orbit.set_cic(eph.cic);
keppler_orbit.set_crc(eph.crc);
keppler_orbit.set_cis(eph.cis);
keppler_orbit.set_crs(eph.crs);
keppler_orbit.set_cuc(eph.cuc);
keppler_orbit.set_cus(eph.cus);
keppler_orbit.set_omega0(eph.OMG0);
keppler_orbit.set_omega(eph.omg);
keppler_orbit.set_i0(eph.i0);
keppler_orbit.set_omegadot(eph.OMGd);
keppler_orbit.set_idot(eph.idot);
// keppler_orbit.set_codesonL2channel(eph.);
keppler_orbit.set_l2pdataflag(eph.flag);
keppler_orbit.set_accuracy(eph.sva);
keppler_orbit.set_health(eph.svh);
keppler_orbit.set_tgd(eph.tgd[0]);
keppler_orbit.set_iodc(eph.iodc);
int prn = 0;
satsys(eph.sat, &prn);
keppler_orbit.set_sat_prn(prn);
ROS_INFO_STREAM("Keppler orbit debuginfo:\r\n"
<< keppler_orbit.DebugString());
}
void Rtcm3Parser::fill_glonass_orbit(
geph_t &eph, apollo::drivers::gnss::GlonassOrbit &orbit) {
orbit.set_position_x(eph.pos[0]);
orbit.set_position_y(eph.pos[1]);
orbit.set_position_z(eph.pos[2]);
orbit.set_velocity_x(eph.vel[0]);
orbit.set_velocity_y(eph.vel[1]);
orbit.set_velocity_z(eph.vel[2]);
orbit.set_accelerate_x(eph.acc[0]);
orbit.set_accelerate_y(eph.acc[1]);
orbit.set_accelerate_z(eph.acc[2]);
orbit.set_health(eph.svh);
orbit.set_clock_offset(-eph.taun);
orbit.set_clock_drift(eph.gamn);
orbit.set_infor_age(eph.age);
orbit.set_frequency_no(eph.frq);
// orbit.set_toe(eph.toe.time + eph.toe.sec);
// orbit.set_tk(eph.tof.time + eph.tof.sec);
int week = 0;
double second = 0.0;
second = time2gpst(eph.toe, &week);
orbit.set_week_num(week);
orbit.set_week_second_s(second);
orbit.set_toe(second);
second = time2gpst(eph.tof, &week);
orbit.set_tk(second);
orbit.set_gnss_time_type(apollo::drivers::gnss::GnssTimeType::GPS_TIME);
int prn = 0;
satsys(eph.sat, &prn);
orbit.set_slot_prn(prn);
}
void Rtcm3Parser::set_observation_time() {
int week = 0;
double second = 0.0;
second = time2gpst(_rtcm.time, &week);
_observation.set_gnss_time_type(apollo::drivers::gnss::GPS_TIME);
_observation.set_gnss_week(week);
_observation.set_gnss_second_s(second);
}
Parser::MessageType Rtcm3Parser::get_message(MessagePtr &message_ptr) {
if (_data == nullptr) {
return MessageType::NONE;
}
int status = 0;
while (_data < _data_end) {
status = input_rtcm3(&_rtcm, *_data++); // parse data use rtklib
switch (status) {
case 1: // observation data
if (process_observation()) {
message_ptr = &_observation;
return MessageType::OBSERVATION;
}
break;
case 2: // ephemeris
if (process_ephemerides()) {
message_ptr = &_ephemeris;
return MessageType::EPHEMERIDES;
}
break;
case 5:
process_station_parameters();
break;
case 10: // ssr messages
default:
break;
}
}
return MessageType::NONE;
}
bool Rtcm3Parser::process_observation() {
ROS_INFO("======Observation message.");
ROS_INFO("Message type %d.", _rtcm.message_type);
ROS_INFO_STREAM("Is base station: " << _is_base_station);
ROS_INFO("Observation number %d.", _rtcm.obs.n);
ROS_INFO("Station Id %d.", _rtcm.staid);
ROS_INFO("time %ld.", _rtcm.time.time);
ROS_INFO("sec %f.", _rtcm.time.sec);
if (_rtcm.obs.n == 0) {
ROS_WARN("Obs is zero.");
}
_observation.Clear();
set_station_position();
if (!_is_base_station) {
_observation.set_receiver_id(0);
} else {
_observation.set_receiver_id(_rtcm.staid + 0x80000000);
}
// set time
set_observation_time();
// set satellite obs
_observation.set_sat_obs_num(_rtcm.obs.n);
_observation.set_health_flag(_rtcm.stah);
for (int i = 0; i < _rtcm.obs.n; ++i) {
int prn = 0;
int sys = 0;
sys = satsys(_rtcm.obs.data[i].sat, &prn);
ROS_INFO("sat %d, receiver %d.", _rtcm.obs.data[i].sat,
_rtcm.obs.data[i].rcv);
ROS_INFO("sys %d, prn %d.", sys, prn);
apollo::drivers::gnss::GnssType gnss_type;
// transform sys to local sys type
if (!gnss_sys_type(sys, gnss_type)) {
return false;
}
auto sat_obs = _observation.add_sat_obs(); // create obj
sat_obs->set_sat_prn(prn);
sat_obs->set_sat_sys(gnss_type);
int j = 0;
for (j = 0; j < NFREQ + NEXOBS; ++j) {
if (is_zero(_rtcm.obs.data[i].L[j])) {
break;
}
apollo::drivers::gnss::GnssBandID baud_id;
if (!gnss_baud_id(gnss_type, j, baud_id)) {
break;
}
double freq = 0;
gnss_frequence(baud_id, freq);
auto band_obs = sat_obs->add_band_obs();
if (_rtcm.obs.data[i].code[i] == CODE_L1C) {
band_obs->set_pseudo_type(
apollo::drivers::gnss::PseudoType::CORSE_CODE);
} else if (_rtcm.obs.data[i].code[i] == CODE_L1P) {
band_obs->set_pseudo_type(
apollo::drivers::gnss::PseudoType::PRECISION_CODE);
} else {
ROS_INFO("Message type %d.", _rtcm.message_type);
ROS_INFO("Code %d, in seq %d, gnss type %d.", _rtcm.obs.data[i].code[i],
j, static_cast<int>(gnss_type));
}
band_obs->set_band_id(baud_id);
band_obs->set_frequency_value(freq);
band_obs->set_pseudo_range(_rtcm.obs.data[i].P[j]);
band_obs->set_carrier_phase(_rtcm.obs.data[i].L[j]);
band_obs->set_loss_lock_index(_rtcm.obs.data[i].SNR[j]);
band_obs->set_doppler(_rtcm.obs.data[i].D[j]);
band_obs->set_snr(_rtcm.obs.data[i].SNR[j]);
}
ROS_INFO("Baud obs num %d.", j);
sat_obs->set_band_obs_num(j);
}
ROS_INFO_STREAM("Obeservation debuginfo:\r\n" << _observation.DebugString());
return true;
}
bool Rtcm3Parser::process_ephemerides() {
apollo::drivers::gnss::GnssType gnss_type;
ROS_INFO("======Ephemeris Message.");
ROS_INFO("Message type %d.", _rtcm.message_type);
ROS_INFO_STREAM("Is base station: " << _is_base_station);
if (!gnss_sys(_rtcm.message_type, gnss_type)) {
ROS_INFO("Failed get gnss type from message type %d.", _rtcm.message_type);
return false;
;
}
apollo::drivers::gnss::GnssTimeType time_type;
gnss_time_type(gnss_type, time_type);
ROS_INFO("Gnss sys %d ephemeris info.", static_cast<int>(gnss_type));
_ephemeris.Clear();
_ephemeris.set_gnss_type(gnss_type);
if (gnss_type == apollo::drivers::gnss::GnssType::GLO_SYS) {
auto obit = _ephemeris.mutable_glonass_orbit();
obit->set_gnss_type(gnss_type);
obit->set_gnss_time_type(time_type);
fill_glonass_orbit(_rtcm.nav.geph[_rtcm.ephsat - 1], *obit);
} else {
auto obit = _ephemeris.mutable_keppler_orbit();
obit->set_gnss_type(gnss_type);
obit->set_gnss_time_type(time_type);
fill_keppler_orbit(_rtcm.nav.eph[_rtcm.ephsat - 1], *obit);
}
ROS_INFO_STREAM("Ephemeris debuginfo:\r\n" << _ephemeris.DebugString());
return true;
}
bool Rtcm3Parser::process_station_parameters() {
// station pose/ant parameters, set pose.
ROS_INFO("======Station parameters message.");
ROS_INFO("Message type %d.", _rtcm.message_type);
ROS_INFO_STREAM("Is base station: " << _is_base_station);
ROS_INFO("Station receiver number %s.", _rtcm.sta.recsno);
ROS_INFO("Station pose (%f, %f, %f).", _rtcm.sta.pos[0], _rtcm.sta.pos[1],
_rtcm.sta.pos[2]);
#if 0
// update station location
auto iter = _station_location.find(_rtcm.staid);
if (iter == _station_location.end()) {
adu::common::Point3D point;
ROS_INFO("Add pose for station id: %d.", _rtcm.staid);
point.set_x(_rtcm.sta.pos[0]);
point.set_y(_rtcm.sta.pos[1]);
point.set_z(_rtcm.sta.pos[2]);
_station_location.insert(std::make_pair(_rtcm.staid, point));
} else {
iter->second.set_x(_rtcm.sta.pos[0]);
iter->second.set_y(_rtcm.sta.pos[1]);
iter->second.set_z(_rtcm.sta.pos[2]);
}
#endif
return true;
}
} // namespace gnss
} // namespace drivers
} // namespace apollo
<commit_msg>drivers: gnss rtcm parser add base station localization.<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include <cmath>
#include <iostream>
#include <limits>
#include <memory>
#include <vector>
#include <ros/ros.h>
#include "gnss/parser.h"
#include "proto/gnss_raw_observation.pb.h"
#include "rtcm/rtcm_decode.h"
namespace apollo {
namespace drivers {
namespace gnss {
// Anonymous namespace that contains helper constants and functions.
namespace {
template <typename T>
constexpr bool is_zero(T value) {
return value == static_cast<T>(0);
}
} // namespace
class Rtcm3Parser : public Parser {
public:
Rtcm3Parser(bool is_base_satation);
virtual MessageType get_message(MessagePtr &message_ptr);
private:
void set_observation_time();
bool set_station_position();
void fill_keppler_orbit(eph_t &eph,
apollo::drivers::gnss::KepplerOrbit &keppler_orbit);
void fill_glonass_orbit(geph_t &eph,
apollo::drivers::gnss::GlonassOrbit &keppler_orbit);
bool process_observation();
bool process_ephemerides();
bool process_station_parameters();
bool _init_flag;
std::vector<uint8_t> _buffer;
rtcm_t _rtcm;
bool _is_base_station = false;
apollo::drivers::gnss::GnssEphemeris _ephemeris;
apollo::drivers::gnss::EpochObservation _observation;
struct Point3D {
double x;
double y;
double z;
};
std::map<int, Point3D> _station_location;
};
Parser *Parser::create_rtcm_v3(bool is_base_station) {
return new Rtcm3Parser(is_base_station);
}
Rtcm3Parser::Rtcm3Parser(bool is_base_station) {
if (1 != init_rtcm(&_rtcm)) {
_init_flag = true;
} else {
_init_flag = false;
}
_ephemeris.Clear();
_observation.Clear();
_is_base_station = is_base_station;
}
bool Rtcm3Parser::set_station_position() {
auto iter = _station_location.find(_rtcm.staid);
if (iter == _station_location.end()) {
ROS_WARN("Station %d has no location info.", _rtcm.staid);
return false;
}
_observation.set_position_x(iter->second.x);
_observation.set_position_y(iter->second.y);
_observation.set_position_z(iter->second.z);
return true;
}
void Rtcm3Parser::fill_keppler_orbit(
eph_t &eph, apollo::drivers::gnss::KepplerOrbit &keppler_orbit) {
keppler_orbit.set_week_num(eph.week);
keppler_orbit.set_af0(eph.f0);
keppler_orbit.set_af1(eph.f1);
keppler_orbit.set_af2(eph.f2);
keppler_orbit.set_iode(eph.iode);
keppler_orbit.set_deltan(eph.deln);
keppler_orbit.set_m0(eph.M0);
keppler_orbit.set_e(eph.e);
keppler_orbit.set_roota(std::sqrt(eph.A));
keppler_orbit.set_toe(eph.toes);
keppler_orbit.set_toc(eph.tocs);
keppler_orbit.set_cic(eph.cic);
keppler_orbit.set_crc(eph.crc);
keppler_orbit.set_cis(eph.cis);
keppler_orbit.set_crs(eph.crs);
keppler_orbit.set_cuc(eph.cuc);
keppler_orbit.set_cus(eph.cus);
keppler_orbit.set_omega0(eph.OMG0);
keppler_orbit.set_omega(eph.omg);
keppler_orbit.set_i0(eph.i0);
keppler_orbit.set_omegadot(eph.OMGd);
keppler_orbit.set_idot(eph.idot);
// keppler_orbit.set_codesonL2channel(eph.);
keppler_orbit.set_l2pdataflag(eph.flag);
keppler_orbit.set_accuracy(eph.sva);
keppler_orbit.set_health(eph.svh);
keppler_orbit.set_tgd(eph.tgd[0]);
keppler_orbit.set_iodc(eph.iodc);
int prn = 0;
satsys(eph.sat, &prn);
keppler_orbit.set_sat_prn(prn);
ROS_INFO_STREAM("Keppler orbit debuginfo:\r\n"
<< keppler_orbit.DebugString());
}
void Rtcm3Parser::fill_glonass_orbit(
geph_t &eph, apollo::drivers::gnss::GlonassOrbit &orbit) {
orbit.set_position_x(eph.pos[0]);
orbit.set_position_y(eph.pos[1]);
orbit.set_position_z(eph.pos[2]);
orbit.set_velocity_x(eph.vel[0]);
orbit.set_velocity_y(eph.vel[1]);
orbit.set_velocity_z(eph.vel[2]);
orbit.set_accelerate_x(eph.acc[0]);
orbit.set_accelerate_y(eph.acc[1]);
orbit.set_accelerate_z(eph.acc[2]);
orbit.set_health(eph.svh);
orbit.set_clock_offset(-eph.taun);
orbit.set_clock_drift(eph.gamn);
orbit.set_infor_age(eph.age);
orbit.set_frequency_no(eph.frq);
// orbit.set_toe(eph.toe.time + eph.toe.sec);
// orbit.set_tk(eph.tof.time + eph.tof.sec);
int week = 0;
double second = 0.0;
second = time2gpst(eph.toe, &week);
orbit.set_week_num(week);
orbit.set_week_second_s(second);
orbit.set_toe(second);
second = time2gpst(eph.tof, &week);
orbit.set_tk(second);
orbit.set_gnss_time_type(apollo::drivers::gnss::GnssTimeType::GPS_TIME);
int prn = 0;
satsys(eph.sat, &prn);
orbit.set_slot_prn(prn);
}
void Rtcm3Parser::set_observation_time() {
int week = 0;
double second = 0.0;
second = time2gpst(_rtcm.time, &week);
_observation.set_gnss_time_type(apollo::drivers::gnss::GPS_TIME);
_observation.set_gnss_week(week);
_observation.set_gnss_second_s(second);
}
Parser::MessageType Rtcm3Parser::get_message(MessagePtr &message_ptr) {
if (_data == nullptr) {
return MessageType::NONE;
}
int status = 0;
while (_data < _data_end) {
status = input_rtcm3(&_rtcm, *_data++); // parse data use rtklib
switch (status) {
case 1: // observation data
if (process_observation()) {
message_ptr = &_observation;
return MessageType::OBSERVATION;
}
break;
case 2: // ephemeris
if (process_ephemerides()) {
message_ptr = &_ephemeris;
return MessageType::EPHEMERIDES;
}
break;
case 5:
process_station_parameters();
break;
case 10: // ssr messages
default:
break;
}
}
return MessageType::NONE;
}
bool Rtcm3Parser::process_observation() {
ROS_INFO("======Observation message.");
ROS_INFO("Message type %d.", _rtcm.message_type);
ROS_INFO_STREAM("Is base station: " << _is_base_station);
ROS_INFO("Observation number %d.", _rtcm.obs.n);
ROS_INFO("Station Id %d.", _rtcm.staid);
ROS_INFO("time %ld.", _rtcm.time.time);
ROS_INFO("sec %f.", _rtcm.time.sec);
if (_rtcm.obs.n == 0) {
ROS_WARN("Obs is zero.");
}
_observation.Clear();
set_station_position();
if (!_is_base_station) {
_observation.set_receiver_id(0);
} else {
_observation.set_receiver_id(_rtcm.staid + 0x80000000);
}
// set time
set_observation_time();
// set satellite obs
_observation.set_sat_obs_num(_rtcm.obs.n);
_observation.set_health_flag(_rtcm.stah);
for (int i = 0; i < _rtcm.obs.n; ++i) {
int prn = 0;
int sys = 0;
sys = satsys(_rtcm.obs.data[i].sat, &prn);
ROS_INFO("sat %d, receiver %d.", _rtcm.obs.data[i].sat,
_rtcm.obs.data[i].rcv);
ROS_INFO("sys %d, prn %d.", sys, prn);
apollo::drivers::gnss::GnssType gnss_type;
// transform sys to local sys type
if (!gnss_sys_type(sys, gnss_type)) {
return false;
}
auto sat_obs = _observation.add_sat_obs(); // create obj
sat_obs->set_sat_prn(prn);
sat_obs->set_sat_sys(gnss_type);
int j = 0;
for (j = 0; j < NFREQ + NEXOBS; ++j) {
if (is_zero(_rtcm.obs.data[i].L[j])) {
break;
}
apollo::drivers::gnss::GnssBandID baud_id;
if (!gnss_baud_id(gnss_type, j, baud_id)) {
break;
}
double freq = 0;
gnss_frequence(baud_id, freq);
auto band_obs = sat_obs->add_band_obs();
if (_rtcm.obs.data[i].code[i] == CODE_L1C) {
band_obs->set_pseudo_type(
apollo::drivers::gnss::PseudoType::CORSE_CODE);
} else if (_rtcm.obs.data[i].code[i] == CODE_L1P) {
band_obs->set_pseudo_type(
apollo::drivers::gnss::PseudoType::PRECISION_CODE);
} else {
ROS_INFO("Message type %d.", _rtcm.message_type);
ROS_INFO("Code %d, in seq %d, gnss type %d.", _rtcm.obs.data[i].code[i],
j, static_cast<int>(gnss_type));
}
band_obs->set_band_id(baud_id);
band_obs->set_frequency_value(freq);
band_obs->set_pseudo_range(_rtcm.obs.data[i].P[j]);
band_obs->set_carrier_phase(_rtcm.obs.data[i].L[j]);
band_obs->set_loss_lock_index(_rtcm.obs.data[i].SNR[j]);
band_obs->set_doppler(_rtcm.obs.data[i].D[j]);
band_obs->set_snr(_rtcm.obs.data[i].SNR[j]);
}
ROS_INFO("Baud obs num %d.", j);
sat_obs->set_band_obs_num(j);
}
ROS_INFO_STREAM("Obeservation debuginfo:\r\n" << _observation.DebugString());
return true;
}
bool Rtcm3Parser::process_ephemerides() {
apollo::drivers::gnss::GnssType gnss_type;
ROS_INFO("======Ephemeris Message.");
ROS_INFO("Message type %d.", _rtcm.message_type);
ROS_INFO_STREAM("Is base station: " << _is_base_station);
if (!gnss_sys(_rtcm.message_type, gnss_type)) {
ROS_INFO("Failed get gnss type from message type %d.", _rtcm.message_type);
return false;
;
}
apollo::drivers::gnss::GnssTimeType time_type;
gnss_time_type(gnss_type, time_type);
ROS_INFO("Gnss sys %d ephemeris info.", static_cast<int>(gnss_type));
_ephemeris.Clear();
_ephemeris.set_gnss_type(gnss_type);
if (gnss_type == apollo::drivers::gnss::GnssType::GLO_SYS) {
auto obit = _ephemeris.mutable_glonass_orbit();
obit->set_gnss_type(gnss_type);
obit->set_gnss_time_type(time_type);
fill_glonass_orbit(_rtcm.nav.geph[_rtcm.ephsat - 1], *obit);
} else {
auto obit = _ephemeris.mutable_keppler_orbit();
obit->set_gnss_type(gnss_type);
obit->set_gnss_time_type(time_type);
fill_keppler_orbit(_rtcm.nav.eph[_rtcm.ephsat - 1], *obit);
}
ROS_INFO_STREAM("Ephemeris debuginfo:\r\n" << _ephemeris.DebugString());
return true;
}
bool Rtcm3Parser::process_station_parameters() {
// station pose/ant parameters, set pose.
ROS_INFO("======Station parameters message.");
ROS_INFO("Message type %d.", _rtcm.message_type);
ROS_INFO_STREAM("Is base station: " << _is_base_station);
ROS_INFO("Station receiver number %s.", _rtcm.sta.recsno);
ROS_INFO("Station pose (%f, %f, %f).", _rtcm.sta.pos[0], _rtcm.sta.pos[1],
_rtcm.sta.pos[2]);
// update station location
auto iter = _station_location.find(_rtcm.staid);
if (iter == _station_location.end()) {
Point3D point;
ROS_INFO("Add pose for station id: %d.", _rtcm.staid);
point.x = _rtcm.sta.pos[0];
point.y = _rtcm.sta.pos[1];
point.z = _rtcm.sta.pos[2];
_station_location.insert(std::make_pair(_rtcm.staid, point));
} else {
iter->second.x = _rtcm.sta.pos[0];
iter->second.y = _rtcm.sta.pos[1];
iter->second.z = _rtcm.sta.pos[2];
}
return true;
}
} // namespace gnss
} // namespace drivers
} // namespace apollo
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2010-2014 Jeremy Lainé
* Contact: https://github.com/jlaine/qdjango
*
* This file is part of the QDjango Library.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
#include <QLocalSocket>
#include <QTcpSocket>
#include <QtTest>
#include <QUrl>
#include "QDjangoFastCgiServer.h"
#include "QDjangoFastCgiServer_p.h"
#include "QDjangoHttpController.h"
#include "QDjangoHttpRequest.h"
#include "QDjangoHttpResponse.h"
#include "QDjangoFastCgiServer.h"
#include "QDjangoUrlResolver.h"
#define ERROR_DATA QByteArray("Status: 500 Internal Server Error\r\n" \
"Content-Length: 107\r\n" \
"Content-Type: text/html; charset=utf-8\r\n" \
"\r\n" \
"<html><head><title>Error</title></head><body><p>An internal server error was encountered.</p></body></html>")
#define NOT_FOUND_DATA QByteArray("Status: 404 Not Found\r\n" \
"Content-Length: 107\r\n" \
"Content-Type: text/html; charset=utf-8\r\n" \
"\r\n" \
"<html><head><title>Error</title></head><body><p>The document you requested was not found.</p></body></html>")
#define ROOT_DATA QByteArray("Status: 200 OK\r\n" \
"Content-Length: 17\r\n" \
"Content-Type: text/plain\r\n" \
"\r\n" \
"method=GET|path=/")
#define QUERY_STRING_DATA QByteArray("Status: 200 OK\r\n" \
"Content-Length: 25\r\n" \
"Content-Type: text/plain\r\n" \
"\r\n" \
"method=GET|path=/|get=bar")
class QDjangoFastCgiReply : public QObject
{
Q_OBJECT
public:
QDjangoFastCgiReply(QObject *parent = 0)
: QObject(parent) {};
QByteArray data;
signals:
void finished();
};
class QDjangoFastCgiClient : public QObject
{
Q_OBJECT
public:
QDjangoFastCgiClient(QIODevice *socket);
QDjangoFastCgiReply* get(const QUrl &url);
private slots:
void _q_readyRead();
private:
QIODevice *m_device;
QMap<quint16, QDjangoFastCgiReply*> m_replies;
quint16 m_requestId;
};
QDjangoFastCgiClient::QDjangoFastCgiClient(QIODevice *socket)
: m_device(socket)
, m_requestId(0)
{
connect(socket, SIGNAL(readyRead()), this, SLOT(_q_readyRead()));
};
QDjangoFastCgiReply* QDjangoFastCgiClient::get(const QUrl &url)
{
const quint16 requestId = ++m_requestId;
QDjangoFastCgiReply *reply = new QDjangoFastCgiReply(this);
m_replies[requestId] = reply;
QByteArray headerBuffer(FCGI_HEADER_LEN, '\0');
FCGI_Header *header = (FCGI_Header*)headerBuffer.data();
QByteArray ba;
// BEGIN REQUEST
ba = QByteArray("\x01\x00\x00\x00\x00\x00\x00\x00", 8);
header->version = 1;
header->requestIdB0 = requestId;
header->requestIdB1 = 0;
header->type = FCGI_BEGIN_REQUEST;
header->contentLengthB0 = ba.size();
header->contentLengthB1 = 0;
m_device->write(headerBuffer + ba);
QMap<QByteArray, QByteArray> params;
params["PATH_INFO"] = url.path().toUtf8();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
params["QUERY_STRING"] = url.query().toUtf8();
#else
params["QUERY_STRING"] = url.encodedQuery();
#endif
params["REQUEST_URI"] = url.toString().toUtf8();
params["REQUEST_METHOD"] = "GET";
ba.clear();
foreach (const QByteArray &key, params.keys()) {
const QByteArray value = params.value(key);
ba.append(char(key.size()));
ba.append(char(value.size()));
ba.append(key);
ba.append(value);
}
// FAST CGI PARAMS
header->type = FCGI_PARAMS;
header->contentLengthB0 = ba.size();
m_device->write(headerBuffer + ba);
// STDIN
header->type = FCGI_STDIN;
header->contentLengthB0 = 0;
m_device->write(headerBuffer);
return reply;
}
void QDjangoFastCgiClient::_q_readyRead()
{
char inputBuffer[FCGI_RECORD_SIZE];
FCGI_Header *header = (FCGI_Header*)inputBuffer;
while (m_device->bytesAvailable()) {
if (m_device->read(inputBuffer, FCGI_HEADER_LEN) != FCGI_HEADER_LEN) {
qWarning("header read fail");
return;
}
const quint16 requestId = (header->requestIdB1 << 8) | header->requestIdB0;
const quint16 contentLength = (header->contentLengthB1 << 8) | header->contentLengthB0;
const quint16 bodyLength = contentLength + header->paddingLength;
if (m_device->read(inputBuffer + FCGI_HEADER_LEN, bodyLength) != bodyLength) {
qWarning("body read fail");
return;
}
if (!m_replies.contains(requestId)) {
qWarning() << "unknown request" << requestId;
return;
}
if (header->type == FCGI_STDOUT) {
const QByteArray data = QByteArray(inputBuffer + FCGI_HEADER_LEN, contentLength);
m_replies[requestId]->data += data;
} else if (header->type == FCGI_END_REQUEST) {
m_replies[requestId]->finished();
}
}
}
/** Test QDjangoFastCgiServer class.
*/
class tst_QDjangoFastCgiServer : public QObject
{
Q_OBJECT
private slots:
void cleanup();
void init();
void testLocal_data();
void testLocal();
void testTcp_data();
void testTcp();
QDjangoHttpResponse* _q_index(const QDjangoHttpRequest &request);
QDjangoHttpResponse* _q_error(const QDjangoHttpRequest &request);
private:
QDjangoFastCgiServer *server;
};
void tst_QDjangoFastCgiServer::cleanup()
{
server->close();
delete server;
}
void tst_QDjangoFastCgiServer::init()
{
server = new QDjangoFastCgiServer;
server->urls()->set(QRegExp(QLatin1String(QLatin1String("^$"))), this, "_q_index");
server->urls()->set(QRegExp(QLatin1String("^internal-server-error$")), this, "_q_error");
}
void tst_QDjangoFastCgiServer::testLocal_data()
{
QTest::addColumn<QString>("path");
QTest::addColumn<QByteArray>("data");
QTest::newRow("root") << "/" << ROOT_DATA;
QTest::newRow("query-string") << "/?message=bar" << QUERY_STRING_DATA;
QTest::newRow("not-found") << "/not-found" << NOT_FOUND_DATA;
QTest::newRow("internal-server-error") << "/internal-server-error" << ERROR_DATA;
}
void tst_QDjangoFastCgiServer::testLocal()
{
QFETCH(QString, path);
QFETCH(QByteArray, data);
const QString name("/tmp/qdjangofastcgi.socket");
QCOMPARE(server->listen(name), true);
QLocalSocket socket;
socket.connectToServer(name);
QCOMPARE(socket.state(), QLocalSocket::ConnectedState);
QDjangoFastCgiClient client(&socket);
QDjangoFastCgiReply *reply = client.get(path);
QEventLoop loop;
QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QCOMPARE(reply->data, data);
}
void tst_QDjangoFastCgiServer::testTcp_data()
{
QTest::addColumn<QString>("path");
QTest::addColumn<QByteArray>("data");
QTest::newRow("root") << "/" << ROOT_DATA;
QTest::newRow("query-string") << "/?message=bar" << QUERY_STRING_DATA;
QTest::newRow("not-found") << "/not-found" << NOT_FOUND_DATA;
QTest::newRow("internal-server-error") << "/internal-server-error" << ERROR_DATA;
}
void tst_QDjangoFastCgiServer::testTcp()
{
QFETCH(QString, path);
QFETCH(QByteArray, data);
QCOMPARE(server->listen(QHostAddress::LocalHost, 8123), true);
QTcpSocket socket;
socket.connectToHost("127.0.0.1", 8123);
QDjangoFastCgiClient client(&socket);
QEventLoop loop;
QObject::connect(&socket, SIGNAL(connected()), &loop, SLOT(quit()));
loop.exec();
QCOMPARE(socket.state(), QAbstractSocket::ConnectedState);
QDjangoFastCgiReply *reply = client.get(path);
QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QCOMPARE(reply->data, data);
}
QDjangoHttpResponse *tst_QDjangoFastCgiServer::_q_index(const QDjangoHttpRequest &request)
{
QDjangoHttpResponse *response = new QDjangoHttpResponse;
response->setHeader(QLatin1String("Content-Type"), QLatin1String("text/plain"));
QString output = QLatin1String("method=") + request.method();
output += QLatin1String("|path=") + request.path();
const QString getValue = request.get(QLatin1String("message"));
if (!getValue.isEmpty())
output += QLatin1String("|get=") + getValue;
const QString postValue = request.post(QLatin1String("message"));
if (!postValue.isEmpty())
output += QLatin1String("|post=") + postValue;
response->setBody(output.toUtf8());
return response;
}
QDjangoHttpResponse *tst_QDjangoFastCgiServer::_q_error(const QDjangoHttpRequest &request)
{
Q_UNUSED(request);
return QDjangoHttpController::serveInternalServerError(request);
}
QTEST_MAIN(tst_QDjangoFastCgiServer)
#include "tst_qdjangofastcgiserver.moc"
<commit_msg>try again to fix tests<commit_after>/*
* Copyright (C) 2010-2014 Jeremy Lainé
* Contact: https://github.com/jlaine/qdjango
*
* This file is part of the QDjango Library.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
#include <QLocalSocket>
#include <QTcpSocket>
#include <QtTest>
#include <QUrl>
#include "QDjangoFastCgiServer.h"
#include "QDjangoFastCgiServer_p.h"
#include "QDjangoHttpController.h"
#include "QDjangoHttpRequest.h"
#include "QDjangoHttpResponse.h"
#include "QDjangoFastCgiServer.h"
#include "QDjangoUrlResolver.h"
#define ERROR_DATA QByteArray("Status: 500 Internal Server Error\r\n" \
"Content-Length: 107\r\n" \
"Content-Type: text/html; charset=utf-8\r\n" \
"\r\n" \
"<html><head><title>Error</title></head><body><p>An internal server error was encountered.</p></body></html>")
#define NOT_FOUND_DATA QByteArray("Status: 404 Not Found\r\n" \
"Content-Length: 107\r\n" \
"Content-Type: text/html; charset=utf-8\r\n" \
"\r\n" \
"<html><head><title>Error</title></head><body><p>The document you requested was not found.</p></body></html>")
#define ROOT_DATA QByteArray("Status: 200 OK\r\n" \
"Content-Length: 17\r\n" \
"Content-Type: text/plain\r\n" \
"\r\n" \
"method=GET|path=/")
#define QUERY_STRING_DATA QByteArray("Status: 200 OK\r\n" \
"Content-Length: 25\r\n" \
"Content-Type: text/plain\r\n" \
"\r\n" \
"method=GET|path=/|get=bar")
class QDjangoFastCgiReply : public QObject
{
Q_OBJECT
public:
QDjangoFastCgiReply(QObject *parent = 0)
: QObject(parent) {};
QByteArray data;
signals:
void finished();
};
class QDjangoFastCgiClient : public QObject
{
Q_OBJECT
public:
QDjangoFastCgiClient(QIODevice *socket);
QDjangoFastCgiReply* get(const QUrl &url);
private slots:
void _q_readyRead();
private:
QIODevice *m_device;
QMap<quint16, QDjangoFastCgiReply*> m_replies;
quint16 m_requestId;
};
QDjangoFastCgiClient::QDjangoFastCgiClient(QIODevice *socket)
: m_device(socket)
, m_requestId(0)
{
connect(socket, SIGNAL(readyRead()), this, SLOT(_q_readyRead()));
};
QDjangoFastCgiReply* QDjangoFastCgiClient::get(const QUrl &url)
{
const quint16 requestId = ++m_requestId;
QDjangoFastCgiReply *reply = new QDjangoFastCgiReply(this);
m_replies[requestId] = reply;
QByteArray headerBuffer(FCGI_HEADER_LEN, '\0');
FCGI_Header *header = (FCGI_Header*)headerBuffer.data();
QByteArray ba;
// BEGIN REQUEST
ba = QByteArray("\x01\x00\x00\x00\x00\x00\x00\x00", 8);
header->version = 1;
header->requestIdB0 = requestId;
header->requestIdB1 = 0;
header->type = FCGI_BEGIN_REQUEST;
header->contentLengthB0 = ba.size();
header->contentLengthB1 = 0;
m_device->write(headerBuffer + ba);
QMap<QByteArray, QByteArray> params;
params["PATH_INFO"] = url.path().toUtf8();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
params["QUERY_STRING"] = url.query().toUtf8();
#else
params["QUERY_STRING"] = url.encodedQuery();
#endif
params["REQUEST_URI"] = url.toString().toUtf8();
params["REQUEST_METHOD"] = "GET";
ba.clear();
foreach (const QByteArray &key, params.keys()) {
const QByteArray value = params.value(key);
ba.append(char(key.size()));
ba.append(char(value.size()));
ba.append(key);
ba.append(value);
}
// FAST CGI PARAMS
header->type = FCGI_PARAMS;
header->contentLengthB0 = ba.size();
m_device->write(headerBuffer + ba);
// STDIN
header->type = FCGI_STDIN;
header->contentLengthB0 = 0;
m_device->write(headerBuffer);
return reply;
}
void QDjangoFastCgiClient::_q_readyRead()
{
char inputBuffer[FCGI_RECORD_SIZE];
FCGI_Header *header = (FCGI_Header*)inputBuffer;
while (m_device->bytesAvailable()) {
if (m_device->read(inputBuffer, FCGI_HEADER_LEN) != FCGI_HEADER_LEN) {
qWarning("header read fail");
return;
}
const quint16 requestId = (header->requestIdB1 << 8) | header->requestIdB0;
const quint16 contentLength = (header->contentLengthB1 << 8) | header->contentLengthB0;
const quint16 bodyLength = contentLength + header->paddingLength;
if (m_device->read(inputBuffer + FCGI_HEADER_LEN, bodyLength) != bodyLength) {
qWarning("body read fail");
return;
}
if (!m_replies.contains(requestId)) {
qWarning() << "unknown request" << requestId;
return;
}
if (header->type == FCGI_STDOUT) {
const QByteArray data = QByteArray(inputBuffer + FCGI_HEADER_LEN, contentLength);
m_replies[requestId]->data += data;
} else if (header->type == FCGI_END_REQUEST) {
QMetaObject::invokeMethod(m_replies[requestId], "finished");
}
}
}
/** Test QDjangoFastCgiServer class.
*/
class tst_QDjangoFastCgiServer : public QObject
{
Q_OBJECT
private slots:
void cleanup();
void init();
void testLocal_data();
void testLocal();
void testTcp_data();
void testTcp();
QDjangoHttpResponse* _q_index(const QDjangoHttpRequest &request);
QDjangoHttpResponse* _q_error(const QDjangoHttpRequest &request);
private:
QDjangoFastCgiServer *server;
};
void tst_QDjangoFastCgiServer::cleanup()
{
server->close();
delete server;
}
void tst_QDjangoFastCgiServer::init()
{
server = new QDjangoFastCgiServer;
server->urls()->set(QRegExp(QLatin1String(QLatin1String("^$"))), this, "_q_index");
server->urls()->set(QRegExp(QLatin1String("^internal-server-error$")), this, "_q_error");
}
void tst_QDjangoFastCgiServer::testLocal_data()
{
QTest::addColumn<QString>("path");
QTest::addColumn<QByteArray>("data");
QTest::newRow("root") << "/" << ROOT_DATA;
QTest::newRow("query-string") << "/?message=bar" << QUERY_STRING_DATA;
QTest::newRow("not-found") << "/not-found" << NOT_FOUND_DATA;
QTest::newRow("internal-server-error") << "/internal-server-error" << ERROR_DATA;
}
void tst_QDjangoFastCgiServer::testLocal()
{
QFETCH(QString, path);
QFETCH(QByteArray, data);
const QString name("/tmp/qdjangofastcgi.socket");
QCOMPARE(server->listen(name), true);
QLocalSocket socket;
socket.connectToServer(name);
QCOMPARE(socket.state(), QLocalSocket::ConnectedState);
QDjangoFastCgiClient client(&socket);
QDjangoFastCgiReply *reply = client.get(path);
QEventLoop loop;
QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QCOMPARE(reply->data, data);
}
void tst_QDjangoFastCgiServer::testTcp_data()
{
QTest::addColumn<QString>("path");
QTest::addColumn<QByteArray>("data");
QTest::newRow("root") << "/" << ROOT_DATA;
QTest::newRow("query-string") << "/?message=bar" << QUERY_STRING_DATA;
QTest::newRow("not-found") << "/not-found" << NOT_FOUND_DATA;
QTest::newRow("internal-server-error") << "/internal-server-error" << ERROR_DATA;
}
void tst_QDjangoFastCgiServer::testTcp()
{
QFETCH(QString, path);
QFETCH(QByteArray, data);
QCOMPARE(server->listen(QHostAddress::LocalHost, 8123), true);
QTcpSocket socket;
socket.connectToHost("127.0.0.1", 8123);
QDjangoFastCgiClient client(&socket);
QEventLoop loop;
QObject::connect(&socket, SIGNAL(connected()), &loop, SLOT(quit()));
loop.exec();
QCOMPARE(socket.state(), QAbstractSocket::ConnectedState);
QDjangoFastCgiReply *reply = client.get(path);
QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
QCOMPARE(reply->data, data);
}
QDjangoHttpResponse *tst_QDjangoFastCgiServer::_q_index(const QDjangoHttpRequest &request)
{
QDjangoHttpResponse *response = new QDjangoHttpResponse;
response->setHeader(QLatin1String("Content-Type"), QLatin1String("text/plain"));
QString output = QLatin1String("method=") + request.method();
output += QLatin1String("|path=") + request.path();
const QString getValue = request.get(QLatin1String("message"));
if (!getValue.isEmpty())
output += QLatin1String("|get=") + getValue;
const QString postValue = request.post(QLatin1String("message"));
if (!postValue.isEmpty())
output += QLatin1String("|post=") + postValue;
response->setBody(output.toUtf8());
return response;
}
QDjangoHttpResponse *tst_QDjangoFastCgiServer::_q_error(const QDjangoHttpRequest &request)
{
Q_UNUSED(request);
return QDjangoHttpController::serveInternalServerError(request);
}
QTEST_MAIN(tst_QDjangoFastCgiServer)
#include "tst_qdjangofastcgiserver.moc"
<|endoftext|>
|
<commit_before>#include "MacauPrior.h"
#include <SmurffCpp/IO/MatrixIO.h>
#include <SmurffCpp/IO/GenericIO.h>
#include <SmurffCpp/Utils/Distribution.h>
#include <SmurffCpp/Utils/Error.h>
#include <SmurffCpp/Utils/counters.h>
#include <SmurffCpp/Utils/linop.h>
#include <ios>
using namespace smurff;
MacauPrior::MacauPrior()
: NormalPrior()
{
}
MacauPrior::MacauPrior(std::shared_ptr<Session> session, uint32_t mode)
: NormalPrior(session, mode, "MacauPrior")
{
beta_precision = SideInfoConfig::BETA_PRECISION_DEFAULT_VALUE;
tol = SideInfoConfig::TOL_DEFAULT_VALUE;
enable_beta_precision_sampling = Config::ENABLE_BETA_PRECISION_SAMPLING_DEFAULT_VALUE;
}
MacauPrior::~MacauPrior()
{
}
void MacauPrior::init()
{
NormalPrior::init();
THROWERROR_ASSERT_MSG(Features->rows() == num_item(), "Number of rows in train must be equal to number of rows in features");
if (use_FtF)
{
std::uint64_t dim = num_feat();
FtF_plus_precision.resize(dim, dim);
Features->At_mul_A(FtF_plus_precision);
FtF_plus_precision.diagonal().array() += beta_precision;
}
Uhat.resize(num_latent(), Features->rows());
Uhat.setZero();
m_beta = std::make_shared<Eigen::MatrixXd>(num_latent(), num_feat());
beta().setZero();
m_session->model().setLinkMatrix(m_mode, m_beta);
}
void MacauPrior::update_prior()
{
/*
>> compute_uhat: 0.5012 (12%) in 110
>> main: 4.1396 (100%) in 1
>> rest of update_prior: 0.1684 (4%) in 110
>> sample hyper mu/Lambda: 0.3804 (9%) in 110
>> sample_beta: 1.4927 (36%) in 110
>> sample_latents: 3.8824 (94%) in 220
>> step: 3.9824 (96%) in 111
>> update_prior: 2.5436 (61%) in 110
*/
COUNTER("update_prior");
{
COUNTER("rest of update_prior");
// residual (Uhat is later overwritten):
//uses: U, Uhat
//writes: Uhat
Udelta = U() - Uhat;
}
// sampling Gaussian
{
COUNTER("sample hyper mu/Lambda");
// BBt = beta * beta'
//uses: beta
BBt = beta() * beta().transpose();
// Uses, Udelta
std::tie(mu, Lambda) = CondNormalWishart(Udelta, mu0, b0,
WI + beta_precision * BBt, df + num_feat());
}
// uses: U, F
// writes: Ft_y
compute_Ft_y_omp(Ft_y);
sample_beta();
{
COUNTER("compute_uhat");
// Uhat = beta * F
// uses: beta, F
// output: Uhat
Features->compute_uhat(Uhat, beta());
}
if (enable_beta_precision_sampling)
{
// uses: beta
// writes: FtF
COUNTER("sample_beta_precision");
double old_beta = beta_precision;
beta_precision = sample_beta_precision(beta(), Lambda, beta_precision_nu0, beta_precision_mu0);
FtF_plus_precision.diagonal().array() += beta_precision - old_beta;
}
}
void MacauPrior::sample_beta()
{
COUNTER("sample_beta");
if (use_FtF)
{
// uses: FtF, Ft_y,
// writes: beta
beta() = FtF_plus_precision.llt().solve(Ft_y.transpose()).transpose();
}
else
{
// uses: Features, beta_precision, Ft_y,
// writes: beta
blockcg_iter = Features->solve_blockcg(beta(), beta_precision, Ft_y, tol, 32, 8, throw_on_cholesky_error);
}
}
const Eigen::VectorXd MacauPrior::getMu(int n) const
{
return mu + Uhat.col(n);
}
void MacauPrior::compute_Ft_y_omp(Eigen::MatrixXd& Ft_y)
{
//-- input
// mu, Lambda (small)
// U
// F
//-- output
// Ft_y
// Ft_y = (U .- mu + Normal(0, Lambda^-1)) * F + std::sqrt(beta_precision) * Normal(0, Lambda^-1)
// Ft_y is [ D x F ] matrix
//HyperU: num_latent x num_item
HyperU = (U() + MvNormal_prec(Lambda, num_item())).colwise() - mu;
Ft_y = Features->A_mul_B(HyperU); // num_latent x num_feat
//-- add beta_precision
HyperU2 = MvNormal_prec(Lambda, num_feat()); // num_latent x num_feat
#pragma omp parallel for schedule(static)
for (int f = 0; f < num_feat(); f++)
{
for (int d = 0; d < num_latent(); d++)
{
Ft_y(d, f) += std::sqrt(beta_precision) * HyperU2(d, f);
}
}
}
void MacauPrior::addSideInfo(const std::shared_ptr<ISideInfo>& side_info_a, double beta_precision_a, double tolerance_a, bool direct_a, bool enable_beta_precision_sampling_a, bool throw_on_cholesky_error_a)
{
//FIXME: remove old code
// old code
// side information
Features = side_info_a;
beta_precision = beta_precision_a;
tol = tolerance_a;
use_FtF = direct_a;
enable_beta_precision_sampling = enable_beta_precision_sampling_a;
throw_on_cholesky_error = throw_on_cholesky_error_a;
// new code
// side information
side_info_values.push_back(side_info_a);
beta_precision_values.push_back(beta_precision_a);
tol_values.push_back(tolerance_a);
direct_values.push_back(direct_a);
enable_beta_precision_sampling_values.push_back(enable_beta_precision_sampling_a);
throw_on_cholesky_error_values.push_back(throw_on_cholesky_error_a);
// other code
// Hyper-prior for beta_precision (mean 1.0, var of 1e+3):
beta_precision_mu0 = 1.0;
beta_precision_nu0 = 1e-3;
}
bool MacauPrior::save(std::shared_ptr<const StepFile> sf) const
{
NormalPrior::save(sf);
std::string path = sf->makeLinkMatrixFileName(m_mode);
smurff::matrix_io::eigen::write_matrix(path, beta());
return true;
}
void MacauPrior::restore(std::shared_ptr<const StepFile> sf)
{
NormalPrior::restore(sf);
std::string path = sf->getLinkMatrixFileName(m_mode);
THROWERROR_FILE_NOT_EXIST(path);
smurff::matrix_io::eigen::read_matrix(path, beta());
}
std::ostream& MacauPrior::info(std::ostream &os, std::string indent)
{
NormalPrior::info(os, indent);
os << indent << " SideInfo: ";
Features->print(os);
os << indent << " Method: ";
if (use_FtF)
{
os << "Cholesky Decomposition";
double needs_gb = (double)num_feat() / 1024. * (double)num_feat() / 1024. / 1024.;
if (needs_gb > 1.0) os << " (needing " << needs_gb << " GB of memory)";
os << std::endl;
} else {
os << "CG Solver with tolerance: " << std::scientific << tol << std::fixed << std::endl;
}
os << indent << " BetaPrecision: ";
if (enable_beta_precision_sampling)
{
os << "sampled around ";
}
else
{
os << "fixed at ";
}
os << beta_precision << std::endl;
return os;
}
std::ostream& MacauPrior::status(std::ostream &os, std::string indent) const
{
os << indent << m_name << ": " << std::endl;
indent += " ";
os << indent << "blockcg iter = " << blockcg_iter << std::endl;
os << indent << "FtF_plus_precision= " << FtF_plus_precision.norm() << std::endl;
os << indent << "HyperU = " << HyperU.norm() << std::endl;
os << indent << "HyperU2 = " << HyperU2.norm() << std::endl;
os << indent << "Beta = " << beta().norm() << std::endl;
os << indent << "beta_precision = " << beta_precision << std::endl;
os << indent << "Ft_y = " << Ft_y.norm() << std::endl;
return os;
}
std::pair<double, double> MacauPrior::posterior_beta_precision(Eigen::MatrixXd & beta, Eigen::MatrixXd & Lambda_u, double nu, double mu)
{
auto BB = beta * beta.transpose();
double nux = nu + beta.rows() * beta.cols();
double mux = mu * nux / (nu + mu * (BB.selfadjointView<Eigen::Lower>() * Lambda_u).trace());
double b = nux / 2;
double c = 2 * mux / nux;
return std::make_pair(b, c);
}
double MacauPrior::sample_beta_precision(Eigen::MatrixXd & beta, Eigen::MatrixXd & Lambda_u, double nu, double mu)
{
auto gamma_post = posterior_beta_precision(beta, Lambda_u, nu, mu);
return rgamma(gamma_post.first, gamma_post.second);
}
<commit_msg>ENH: simplify compute_Ft_y_omp<commit_after>#include "MacauPrior.h"
#include <SmurffCpp/IO/MatrixIO.h>
#include <SmurffCpp/IO/GenericIO.h>
#include <SmurffCpp/Utils/Distribution.h>
#include <SmurffCpp/Utils/Error.h>
#include <SmurffCpp/Utils/counters.h>
#include <SmurffCpp/Utils/linop.h>
#include <ios>
using namespace smurff;
MacauPrior::MacauPrior()
: NormalPrior()
{
}
MacauPrior::MacauPrior(std::shared_ptr<Session> session, uint32_t mode)
: NormalPrior(session, mode, "MacauPrior")
{
beta_precision = SideInfoConfig::BETA_PRECISION_DEFAULT_VALUE;
tol = SideInfoConfig::TOL_DEFAULT_VALUE;
enable_beta_precision_sampling = Config::ENABLE_BETA_PRECISION_SAMPLING_DEFAULT_VALUE;
}
MacauPrior::~MacauPrior()
{
}
void MacauPrior::init()
{
NormalPrior::init();
THROWERROR_ASSERT_MSG(Features->rows() == num_item(), "Number of rows in train must be equal to number of rows in features");
if (use_FtF)
{
std::uint64_t dim = num_feat();
FtF_plus_precision.resize(dim, dim);
Features->At_mul_A(FtF_plus_precision);
FtF_plus_precision.diagonal().array() += beta_precision;
}
Uhat.resize(num_latent(), Features->rows());
Uhat.setZero();
m_beta = std::make_shared<Eigen::MatrixXd>(num_latent(), num_feat());
beta().setZero();
m_session->model().setLinkMatrix(m_mode, m_beta);
}
void MacauPrior::update_prior()
{
/*
>> compute_uhat: 0.5012 (12%) in 110
>> main: 4.1396 (100%) in 1
>> rest of update_prior: 0.1684 (4%) in 110
>> sample hyper mu/Lambda: 0.3804 (9%) in 110
>> sample_beta: 1.4927 (36%) in 110
>> sample_latents: 3.8824 (94%) in 220
>> step: 3.9824 (96%) in 111
>> update_prior: 2.5436 (61%) in 110
*/
COUNTER("update_prior");
{
COUNTER("rest of update_prior");
// residual (Uhat is later overwritten):
//uses: U, Uhat
//writes: Uhat
Udelta = U() - Uhat;
}
// sampling Gaussian
{
COUNTER("sample hyper mu/Lambda");
// BBt = beta * beta'
//uses: beta
BBt = beta() * beta().transpose();
// Uses, Udelta
std::tie(mu, Lambda) = CondNormalWishart(Udelta, mu0, b0,
WI + beta_precision * BBt, df + num_feat());
}
// uses: U, F
// writes: Ft_y
compute_Ft_y_omp(Ft_y);
sample_beta();
{
COUNTER("compute_uhat");
// Uhat = beta * F
// uses: beta, F
// output: Uhat
Features->compute_uhat(Uhat, beta());
}
if (enable_beta_precision_sampling)
{
// uses: beta
// writes: FtF
COUNTER("sample_beta_precision");
double old_beta = beta_precision;
beta_precision = sample_beta_precision(beta(), Lambda, beta_precision_nu0, beta_precision_mu0);
FtF_plus_precision.diagonal().array() += beta_precision - old_beta;
}
}
void MacauPrior::sample_beta()
{
COUNTER("sample_beta");
if (use_FtF)
{
// uses: FtF, Ft_y,
// writes: beta
beta() = FtF_plus_precision.llt().solve(Ft_y.transpose()).transpose();
}
else
{
// uses: Features, beta_precision, Ft_y,
// writes: beta
blockcg_iter = Features->solve_blockcg(beta(), beta_precision, Ft_y, tol, 32, 8, throw_on_cholesky_error);
}
}
const Eigen::VectorXd MacauPrior::getMu(int n) const
{
return mu + Uhat.col(n);
}
void MacauPrior::compute_Ft_y_omp(Eigen::MatrixXd& Ft_y)
{
//-- input
// mu, Lambda (small)
// U
// F
//-- output
// Ft_y
// Ft_y = (U .- mu + Normal(0, Lambda^-1)) * F + std::sqrt(beta_precision) * Normal(0, Lambda^-1)
// Ft_y is [ D x F ] matrix
//HyperU: num_latent x num_item
HyperU = (U() + MvNormal_prec(Lambda, num_item())).colwise() - mu;
Ft_y = Features->A_mul_B(HyperU); // num_latent x num_feat
//-- add beta_precision
HyperU2 = MvNormal_prec(Lambda, num_feat()); // num_latent x num_feat
Ft_y += std::sqrt(beta_precision) * HyperU2;
}
void MacauPrior::addSideInfo(const std::shared_ptr<ISideInfo>& side_info_a, double beta_precision_a, double tolerance_a, bool direct_a, bool enable_beta_precision_sampling_a, bool throw_on_cholesky_error_a)
{
//FIXME: remove old code
// old code
// side information
Features = side_info_a;
beta_precision = beta_precision_a;
tol = tolerance_a;
use_FtF = direct_a;
enable_beta_precision_sampling = enable_beta_precision_sampling_a;
throw_on_cholesky_error = throw_on_cholesky_error_a;
// new code
// side information
side_info_values.push_back(side_info_a);
beta_precision_values.push_back(beta_precision_a);
tol_values.push_back(tolerance_a);
direct_values.push_back(direct_a);
enable_beta_precision_sampling_values.push_back(enable_beta_precision_sampling_a);
throw_on_cholesky_error_values.push_back(throw_on_cholesky_error_a);
// other code
// Hyper-prior for beta_precision (mean 1.0, var of 1e+3):
beta_precision_mu0 = 1.0;
beta_precision_nu0 = 1e-3;
}
bool MacauPrior::save(std::shared_ptr<const StepFile> sf) const
{
NormalPrior::save(sf);
std::string path = sf->makeLinkMatrixFileName(m_mode);
smurff::matrix_io::eigen::write_matrix(path, beta());
return true;
}
void MacauPrior::restore(std::shared_ptr<const StepFile> sf)
{
NormalPrior::restore(sf);
std::string path = sf->getLinkMatrixFileName(m_mode);
THROWERROR_FILE_NOT_EXIST(path);
smurff::matrix_io::eigen::read_matrix(path, beta());
}
std::ostream& MacauPrior::info(std::ostream &os, std::string indent)
{
NormalPrior::info(os, indent);
os << indent << " SideInfo: ";
Features->print(os);
os << indent << " Method: ";
if (use_FtF)
{
os << "Cholesky Decomposition";
double needs_gb = (double)num_feat() / 1024. * (double)num_feat() / 1024. / 1024.;
if (needs_gb > 1.0) os << " (needing " << needs_gb << " GB of memory)";
os << std::endl;
} else {
os << "CG Solver with tolerance: " << std::scientific << tol << std::fixed << std::endl;
}
os << indent << " BetaPrecision: ";
if (enable_beta_precision_sampling)
{
os << "sampled around ";
}
else
{
os << "fixed at ";
}
os << beta_precision << std::endl;
return os;
}
std::ostream& MacauPrior::status(std::ostream &os, std::string indent) const
{
os << indent << m_name << ": " << std::endl;
indent += " ";
os << indent << "blockcg iter = " << blockcg_iter << std::endl;
os << indent << "FtF_plus_precision= " << FtF_plus_precision.norm() << std::endl;
os << indent << "HyperU = " << HyperU.norm() << std::endl;
os << indent << "HyperU2 = " << HyperU2.norm() << std::endl;
os << indent << "Beta = " << beta().norm() << std::endl;
os << indent << "beta_precision = " << beta_precision << std::endl;
os << indent << "Ft_y = " << Ft_y.norm() << std::endl;
return os;
}
std::pair<double, double> MacauPrior::posterior_beta_precision(Eigen::MatrixXd & beta, Eigen::MatrixXd & Lambda_u, double nu, double mu)
{
auto BB = beta * beta.transpose();
double nux = nu + beta.rows() * beta.cols();
double mux = mu * nux / (nu + mu * (BB.selfadjointView<Eigen::Lower>() * Lambda_u).trace());
double b = nux / 2;
double c = 2 * mux / nux;
return std::make_pair(b, c);
}
double MacauPrior::sample_beta_precision(Eigen::MatrixXd & beta, Eigen::MatrixXd & Lambda_u, double nu, double mu)
{
auto gamma_post = posterior_beta_precision(beta, Lambda_u, nu, mu);
return rgamma(gamma_post.first, gamma_post.second);
}
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used 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. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "qmlinspectorconstants.h"
#include "qmlinspector.h"
#include "qmlinspectorplugin.h"
#include <debugger/debuggeruiswitcher.h>
#include <debugger/debuggerconstants.h>
#include <qmlprojectmanager/qmlproject.h>
#include <qmljseditor/qmljseditorconstants.h>
#include <coreplugin/modemanager.h>
#include <projectexplorer/projectexplorer.h>
#include <extensionsystem/pluginmanager.h>
#include <coreplugin/icore.h>
#include <projectexplorer/runconfiguration.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/project.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/uniqueidmanager.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/command.h>
#include <QtCore/QStringList>
#include <QtCore/QtPlugin>
#include <QtCore/QTimer>
#include <QtGui/QHBoxLayout>
#include <QtGui/QToolButton>
#include <QtGui/QMessageBox>
#include <QtCore/QDebug>
using namespace Qml;
static QToolButton *createToolButton(QAction *action)
{
QToolButton *button = new QToolButton;
button->setDefaultAction(action);
return button;
}
QmlInspectorPlugin::QmlInspectorPlugin()
: m_inspector(0), m_connectionTimer(new QTimer(this)),
m_connectionAttempts(0)
{
m_connectionTimer->setInterval(75);
}
QmlInspectorPlugin::~QmlInspectorPlugin()
{
}
void QmlInspectorPlugin::shutdown()
{
removeObject(m_inspector);
delete m_inspector;
m_inspector = 0;
}
bool QmlInspectorPlugin::initialize(const QStringList &arguments, QString *errorString)
{
Q_UNUSED(arguments);
Q_UNUSED(errorString);
Core::ICore *core = Core::ICore::instance();
connect(Core::ModeManager::instance(), SIGNAL(currentModeChanged(Core::IMode*)),
SLOT(prepareDebugger(Core::IMode*)));
ExtensionSystem::PluginManager *pluginManager = ExtensionSystem::PluginManager::instance();
Debugger::DebuggerUISwitcher *uiSwitcher = pluginManager->getObject<Debugger::DebuggerUISwitcher>();
uiSwitcher->addLanguage(Qml::Constants::LANG_QML,
QList<int>() << core->uniqueIDManager()->uniqueIdentifier(Constants::C_INSPECTOR));
m_inspector = new QmlInspector;
m_inspector->createDockWidgets();
addObject(m_inspector);
connect(m_connectionTimer, SIGNAL(timeout()), SLOT(pollInspector()));
return true;
}
void QmlInspectorPlugin::extensionsInitialized()
{
ExtensionSystem::PluginManager *pluginManager = ExtensionSystem::PluginManager::instance();
Debugger::DebuggerUISwitcher *uiSwitcher = pluginManager->getObject<Debugger::DebuggerUISwitcher>();
connect(uiSwitcher, SIGNAL(dockArranged(QString)), SLOT(setDockWidgetArrangement(QString)));
ProjectExplorer::ProjectExplorerPlugin *pex = ProjectExplorer::ProjectExplorerPlugin::instance();
if (pex) {
connect(pex, SIGNAL(aboutToExecuteProject(ProjectExplorer::Project*, QString)),
SLOT(activateDebuggerForProject(ProjectExplorer::Project*, QString)));
}
QWidget *configBar = new QWidget;
configBar->setProperty("topBorder", true);
QHBoxLayout *configBarLayout = new QHBoxLayout(configBar);
configBarLayout->setMargin(0);
configBarLayout->setSpacing(5);
Core::ICore *core = Core::ICore::instance();
Core::ActionManager *am = core->actionManager();
configBarLayout->addWidget(createToolButton(am->command(ProjectExplorer::Constants::DEBUG)->action()));
configBarLayout->addWidget(createToolButton(am->command(ProjectExplorer::Constants::STOP)->action()));
configBarLayout->addStretch();
uiSwitcher->setToolbar(Qml::Constants::LANG_QML, configBar);
}
void QmlInspectorPlugin::activateDebuggerForProject(ProjectExplorer::Project *project, const QString &runMode)
{
if (runMode == ProjectExplorer::Constants::DEBUGMODE) {
// FIXME we probably want to activate the debugger for other projects than QmlProjects,
// if they contain Qml files. Some kind of options should exist for this behavior.
//QmlProjectManager::QmlProject *qmlproj = qobject_cast<QmlProjectManager::QmlProject*>(project);
//if (qmlproj)
m_connectionTimer->start();
}
}
void QmlInspectorPlugin::pollInspector()
{
++m_connectionAttempts;
if (m_inspector->connectToViewer()) {
m_connectionTimer->stop();
m_connectionAttempts = 0;
} else if (m_connectionAttempts == MaxConnectionAttempts) {
m_connectionTimer->stop();
m_connectionAttempts = 0;
QMessageBox::critical(0,
tr("Failed to connect to debugger"),
tr("Could not connect to debugger server. Please check your settings from Projects pane.") );
}
}
void QmlInspectorPlugin::prepareDebugger(Core::IMode *mode)
{
if (mode->id() != Debugger::Constants::MODE_DEBUG)
return;
ProjectExplorer::ProjectExplorerPlugin *pex = ProjectExplorer::ProjectExplorerPlugin::instance();
if (pex->startupProject() && pex->startupProject()->id() == "QmlProjectManager.QmlProject")
{
ExtensionSystem::PluginManager *pluginManager = ExtensionSystem::PluginManager::instance();
Debugger::DebuggerUISwitcher *uiSwitcher = pluginManager->getObject<Debugger::DebuggerUISwitcher>();
uiSwitcher->setActiveLanguage(Qml::Constants::LANG_QML);
}
}
void QmlInspectorPlugin::setDockWidgetArrangement(const QString &activeLanguage)
{
if (activeLanguage == Qml::Constants::LANG_QML || activeLanguage.isEmpty())
m_inspector->setSimpleDockWidgetArrangement();
}
Q_EXPORT_PLUGIN(QmlInspectorPlugin)
<commit_msg>restored commented-out code<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used 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. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "qmlinspectorconstants.h"
#include "qmlinspector.h"
#include "qmlinspectorplugin.h"
#include <debugger/debuggeruiswitcher.h>
#include <debugger/debuggerconstants.h>
#include <qmlprojectmanager/qmlproject.h>
#include <qmljseditor/qmljseditorconstants.h>
#include <coreplugin/modemanager.h>
#include <projectexplorer/projectexplorer.h>
#include <extensionsystem/pluginmanager.h>
#include <coreplugin/icore.h>
#include <projectexplorer/runconfiguration.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/project.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/uniqueidmanager.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/command.h>
#include <QtCore/QStringList>
#include <QtCore/QtPlugin>
#include <QtCore/QTimer>
#include <QtGui/QHBoxLayout>
#include <QtGui/QToolButton>
#include <QtGui/QMessageBox>
#include <QtCore/QDebug>
using namespace Qml;
static QToolButton *createToolButton(QAction *action)
{
QToolButton *button = new QToolButton;
button->setDefaultAction(action);
return button;
}
QmlInspectorPlugin::QmlInspectorPlugin()
: m_inspector(0), m_connectionTimer(new QTimer(this)),
m_connectionAttempts(0)
{
m_connectionTimer->setInterval(75);
}
QmlInspectorPlugin::~QmlInspectorPlugin()
{
}
void QmlInspectorPlugin::shutdown()
{
removeObject(m_inspector);
delete m_inspector;
m_inspector = 0;
}
bool QmlInspectorPlugin::initialize(const QStringList &arguments, QString *errorString)
{
Q_UNUSED(arguments);
Q_UNUSED(errorString);
Core::ICore *core = Core::ICore::instance();
connect(Core::ModeManager::instance(), SIGNAL(currentModeChanged(Core::IMode*)),
SLOT(prepareDebugger(Core::IMode*)));
ExtensionSystem::PluginManager *pluginManager = ExtensionSystem::PluginManager::instance();
Debugger::DebuggerUISwitcher *uiSwitcher = pluginManager->getObject<Debugger::DebuggerUISwitcher>();
uiSwitcher->addLanguage(Qml::Constants::LANG_QML,
QList<int>() << core->uniqueIDManager()->uniqueIdentifier(Constants::C_INSPECTOR));
m_inspector = new QmlInspector;
m_inspector->createDockWidgets();
addObject(m_inspector);
connect(m_connectionTimer, SIGNAL(timeout()), SLOT(pollInspector()));
return true;
}
void QmlInspectorPlugin::extensionsInitialized()
{
ExtensionSystem::PluginManager *pluginManager = ExtensionSystem::PluginManager::instance();
Debugger::DebuggerUISwitcher *uiSwitcher = pluginManager->getObject<Debugger::DebuggerUISwitcher>();
connect(uiSwitcher, SIGNAL(dockArranged(QString)), SLOT(setDockWidgetArrangement(QString)));
ProjectExplorer::ProjectExplorerPlugin *pex = ProjectExplorer::ProjectExplorerPlugin::instance();
if (pex) {
connect(pex, SIGNAL(aboutToExecuteProject(ProjectExplorer::Project*, QString)),
SLOT(activateDebuggerForProject(ProjectExplorer::Project*, QString)));
}
QWidget *configBar = new QWidget;
configBar->setProperty("topBorder", true);
QHBoxLayout *configBarLayout = new QHBoxLayout(configBar);
configBarLayout->setMargin(0);
configBarLayout->setSpacing(5);
Core::ICore *core = Core::ICore::instance();
Core::ActionManager *am = core->actionManager();
configBarLayout->addWidget(createToolButton(am->command(ProjectExplorer::Constants::DEBUG)->action()));
configBarLayout->addWidget(createToolButton(am->command(ProjectExplorer::Constants::STOP)->action()));
configBarLayout->addStretch();
uiSwitcher->setToolbar(Qml::Constants::LANG_QML, configBar);
}
void QmlInspectorPlugin::activateDebuggerForProject(ProjectExplorer::Project *project, const QString &runMode)
{
if (runMode == ProjectExplorer::Constants::DEBUGMODE) {
// FIXME we probably want to activate the debugger for other projects than QmlProjects,
// if they contain Qml files. Some kind of options should exist for this behavior.
QmlProjectManager::QmlProject *qmlproj = qobject_cast<QmlProjectManager::QmlProject*>(project);
if (qmlproj)
m_connectionTimer->start();
}
}
void QmlInspectorPlugin::pollInspector()
{
++m_connectionAttempts;
if (m_inspector->connectToViewer()) {
m_connectionTimer->stop();
m_connectionAttempts = 0;
} else if (m_connectionAttempts == MaxConnectionAttempts) {
m_connectionTimer->stop();
m_connectionAttempts = 0;
QMessageBox::critical(0,
tr("Failed to connect to debugger"),
tr("Could not connect to debugger server. Please check your settings from Projects pane.") );
}
}
void QmlInspectorPlugin::prepareDebugger(Core::IMode *mode)
{
if (mode->id() != Debugger::Constants::MODE_DEBUG)
return;
ProjectExplorer::ProjectExplorerPlugin *pex = ProjectExplorer::ProjectExplorerPlugin::instance();
if (pex->startupProject() && pex->startupProject()->id() == "QmlProjectManager.QmlProject")
{
ExtensionSystem::PluginManager *pluginManager = ExtensionSystem::PluginManager::instance();
Debugger::DebuggerUISwitcher *uiSwitcher = pluginManager->getObject<Debugger::DebuggerUISwitcher>();
uiSwitcher->setActiveLanguage(Qml::Constants::LANG_QML);
}
}
void QmlInspectorPlugin::setDockWidgetArrangement(const QString &activeLanguage)
{
if (activeLanguage == Qml::Constants::LANG_QML || activeLanguage.isEmpty())
m_inspector->setSimpleDockWidgetArrangement();
}
Q_EXPORT_PLUGIN(QmlInspectorPlugin)
<|endoftext|>
|
<commit_before>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "xwalk/runtime/browser/xwalk_browser_main_parts_android.h"
#include <string>
#include "base/android/path_utils.h"
#include "base/base_paths_android.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/message_loop/message_loop.h"
#include "base/path_service.h"
#include "base/threading/sequenced_worker_pool.h"
#include "cc/base/switches.h"
#include "content/public/browser/android/compositor.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/cookie_store_factory.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/result_codes.h"
#include "net/android/network_change_notifier_factory_android.h"
#include "net/base/network_change_notifier.h"
#include "net/base/net_module.h"
#include "net/base/net_util.h"
#include "net/cookies/cookie_monster.h"
#include "net/cookies/cookie_store.h"
#include "net/grit/net_resources.h"
#include "ui/base/layout.h"
#include "ui/base/l10n/l10n_util_android.h"
#include "ui/base/resource/resource_bundle.h"
#include "xwalk/extensions/browser/xwalk_extension_service.h"
#include "xwalk/extensions/common/xwalk_extension.h"
#include "xwalk/extensions/common/xwalk_extension_switches.h"
#include "xwalk/runtime/browser/android/cookie_manager.h"
#include "xwalk/runtime/browser/xwalk_runner.h"
#include "xwalk/runtime/common/xwalk_runtime_features.h"
#include "xwalk/runtime/common/xwalk_switches.h"
namespace {
base::StringPiece PlatformResourceProvider(int key) {
if (key == IDR_DIR_HEADER_HTML) {
base::StringPiece html_data =
ui::ResourceBundle::GetSharedInstance().GetRawDataResource(
IDR_DIR_HEADER_HTML);
return html_data;
}
return base::StringPiece();
}
void MoveUserDataDirIfNecessary(const base::FilePath& user_data_dir,
const base::FilePath& profile) {
if (base::DirectoryExists(profile))
return;
if (!base::CreateDirectory(profile))
return;
const char* possible_data_dir_names[] = {
"Cache",
"Cookies",
"Cookies-journal",
"Local Storage",
};
for (int i = 0; i < 4; i++) {
base::FilePath dir = user_data_dir.Append(possible_data_dir_names[i]);
if (base::PathExists(dir)) {
if (!base::Move(dir, profile.Append(possible_data_dir_names[i]))) {
NOTREACHED() << "Failed to import previous user data: "
<< possible_data_dir_names[i];
}
}
}
}
} // namespace
namespace xwalk {
using content::BrowserThread;
using extensions::XWalkExtension;
XWalkBrowserMainPartsAndroid::XWalkBrowserMainPartsAndroid(
const content::MainFunctionParams& parameters)
: XWalkBrowserMainParts(parameters) {
}
XWalkBrowserMainPartsAndroid::~XWalkBrowserMainPartsAndroid() {
}
void XWalkBrowserMainPartsAndroid::PreEarlyInitialization() {
net::NetworkChangeNotifier::SetFactory(
new net::NetworkChangeNotifierFactoryAndroid());
// As Crosswalk uses in-process mode, that's easier than Chromium
// to reach the default limit(1024) of open files per process on
// Android. So increase the limit to 4096 explicitly.
base::SetFdLimit(4096);
// Initialize the Compositor.
content::Compositor::Initialize();
XWalkBrowserMainParts::PreEarlyInitialization();
}
void XWalkBrowserMainPartsAndroid::PreMainMessageLoopStart() {
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
// Disable ExtensionProcess for Android.
// External extensions will run in the BrowserProcess (in process mode).
command_line->AppendSwitch(switches::kXWalkDisableExtensionProcess);
// Only force to enable WebGL for Android for IA platforms because
// we've tested the WebGL conformance test. For other platforms, just
// follow up the behavior defined by Chromium upstream.
#if defined(ARCH_CPU_X86) || defined(ARCH_CPU_X86_64)
command_line->AppendSwitch(switches::kIgnoreGpuBlacklist);
#endif
// Enable experiemntal features like polymer and css animations because
// CrossWalk is testbed of state of art of web technology.
command_line->AppendSwitch(switches::kEnableExperimentalWebPlatformFeatures);
#if defined(ENABLE_WEBRTC)
// Disable HW encoding/decoding acceleration for WebRTC on Android.
// FIXME: Remove these switches for Android when Android OS is removed from
// GPU accelerated_video_decode blacklist or we stop ignoring the GPU
// blacklist.
command_line->AppendSwitch(switches::kDisableWebRtcHWDecoding);
command_line->AppendSwitch(switches::kDisableWebRtcHWEncoding);
#endif
command_line->AppendSwitch(switches::kEnableViewportMeta);
XWalkBrowserMainParts::PreMainMessageLoopStart();
startup_url_ = GURL();
}
void XWalkBrowserMainPartsAndroid::PostMainMessageLoopStart() {
base::MessageLoopForUI::current()->Start();
}
void XWalkBrowserMainPartsAndroid::PreMainMessageLoopRun() {
net::NetModule::SetResourceProvider(PlatformResourceProvider);
if (parameters_.ui_task) {
parameters_.ui_task->Run();
delete parameters_.ui_task;
run_default_message_loop_ = false;
}
xwalk_runner_->PreMainMessageLoopRun();
extension_service_ = xwalk_runner_->extension_service();
// Prepare the cookie store.
base::FilePath user_data_dir;
if (!PathService::Get(base::DIR_ANDROID_APP_DATA, &user_data_dir)) {
NOTREACHED() << "Failed to get app data directory for Crosswalk";
}
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kXWalkProfileName)) {
base::FilePath profile = user_data_dir.Append(
command_line->GetSwitchValuePath(switches::kXWalkProfileName));
MoveUserDataDirIfNecessary(user_data_dir, profile);
user_data_dir = profile;
}
base::FilePath cookie_store_path = user_data_dir.Append(
FILE_PATH_LITERAL("Cookies"));
scoped_refptr<base::SequencedTaskRunner> background_task_runner =
BrowserThread::GetBlockingPool()->GetSequencedTaskRunner(
BrowserThread::GetBlockingPool()->GetSequenceToken());
content::CookieStoreConfig cookie_config(
cookie_store_path,
content::CookieStoreConfig::RESTORED_SESSION_COOKIES,
NULL, NULL);
cookie_config.client_task_runner =
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
cookie_config.background_task_runner = background_task_runner;
cookie_store_ = content::CreateCookieStore(cookie_config);
cookie_store_->GetCookieMonster()->SetPersistSessionCookies(true);
SetCookieMonsterOnNetworkStackInit(cookie_store_->GetCookieMonster());
}
void XWalkBrowserMainPartsAndroid::PostMainMessageLoopRun() {
XWalkBrowserMainParts::PostMainMessageLoopRun();
base::MessageLoopForUI::current()->Start();
}
void XWalkBrowserMainPartsAndroid::CreateInternalExtensionsForExtensionThread(
content::RenderProcessHost* host,
extensions::XWalkExtensionVector* extensions) {
// On Android part, the ownership of each extension object will be transferred
// to XWalkExtensionServer after this method is called. It is a rule enforced
// by extension system that XWalkExtensionServer must own the extension
// objects and extension instances.
extensions::XWalkExtensionVector::const_iterator it = extensions_.begin();
for (; it != extensions_.end(); ++it)
extensions->push_back(*it);
}
void XWalkBrowserMainPartsAndroid::RegisterExtension(
scoped_ptr<XWalkExtension> extension) {
// Since the creation of extension object is driven by Java side, and each
// Java extension is backed by a native extension object. However, the Java
// object may be destroyed by Android lifecycle management without destroying
// the native side object. We keep the reference to native extension object
// to make sure we can reuse the native object if Java extension is re-created
// on resuming.
extensions_.push_back(extension.release());
}
XWalkExtension* XWalkBrowserMainPartsAndroid::LookupExtension(
const std::string& name) {
extensions::XWalkExtensionVector::const_iterator it = extensions_.begin();
for (; it != extensions_.end(); ++it) {
XWalkExtension* extension = *it;
if (name == extension->name()) return extension;
}
return NULL;
}
} // namespace xwalk
<commit_msg>Revert "[Android] Enable Experimental WebPlatform Features"<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "xwalk/runtime/browser/xwalk_browser_main_parts_android.h"
#include <string>
#include "base/android/path_utils.h"
#include "base/base_paths_android.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/message_loop/message_loop.h"
#include "base/path_service.h"
#include "base/threading/sequenced_worker_pool.h"
#include "cc/base/switches.h"
#include "content/public/browser/android/compositor.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/cookie_store_factory.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/result_codes.h"
#include "net/android/network_change_notifier_factory_android.h"
#include "net/base/network_change_notifier.h"
#include "net/base/net_module.h"
#include "net/base/net_util.h"
#include "net/cookies/cookie_monster.h"
#include "net/cookies/cookie_store.h"
#include "net/grit/net_resources.h"
#include "ui/base/layout.h"
#include "ui/base/l10n/l10n_util_android.h"
#include "ui/base/resource/resource_bundle.h"
#include "xwalk/extensions/browser/xwalk_extension_service.h"
#include "xwalk/extensions/common/xwalk_extension.h"
#include "xwalk/extensions/common/xwalk_extension_switches.h"
#include "xwalk/runtime/browser/android/cookie_manager.h"
#include "xwalk/runtime/browser/xwalk_runner.h"
#include "xwalk/runtime/common/xwalk_runtime_features.h"
#include "xwalk/runtime/common/xwalk_switches.h"
namespace {
base::StringPiece PlatformResourceProvider(int key) {
if (key == IDR_DIR_HEADER_HTML) {
base::StringPiece html_data =
ui::ResourceBundle::GetSharedInstance().GetRawDataResource(
IDR_DIR_HEADER_HTML);
return html_data;
}
return base::StringPiece();
}
void MoveUserDataDirIfNecessary(const base::FilePath& user_data_dir,
const base::FilePath& profile) {
if (base::DirectoryExists(profile))
return;
if (!base::CreateDirectory(profile))
return;
const char* possible_data_dir_names[] = {
"Cache",
"Cookies",
"Cookies-journal",
"Local Storage",
};
for (int i = 0; i < 4; i++) {
base::FilePath dir = user_data_dir.Append(possible_data_dir_names[i]);
if (base::PathExists(dir)) {
if (!base::Move(dir, profile.Append(possible_data_dir_names[i]))) {
NOTREACHED() << "Failed to import previous user data: "
<< possible_data_dir_names[i];
}
}
}
}
} // namespace
namespace xwalk {
using content::BrowserThread;
using extensions::XWalkExtension;
XWalkBrowserMainPartsAndroid::XWalkBrowserMainPartsAndroid(
const content::MainFunctionParams& parameters)
: XWalkBrowserMainParts(parameters) {
}
XWalkBrowserMainPartsAndroid::~XWalkBrowserMainPartsAndroid() {
}
void XWalkBrowserMainPartsAndroid::PreEarlyInitialization() {
net::NetworkChangeNotifier::SetFactory(
new net::NetworkChangeNotifierFactoryAndroid());
// As Crosswalk uses in-process mode, that's easier than Chromium
// to reach the default limit(1024) of open files per process on
// Android. So increase the limit to 4096 explicitly.
base::SetFdLimit(4096);
// Initialize the Compositor.
content::Compositor::Initialize();
XWalkBrowserMainParts::PreEarlyInitialization();
}
void XWalkBrowserMainPartsAndroid::PreMainMessageLoopStart() {
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
// Disable ExtensionProcess for Android.
// External extensions will run in the BrowserProcess (in process mode).
command_line->AppendSwitch(switches::kXWalkDisableExtensionProcess);
// Only force to enable WebGL for Android for IA platforms because
// we've tested the WebGL conformance test. For other platforms, just
// follow up the behavior defined by Chromium upstream.
#if defined(ARCH_CPU_X86) || defined(ARCH_CPU_X86_64)
command_line->AppendSwitch(switches::kIgnoreGpuBlacklist);
#endif
#if defined(ENABLE_WEBRTC)
// Disable HW encoding/decoding acceleration for WebRTC on Android.
// FIXME: Remove these switches for Android when Android OS is removed from
// GPU accelerated_video_decode blacklist or we stop ignoring the GPU
// blacklist.
command_line->AppendSwitch(switches::kDisableWebRtcHWDecoding);
command_line->AppendSwitch(switches::kDisableWebRtcHWEncoding);
#endif
command_line->AppendSwitch(switches::kEnableViewportMeta);
XWalkBrowserMainParts::PreMainMessageLoopStart();
startup_url_ = GURL();
}
void XWalkBrowserMainPartsAndroid::PostMainMessageLoopStart() {
base::MessageLoopForUI::current()->Start();
}
void XWalkBrowserMainPartsAndroid::PreMainMessageLoopRun() {
net::NetModule::SetResourceProvider(PlatformResourceProvider);
if (parameters_.ui_task) {
parameters_.ui_task->Run();
delete parameters_.ui_task;
run_default_message_loop_ = false;
}
xwalk_runner_->PreMainMessageLoopRun();
extension_service_ = xwalk_runner_->extension_service();
// Prepare the cookie store.
base::FilePath user_data_dir;
if (!PathService::Get(base::DIR_ANDROID_APP_DATA, &user_data_dir)) {
NOTREACHED() << "Failed to get app data directory for Crosswalk";
}
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kXWalkProfileName)) {
base::FilePath profile = user_data_dir.Append(
command_line->GetSwitchValuePath(switches::kXWalkProfileName));
MoveUserDataDirIfNecessary(user_data_dir, profile);
user_data_dir = profile;
}
base::FilePath cookie_store_path = user_data_dir.Append(
FILE_PATH_LITERAL("Cookies"));
scoped_refptr<base::SequencedTaskRunner> background_task_runner =
BrowserThread::GetBlockingPool()->GetSequencedTaskRunner(
BrowserThread::GetBlockingPool()->GetSequenceToken());
content::CookieStoreConfig cookie_config(
cookie_store_path,
content::CookieStoreConfig::RESTORED_SESSION_COOKIES,
NULL, NULL);
cookie_config.client_task_runner =
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO);
cookie_config.background_task_runner = background_task_runner;
cookie_store_ = content::CreateCookieStore(cookie_config);
cookie_store_->GetCookieMonster()->SetPersistSessionCookies(true);
SetCookieMonsterOnNetworkStackInit(cookie_store_->GetCookieMonster());
}
void XWalkBrowserMainPartsAndroid::PostMainMessageLoopRun() {
XWalkBrowserMainParts::PostMainMessageLoopRun();
base::MessageLoopForUI::current()->Start();
}
void XWalkBrowserMainPartsAndroid::CreateInternalExtensionsForExtensionThread(
content::RenderProcessHost* host,
extensions::XWalkExtensionVector* extensions) {
// On Android part, the ownership of each extension object will be transferred
// to XWalkExtensionServer after this method is called. It is a rule enforced
// by extension system that XWalkExtensionServer must own the extension
// objects and extension instances.
extensions::XWalkExtensionVector::const_iterator it = extensions_.begin();
for (; it != extensions_.end(); ++it)
extensions->push_back(*it);
}
void XWalkBrowserMainPartsAndroid::RegisterExtension(
scoped_ptr<XWalkExtension> extension) {
// Since the creation of extension object is driven by Java side, and each
// Java extension is backed by a native extension object. However, the Java
// object may be destroyed by Android lifecycle management without destroying
// the native side object. We keep the reference to native extension object
// to make sure we can reuse the native object if Java extension is re-created
// on resuming.
extensions_.push_back(extension.release());
}
XWalkExtension* XWalkBrowserMainPartsAndroid::LookupExtension(
const std::string& name) {
extensions::XWalkExtensionVector::const_iterator it = extensions_.begin();
for (; it != extensions_.end(); ++it) {
XWalkExtension* extension = *it;
if (name == extension->name()) return extension;
}
return NULL;
}
} // namespace xwalk
<|endoftext|>
|
<commit_before><commit_msg>Prediction: refactor lane_l<commit_after><|endoftext|>
|
<commit_before>#include <flexcore/scheduler/cyclecontrol.hpp>
#include <stdexcept>
#include <algorithm>
namespace fc
{
namespace thread
{
using clock = master_clock<std::centi>;
constexpr wall_clock::steady::duration cycle_control::min_tick_length;
constexpr virtual_clock::steady::duration cycle_control::fast_tick;
constexpr virtual_clock::steady::duration cycle_control::medium_tick;
constexpr virtual_clock::steady::duration cycle_control::slow_tick;
cycle_control::cycle_control(std::unique_ptr<scheduler> scheduler,
const std::shared_ptr<main_loop>& loop)
: cycle_control(std::move(scheduler), [this](auto& task)
{
return store_exception(task);
},
loop
)
{
}
void cycle_control::start()
{
assert(!running);
keep_working.store(true);
running = true;
// give the main thread some actual work to do (execute infinite main loop)
main_loop_thread = std::thread{
[&, this](){
while(keep_working.load())
main_loop_->loop_body([this](){ work(); });
}
};
}
void cycle_control::stop()
{
keep_working.store(false);
if (main_loop_thread.joinable())
main_loop_thread.join();
// wait for scheduled tasks to finish
auto wait_or_throw = [this](auto& task_vector)
{
for (auto& t : task_vector.tasks)
if (!t.wait_until_done(slow_tick))
timeout_callback(t);
};
wait_or_throw(tasks_fast);
wait_or_throw(tasks_medium);
wait_or_throw(tasks_slow);
running = false;
}
bool cycle_control::store_exception(periodic_task&)
{
auto ep = std::make_exception_ptr(out_of_time_exception());
std::lock_guard<std::mutex> lock(task_exception_mutex);
task_exceptions.push_back(ep);
return false;
}
void cycle_control::work()
{
auto now = virtual_clock::steady::now().time_since_epoch();
auto run_if_due = [this, now](auto& task_vector)
{
if (now % task_vector.tick == virtual_clock::duration::zero())
if (!run_periodic_tasks(task_vector))
return false;
return true;
};
clock::advance();
if (!run_if_due(tasks_fast)) return;
if (!run_if_due(tasks_medium)) return;
if (!run_if_due(tasks_slow)) return;
}
void cycle_control::wait_for_current_tasks()
{
auto now = virtual_clock::steady::now().time_since_epoch();
auto wait_for_tasks = [this, now](auto& task_vector)
{
if (now % task_vector.tick == virtual_clock::duration::zero())
{
for (auto& task : task_vector.tasks)
if (!task.wait_until_done(task_vector.tick))
{
if (!timeout_callback(task))
{
keep_working.store(false);
return false;
}
}
}
return true;
};
if (!wait_for_tasks(tasks_slow)) return;
if (!wait_for_tasks(tasks_medium)) return;
if (!wait_for_tasks(tasks_fast)) return;
}
cycle_control::~cycle_control()
{
stop();
}
bool cycle_control::run_periodic_tasks(tick_task_pair& tasks)
{
assert(tasks.done_tasks.empty());
for (auto& task : tasks.tasks)
{
if (!task.done())
{
if (!timeout_callback(task))
{
keep_working.store(false);
return false;
}
if (!task.done())
continue;
}
tasks.done_tasks.emplace_back(task);
}
for (auto& task_ref : tasks.done_tasks)
{
periodic_task& task = task_ref.get();
assert(task.done());
task.set_work_to_do(true);
task.send_switch_tick();
}
for (auto& task_ref : tasks.done_tasks)
{
periodic_task& task = task_ref.get();
scheduler_->add_task([&task] { task(); });
}
tasks.done_tasks.clear();
return true;
}
void cycle_control::add_task(periodic_task task, virtual_clock::duration tick_rate)
{
if (running)
throw std::runtime_error{"Worker threads are already running"};
if (tick_rate == slow_tick)
tasks_slow.tasks.emplace_back(std::move(task));
else if (tick_rate == medium_tick)
tasks_medium.tasks.emplace_back(std::move(task));
else if (tick_rate == fast_tick)
tasks_fast.tasks.emplace_back(std::move(task));
else
throw std::invalid_argument{"Unsupported tick_rate"};
}
std::exception_ptr cycle_control::last_exception()
{
std::lock_guard<std::mutex> lock(task_exception_mutex);
if(task_exceptions.empty())
return nullptr;
std::exception_ptr except = task_exceptions.back();
task_exceptions.pop_back();
return except;
}
void cycle_control::set_main_loop(const std::shared_ptr<main_loop>& loop)
{
assert(!running);
main_loop_ = loop;
main_loop_->wait_for_current_tasks = [this](){ wait_for_current_tasks(); };
}
void realtime_main_loop::loop_body(const std::function<void(void)>& work)
{
const auto now = wall_clock::steady::now();
work();
std::this_thread::sleep_until(now + cycle_control::min_tick_length);
}
void timewarp_main_loop::loop_body(const std::function<void(void)>& work)
{
const auto now = wall_clock::steady::now();
wait_for_current_tasks();
work();
std::unique_lock<std::mutex> lock(warp_mutex);
warp_signal.wait_until(lock,
now + cycle_control::min_tick_length * warp_factor,
[this, &now]()
{
return wall_clock::steady::now() >= now + cycle_control::min_tick_length * warp_factor;
});
}
void timewarp_main_loop::set_warp_factor(double factor)
{
std::lock_guard<std::mutex> lock(warp_mutex);
warp_factor = factor;
warp_signal.notify_all();
}
void afap_main_loop::loop_body(const std::function<void(void)>& work)
{
wait_for_current_tasks();
work();
}
} /* namespace thread */
} /* namespace fc */
<commit_msg>qualified call to member in lambda<commit_after>#include <flexcore/scheduler/cyclecontrol.hpp>
#include <stdexcept>
#include <algorithm>
namespace fc
{
namespace thread
{
using clock = master_clock<std::centi>;
constexpr wall_clock::steady::duration cycle_control::min_tick_length;
constexpr virtual_clock::steady::duration cycle_control::fast_tick;
constexpr virtual_clock::steady::duration cycle_control::medium_tick;
constexpr virtual_clock::steady::duration cycle_control::slow_tick;
cycle_control::cycle_control(std::unique_ptr<scheduler> scheduler,
const std::shared_ptr<main_loop>& loop)
: cycle_control(std::move(scheduler), [this](auto& task)
{
return this->store_exception(task);
},
loop
)
{
}
void cycle_control::start()
{
assert(!running);
keep_working.store(true);
running = true;
// give the main thread some actual work to do (execute infinite main loop)
main_loop_thread = std::thread{
[&, this](){
while(keep_working.load())
main_loop_->loop_body([this](){ work(); });
}
};
}
void cycle_control::stop()
{
keep_working.store(false);
if (main_loop_thread.joinable())
main_loop_thread.join();
// wait for scheduled tasks to finish
auto wait_or_throw = [this](auto& task_vector)
{
for (auto& t : task_vector.tasks)
if (!t.wait_until_done(slow_tick))
timeout_callback(t);
};
wait_or_throw(tasks_fast);
wait_or_throw(tasks_medium);
wait_or_throw(tasks_slow);
running = false;
}
bool cycle_control::store_exception(periodic_task&)
{
auto ep = std::make_exception_ptr(out_of_time_exception());
std::lock_guard<std::mutex> lock(task_exception_mutex);
task_exceptions.push_back(ep);
return false;
}
void cycle_control::work()
{
auto now = virtual_clock::steady::now().time_since_epoch();
auto run_if_due = [this, now](auto& task_vector)
{
if (now % task_vector.tick == virtual_clock::duration::zero())
if (!run_periodic_tasks(task_vector))
return false;
return true;
};
clock::advance();
if (!run_if_due(tasks_fast)) return;
if (!run_if_due(tasks_medium)) return;
if (!run_if_due(tasks_slow)) return;
}
void cycle_control::wait_for_current_tasks()
{
auto now = virtual_clock::steady::now().time_since_epoch();
auto wait_for_tasks = [this, now](auto& task_vector)
{
if (now % task_vector.tick == virtual_clock::duration::zero())
{
for (auto& task : task_vector.tasks)
if (!task.wait_until_done(task_vector.tick))
{
if (!timeout_callback(task))
{
keep_working.store(false);
return false;
}
}
}
return true;
};
if (!wait_for_tasks(tasks_slow)) return;
if (!wait_for_tasks(tasks_medium)) return;
if (!wait_for_tasks(tasks_fast)) return;
}
cycle_control::~cycle_control()
{
stop();
}
bool cycle_control::run_periodic_tasks(tick_task_pair& tasks)
{
assert(tasks.done_tasks.empty());
for (auto& task : tasks.tasks)
{
if (!task.done())
{
if (!timeout_callback(task))
{
keep_working.store(false);
return false;
}
if (!task.done())
continue;
}
tasks.done_tasks.emplace_back(task);
}
for (auto& task_ref : tasks.done_tasks)
{
periodic_task& task = task_ref.get();
assert(task.done());
task.set_work_to_do(true);
task.send_switch_tick();
}
for (auto& task_ref : tasks.done_tasks)
{
periodic_task& task = task_ref.get();
scheduler_->add_task([&task] { task(); });
}
tasks.done_tasks.clear();
return true;
}
void cycle_control::add_task(periodic_task task, virtual_clock::duration tick_rate)
{
if (running)
throw std::runtime_error{"Worker threads are already running"};
if (tick_rate == slow_tick)
tasks_slow.tasks.emplace_back(std::move(task));
else if (tick_rate == medium_tick)
tasks_medium.tasks.emplace_back(std::move(task));
else if (tick_rate == fast_tick)
tasks_fast.tasks.emplace_back(std::move(task));
else
throw std::invalid_argument{"Unsupported tick_rate"};
}
std::exception_ptr cycle_control::last_exception()
{
std::lock_guard<std::mutex> lock(task_exception_mutex);
if(task_exceptions.empty())
return nullptr;
std::exception_ptr except = task_exceptions.back();
task_exceptions.pop_back();
return except;
}
void cycle_control::set_main_loop(const std::shared_ptr<main_loop>& loop)
{
assert(!running);
main_loop_ = loop;
main_loop_->wait_for_current_tasks = [this](){ wait_for_current_tasks(); };
}
void realtime_main_loop::loop_body(const std::function<void(void)>& work)
{
const auto now = wall_clock::steady::now();
work();
std::this_thread::sleep_until(now + cycle_control::min_tick_length);
}
void timewarp_main_loop::loop_body(const std::function<void(void)>& work)
{
const auto now = wall_clock::steady::now();
wait_for_current_tasks();
work();
std::unique_lock<std::mutex> lock(warp_mutex);
warp_signal.wait_until(lock,
now + cycle_control::min_tick_length * warp_factor,
[this, &now]()
{
return wall_clock::steady::now() >= now + cycle_control::min_tick_length * warp_factor;
});
}
void timewarp_main_loop::set_warp_factor(double factor)
{
std::lock_guard<std::mutex> lock(warp_mutex);
warp_factor = factor;
warp_signal.notify_all();
}
void afap_main_loop::loop_body(const std::function<void(void)>& work)
{
wait_for_current_tasks();
work();
}
} /* namespace thread */
} /* namespace fc */
<|endoftext|>
|
<commit_before>/* * This file is part of m-keyboard *
*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* Contact: Nokia Corporation (directui@nokia.com)
*
* 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 "mkeyboardsettings.h"
#include "mkeyboardsettingswidget.h"
#include "keyboarddata.h"
#include <QObject>
#include <QGraphicsWidget>
#include <QDir>
#include <QFileInfo>
#include <QDebug>
namespace {
const QString SettingsImErrorCorrection("/meegotouch/inputmethods/virtualkeyboard/correctionenabled");
const QString SettingsImCorrectionSpace("/meegotouch/inputmethods/virtualkeyboard/correctwithspace");
const QString InputMethodLayouts("/meegotouch/inputmethods/virtualkeyboard/layouts");
const QString VKBConfigurationPath("/usr/share/meegotouch/virtual-keyboard/layouts/");
const QString VKBLayoutsFilterRule("*.xml");
const QString VKBLayoutsIgnoreRules("number|test|customer|default"); // use as regexp to ignore number, test, customer and default layouts
const QString ChineseVKBConfigurationPath("/usr/share/meegotouch/virtual-keyboard/layouts/chinese");
};
MKeyboardSettings::MKeyboardSettings()
: keyboardErrorCorrectionConf(SettingsImErrorCorrection),
keyboardCorrectionSpaceConf(SettingsImCorrectionSpace),
selectedKeyboardsConf(InputMethodLayouts)
{
readAvailableKeyboards();
connect(&keyboardErrorCorrectionConf, SIGNAL(valueChanged()),
this, SIGNAL(errorCorrectionChanged()));
connect(&keyboardCorrectionSpaceConf, SIGNAL(valueChanged()),
this, SIGNAL(correctionSpaceChanged()));
connect(&selectedKeyboardsConf, SIGNAL(valueChanged()),
this, SIGNAL(selectedKeyboardsChanged()));
}
MKeyboardSettings::~MKeyboardSettings()
{
}
QGraphicsWidget *MKeyboardSettings::createContentWidget(QGraphicsWidget *parent)
{
// the pointer of returned QGraphicsWidget is owned by the caller,
// so we just always create a new containerWidget.
return new MKeyboardSettingsWidget(this, parent);
}
QString MKeyboardSettings::title()
{
//% "Virtual keyboards"
return qtTrId("qtn_txts_virtual_keyboards");;
}
QString MKeyboardSettings::icon()
{
return "";
}
void MKeyboardSettings::readAvailableKeyboards()
{
availableKeyboardInfos.clear();
QList<QDir> dirs;
dirs << QDir(VKBConfigurationPath, VKBLayoutsFilterRule);
// TO BE REMOVED
// Add Chinese input method layout directories here to allow our setting
// could manage Chinese IM layouts. This is a workaround, will be removed later.
dirs << QDir(ChineseVKBConfigurationPath, VKBLayoutsFilterRule);
QRegExp ignoreExp(VKBLayoutsIgnoreRules, Qt::CaseInsensitive);
foreach (const QDir &dir, dirs) {
// available keyboard layouts are determined by xml layouts that can be found
foreach (const QFileInfo &keyboardFileInfo, dir.entryInfoList()) {
if (keyboardFileInfo.fileName().contains(ignoreExp))
continue;
KeyboardData keyboard;
if (keyboard.loadNokiaKeyboard(keyboardFileInfo.filePath())) {
if (keyboard.layoutFile().isEmpty()
|| keyboard.language().isEmpty()
|| keyboard.title().isEmpty())
continue;
bool duplicated = false;
foreach (const KeyboardInfo &info, availableKeyboardInfos) {
if (info.layoutFile == keyboard.layoutFile()
|| info.title == keyboard.title()) {
// strip duplicated layout which has the same layout/title
duplicated = true;
break;
}
}
if (!duplicated) {
KeyboardInfo keyboardInfo;
// strip the path, only save the layout file name.
keyboardInfo.layoutFile = QFileInfo(keyboard.layoutFile()).fileName();
keyboardInfo.title = keyboard.title();
availableKeyboardInfos.append(keyboardInfo);
}
}
}
}
}
QMap<QString, QString> MKeyboardSettings::availableKeyboards() const
{
QMap<QString, QString> keyboards;
foreach (const KeyboardInfo &keyboardInfo, availableKeyboardInfos) {
keyboards.insert(keyboardInfo.layoutFile, keyboardInfo.title);
}
return keyboards;
}
QMap<QString, QString> MKeyboardSettings::selectedKeyboards() const
{
QMap<QString, QString> keyboards;
foreach (const QString layoutFile, selectedKeyboardsConf.value().toStringList()) {
keyboards.insert(layoutFile, keyboardTitle(layoutFile));
}
return keyboards;
}
void MKeyboardSettings::setSelectedKeyboards(const QStringList &keyboardLayouts)
{
selectedKeyboardsConf.set(keyboardLayouts);
}
QString MKeyboardSettings::keyboardTitle(const QString &layoutFile) const
{
QString title;
foreach (const KeyboardInfo &keyboardInfo, availableKeyboardInfos) {
if (keyboardInfo.layoutFile == layoutFile) {
title = keyboardInfo.title;
break;
}
}
return title;
}
QString MKeyboardSettings::keyboardLayoutFile(const QString &title) const
{
QString layoutFile;
foreach (const KeyboardInfo &keyboardInfo, availableKeyboardInfos) {
if (keyboardInfo.title == title) {
layoutFile = keyboardInfo.layoutFile;
break;
}
}
return layoutFile;
}
bool MKeyboardSettings::errorCorrection() const
{
return keyboardErrorCorrectionConf.value().toBool();
}
void MKeyboardSettings::setErrorCorrection(bool enabled)
{
keyboardErrorCorrectionConf.set(enabled);
}
bool MKeyboardSettings::correctionSpace() const
{
return keyboardCorrectionSpaceConf.value().toBool();
}
void MKeyboardSettings::setCorrectionSpace(bool enabled)
{
keyboardCorrectionSpaceConf.set(enabled);
}
<commit_msg>Fixes: NB#239442 - [TASK] Load VKB layouts dynamically from user folder<commit_after>/* * This file is part of m-keyboard *
*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* Contact: Nokia Corporation (directui@nokia.com)
*
* 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 "mkeyboardsettings.h"
#include "mkeyboardsettingswidget.h"
#include "keyboarddata.h"
#include <QObject>
#include <QGraphicsWidget>
#include <QDir>
#include <QFileInfo>
#include <QDebug>
namespace {
const QString SettingsImErrorCorrection("/meegotouch/inputmethods/virtualkeyboard/correctionenabled");
const QString SettingsImCorrectionSpace("/meegotouch/inputmethods/virtualkeyboard/correctwithspace");
const QString InputMethodLayouts("/meegotouch/inputmethods/virtualkeyboard/layouts");
const QString VKBConfigurationPath("/usr/share/meegotouch/virtual-keyboard/layouts/");
const QString VKBLayoutsFilterRule("*.xml");
const QString VKBLayoutsIgnoreRules("number|test|customer|default"); // use as regexp to ignore number, test, customer and default layouts
const QString ChineseVKBConfigurationPath("/usr/share/meegotouch/virtual-keyboard/layouts/chinese");
const QString VKBUserLayoutPath(".config/meego-keyboard/layouts/"); // relative to home dir
};
MKeyboardSettings::MKeyboardSettings()
: keyboardErrorCorrectionConf(SettingsImErrorCorrection),
keyboardCorrectionSpaceConf(SettingsImCorrectionSpace),
selectedKeyboardsConf(InputMethodLayouts)
{
readAvailableKeyboards();
connect(&keyboardErrorCorrectionConf, SIGNAL(valueChanged()),
this, SIGNAL(errorCorrectionChanged()));
connect(&keyboardCorrectionSpaceConf, SIGNAL(valueChanged()),
this, SIGNAL(correctionSpaceChanged()));
connect(&selectedKeyboardsConf, SIGNAL(valueChanged()),
this, SIGNAL(selectedKeyboardsChanged()));
}
MKeyboardSettings::~MKeyboardSettings()
{
}
QGraphicsWidget *MKeyboardSettings::createContentWidget(QGraphicsWidget *parent)
{
// the pointer of returned QGraphicsWidget is owned by the caller,
// so we just always create a new containerWidget.
return new MKeyboardSettingsWidget(this, parent);
}
QString MKeyboardSettings::title()
{
//% "Virtual keyboards"
return qtTrId("qtn_txts_virtual_keyboards");;
}
QString MKeyboardSettings::icon()
{
return "";
}
void MKeyboardSettings::readAvailableKeyboards()
{
availableKeyboardInfos.clear();
QList<QDir> dirs;
dirs << QDir(VKBConfigurationPath, VKBLayoutsFilterRule);
// TO BE REMOVED
// Add Chinese input method layout directories here to allow our setting
// could manage Chinese IM layouts. This is a workaround, will be removed later.
dirs << QDir(ChineseVKBConfigurationPath, VKBLayoutsFilterRule);
dirs << QDir(QDir::homePath() + QDir::separator() + VKBUserLayoutPath, VKBLayoutsFilterRule);
QRegExp ignoreExp(VKBLayoutsIgnoreRules, Qt::CaseInsensitive);
foreach (const QDir &dir, dirs) {
// available keyboard layouts are determined by xml layouts that can be found
foreach (const QFileInfo &keyboardFileInfo, dir.entryInfoList()) {
if (keyboardFileInfo.fileName().contains(ignoreExp))
continue;
KeyboardData keyboard;
if (keyboard.loadNokiaKeyboard(keyboardFileInfo.filePath())) {
if (keyboard.layoutFile().isEmpty()
|| keyboard.language().isEmpty()
|| keyboard.title().isEmpty())
continue;
bool duplicated = false;
foreach (const KeyboardInfo &info, availableKeyboardInfos) {
if (info.layoutFile == keyboard.layoutFile()
|| info.title == keyboard.title()) {
// strip duplicated layout which has the same layout/title
duplicated = true;
break;
}
}
if (!duplicated) {
KeyboardInfo keyboardInfo;
// strip the path, only save the layout file name.
keyboardInfo.layoutFile = QFileInfo(keyboard.layoutFile()).fileName();
keyboardInfo.title = keyboard.title();
availableKeyboardInfos.append(keyboardInfo);
}
}
}
}
}
QMap<QString, QString> MKeyboardSettings::availableKeyboards() const
{
QMap<QString, QString> keyboards;
foreach (const KeyboardInfo &keyboardInfo, availableKeyboardInfos) {
keyboards.insert(keyboardInfo.layoutFile, keyboardInfo.title);
}
return keyboards;
}
QMap<QString, QString> MKeyboardSettings::selectedKeyboards() const
{
QMap<QString, QString> keyboards;
foreach (const QString layoutFile, selectedKeyboardsConf.value().toStringList()) {
keyboards.insert(layoutFile, keyboardTitle(layoutFile));
}
return keyboards;
}
void MKeyboardSettings::setSelectedKeyboards(const QStringList &keyboardLayouts)
{
selectedKeyboardsConf.set(keyboardLayouts);
}
QString MKeyboardSettings::keyboardTitle(const QString &layoutFile) const
{
QString title;
foreach (const KeyboardInfo &keyboardInfo, availableKeyboardInfos) {
if (keyboardInfo.layoutFile == layoutFile) {
title = keyboardInfo.title;
break;
}
}
return title;
}
QString MKeyboardSettings::keyboardLayoutFile(const QString &title) const
{
QString layoutFile;
foreach (const KeyboardInfo &keyboardInfo, availableKeyboardInfos) {
if (keyboardInfo.title == title) {
layoutFile = keyboardInfo.layoutFile;
break;
}
}
return layoutFile;
}
bool MKeyboardSettings::errorCorrection() const
{
return keyboardErrorCorrectionConf.value().toBool();
}
void MKeyboardSettings::setErrorCorrection(bool enabled)
{
keyboardErrorCorrectionConf.set(enabled);
}
bool MKeyboardSettings::correctionSpace() const
{
return keyboardCorrectionSpaceConf.value().toBool();
}
void MKeyboardSettings::setCorrectionSpace(bool enabled)
{
keyboardCorrectionSpaceConf.set(enabled);
}
<|endoftext|>
|
<commit_before>/*
* SessionSVN.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionSVN.hpp"
#include <core/system/Environment.hpp>
#include <core/system/Process.hpp>
#include <core/system/ShellUtils.hpp>
#include <session/projects/SessionProjects.hpp>
#include <session/SessionOptions.hpp>
using namespace core;
using namespace core::shell_utils;
namespace session {
namespace modules {
namespace svn {
namespace {
system::ProcessOptions procOptions()
{
core::system::ProcessOptions options;
// detach the session so there is no terminal
#ifndef _WIN32
options.detachSession = true;
#endif
// get current environment for modification prior to passing to child
core::system::Options childEnv;
core::system::environment(&childEnv);
// TODO: Add Subversion bin dir to path if necessary
// add postback directory to PATH
FilePath postbackDir = session::options().rpostbackPath().parent();
core::system::addToPath(&childEnv, postbackDir.absolutePath());
options.workingDir = projects::projectContext().directory();
// on windows set HOME to USERPROFILE
#ifdef _WIN32
std::string userProfile = core::system::getenv(childEnv, "USERPROFILE");
core::system::setenv(&childEnv, "HOME", userProfile);
#endif
// set custom environment
options.environment = childEnv;
return options;
}
} // namespace
bool isSvnInstalled()
{
system::ProcessResult result;
Error error = system::runProgram("svn",
ShellArgs() << "help",
"",
procOptions(),
&result);
if (error)
{
LOG_ERROR(error);
return false;
}
return result.exitStatus == EXIT_SUCCESS;
}
bool isSvnDirectory(const core::FilePath& workingDir)
{
if (workingDir.empty())
return false;
system::ProcessOptions options = procOptions();
options.workingDir = workingDir;
system::ProcessResult result;
Error error = system::runProgram("svn",
ShellArgs() << "info",
"",
options,
&result);
if (error)
return false;
return result.exitStatus == EXIT_SUCCESS;
}
Error initialize()
{
return Success();
}
Error initializeSvn(const core::FilePath& workingDir)
{
return Success();
}
} // namespace svn
} // namespace modules
} //namespace session
<commit_msg>fix gcc 4.2 build break<commit_after>/*
* SessionSVN.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionSVN.hpp"
#include <core/system/Environment.hpp>
#include <core/system/Process.hpp>
#include <core/system/ShellUtils.hpp>
#include <session/projects/SessionProjects.hpp>
#include <session/SessionOptions.hpp>
using namespace core;
using namespace core::shell_utils;
namespace session {
namespace modules {
namespace svn {
namespace {
core::system::ProcessOptions procOptions()
{
core::system::ProcessOptions options;
// detach the session so there is no terminal
#ifndef _WIN32
options.detachSession = true;
#endif
// get current environment for modification prior to passing to child
core::system::Options childEnv;
core::system::environment(&childEnv);
// TODO: Add Subversion bin dir to path if necessary
// add postback directory to PATH
FilePath postbackDir = session::options().rpostbackPath().parent();
core::system::addToPath(&childEnv, postbackDir.absolutePath());
options.workingDir = projects::projectContext().directory();
// on windows set HOME to USERPROFILE
#ifdef _WIN32
std::string userProfile = core::system::getenv(childEnv, "USERPROFILE");
core::system::setenv(&childEnv, "HOME", userProfile);
#endif
// set custom environment
options.environment = childEnv;
return options;
}
} // namespace
bool isSvnInstalled()
{
core::system::ProcessResult result;
Error error = core::system::runProgram("svn",
ShellArgs() << "help",
"",
procOptions(),
&result);
if (error)
{
LOG_ERROR(error);
return false;
}
return result.exitStatus == EXIT_SUCCESS;
}
bool isSvnDirectory(const core::FilePath& workingDir)
{
if (workingDir.empty())
return false;
core::system::ProcessOptions options = procOptions();
options.workingDir = workingDir;
core::system::ProcessResult result;
Error error = core::system::runProgram("svn",
ShellArgs() << "info",
"",
options,
&result);
if (error)
return false;
return result.exitStatus == EXIT_SUCCESS;
}
Error initialize()
{
return Success();
}
Error initializeSvn(const core::FilePath& workingDir)
{
return Success();
}
} // namespace svn
} // namespace modules
} //namespace session
<|endoftext|>
|
<commit_before>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010-2015 Belledonne Communications SARL, All rights reserved.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <sys/types.h>
#include <dirent.h>
#include "pushnotificationservice.hh"
#include "pushnotificationclient.hh"
#include "common.hh"
#include <boost/bind.hpp>
#include <sstream>
static const char *APN_DEV_ADDRESS = "gateway.sandbox.push.apple.com";
static const char *APN_PROD_ADDRESS = "gateway.push.apple.com";
static const char *APN_PORT = "2195";
static const char *GPN_ADDRESS = "android.googleapis.com";
static const char *GPN_PORT = "443";
static const char *WPPN_PORT = "80";
using namespace ::std;
namespace ssl = boost::asio::ssl;
int PushNotificationService::sendRequest(const std::shared_ptr<PushNotificationRequest> &pn) {
std::shared_ptr<PushNotificationClient> client=mClients[pn->getAppIdentifier()];
if (client==0){
if (pn->getType().compare(string("wp"))==0) {
string wpClient = pn->getAppIdentifier();
std::shared_ptr<ssl::context> ctx(new ssl::context(mIOService, ssl::context::sslv23_client));
boost::system::error_code err;
ctx->set_options(ssl::context::default_workarounds, err);
ctx->set_verify_mode(ssl::context::verify_none);
mClients[wpClient] = std::make_shared<PushNotificationClient>(wpClient, this, ctx, pn->getAppIdentifier(), WPPN_PORT, mMaxQueueSize, false);
LOGD("Creating PN client for %s",pn->getAppIdentifier().c_str());
client = mClients[wpClient];
} else {
LOGE("No push notification certificate for client %s",pn->getAppIdentifier().c_str());
return -1;
}
}
//this method is called from flexisip main thread, while service is running in its own thread.
//To avoid using dedicated mutex, use the server post() method to delegate the processing of the push notification to the service thread.
mIOService.post(std::bind(&PushNotificationClient::sendRequest,client,pn));
return 0;
}
void PushNotificationService::start() {
if (mThread && !mThread->joinable()) {
delete mThread;
mThread = NULL;
}
if (mThread == NULL) {
LOGD("Start PushNotificationService");
mHaveToStop = false;
mThread = new thread(&PushNotificationService::run, this);
}
}
void PushNotificationService::stop() {
if (mThread != NULL) {
LOGD("Stopping PushNotificationService");
mHaveToStop = true;
mIOService.stop();
if (mThread->joinable()) {
mThread->join();
}
delete mThread;
mThread = NULL;
}
}
void PushNotificationService::waitEnd() {
if (mThread != NULL) {
LOGD("Waiting for PushNotificationService to end");
bool finished = false;
while (!finished) {
finished = true;
map<string, std::shared_ptr<PushNotificationClient> >::const_iterator it;
for (it = mClients.begin(); it != mClients.end(); ++it) {
if (!it->second->isIdle()) {
finished = false;
break;
}
}
}
usleep(100000); // avoid eating all cpu for nothing
}
}
void PushNotificationService::setupErrorClient(){
// Error client
std::shared_ptr<ssl::context> ctx(new ssl::context(mIOService, ssl::context::sslv23_client));
boost::system::error_code err;
ctx->set_options(ssl::context::default_workarounds, err);
ctx->set_verify_mode(ssl::context::verify_none);
mClients["error"]=std::make_shared<PushNotificationClient>("error", this, ctx, "127.0.0.1", "1", mMaxQueueSize, false);
}
void PushNotificationService::setupGenericClient(const url_t *url){
std::shared_ptr<ssl::context> ctx(new ssl::context(mIOService, ssl::context::sslv23_client));
boost::system::error_code err;
ctx->set_options(ssl::context::default_workarounds, err);
ctx->set_verify_mode(ssl::context::verify_none);
mClients["generic"]=std::make_shared<PushNotificationClient>("generic", this, ctx, url->url_host, url_port(url), mMaxQueueSize, false);
}
void PushNotificationService::setupiOSClient(const std::string &certdir, const std::string &cafile) {
struct dirent *dirent;
DIR *dirp;
dirp=opendir(certdir.c_str());
if (dirp==NULL){
LOGE("Could not open push notification certificates directory (%s): %s",certdir.c_str(),strerror(errno));
return;
}
SLOGD << "Searching push notification client on dir [" << certdir << "]";
while(true){
errno = 0;
if((dirent=readdir(dirp))==NULL) {
if(errno) SLOGE << "Cannot read dir [" << certdir << "] because [" << strerror(errno) << "]";
break;
}
string cert=string(dirent->d_name);
if(cert.compare(string(".")) == 0 || cert.compare(string("..")) == 0) continue;
string certpath= string(certdir)+"/"+cert;
std::shared_ptr<ssl::context> context(new ssl::context(mIOService, ssl::context::sslv23_client));
boost::system::error_code error;
context->set_options(ssl::context::default_workarounds, error);
context->set_password_callback(bind(&PushNotificationService::handle_password_callback, this, _1, _2));
if (!cafile.empty()) {
context->set_verify_mode(ssl::context::verify_peer);
#if BOOST_VERSION >= 104800
context->set_verify_callback(bind(&PushNotificationService::handle_verify_callback, this, _1, _2));
#endif
context->load_verify_file(cafile, error);
if (error) {
LOGE("load_verify_file: %s",error.message().c_str());
continue;
}
} else {
context->set_verify_mode(ssl::context::verify_none);
}
context->add_verify_path("/etc/ssl/certs");
if (!cert.empty()) {
context->use_certificate_file(certpath, ssl::context::file_format::pem, error);
if (error) {
LOGE("use_certificate_file %s: %s",certpath.c_str(), error.message().c_str());
continue;
}
}
string key=certpath;
if (!key.empty()) {
context->use_private_key_file(key, ssl::context::file_format::pem, error);
if (error) {
LOGE("use_private_key_file %s: %s", certpath.c_str(), error.message().c_str());
continue;
}
}
string certName = cert.substr(0, cert.size() - 4); // Remove .pem at the end of cert
const char *apn_server;
if (certName.find(".dev")!=string::npos)
apn_server=APN_DEV_ADDRESS;
else apn_server=APN_PROD_ADDRESS;
mClients[certName]=std::make_shared<PushNotificationClient>(cert, this, context, apn_server, APN_PORT, mMaxQueueSize, true);
SLOGD << "Adding ios push notification client [" << certName << "]";
}
closedir(dirp);
}
void PushNotificationService::setupAndroidClient(const std::map<std::string, std::string> googleKeys) {
map<string, string>::const_iterator it;
for (it = googleKeys.begin(); it != googleKeys.end(); ++it) {
string android_app_id = it->first;
std::shared_ptr<ssl::context> ctx(new ssl::context(mIOService, ssl::context::sslv23_client));
boost::system::error_code err;
ctx->set_options(ssl::context::default_workarounds, err);
ctx->set_verify_mode(ssl::context::verify_none);
mClients[android_app_id]=std::make_shared<PushNotificationClient>("google", this, ctx, GPN_ADDRESS, GPN_PORT, mMaxQueueSize, true);
SLOGD << "Adding android push notification client [" << android_app_id << "]";
}
}
PushNotificationService::PushNotificationService(int maxQueueSize) :
mIOService(), mThread(NULL), mMaxQueueSize(maxQueueSize), mClients(), mCountFailed(NULL), mCountSent(NULL) {
setupErrorClient();
}
PushNotificationService::~PushNotificationService() {
stop();
}
int PushNotificationService::run() {
LOGD("PushNotificationService Start");
boost::asio::io_service::work work(mIOService);
mIOService.run();
LOGD("PushNotificationService End");
return 0;
}
void PushNotificationService::clientEnded() {
}
boost::asio::io_service &PushNotificationService::getService() {
return mIOService;
}
string PushNotificationService::handle_password_callback(size_t max_length, ssl::context_base::password_purpose purpose) const {
return mPassword;
}
#if BOOST_VERSION >= 104800
bool PushNotificationService::handle_verify_callback(bool preverified, ssl::verify_context& ctx) const {
char subject_name[256];
#if not(__GNUC__ == 4 && __GNUC_MINOR__ < 5 )
SLOGD << "Verifying " << [&] () {
X509* cert = X509_STORE_CTX_get_current_cert(ctx.native_handle());
X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 256);
return subject_name;
}();
#else
X509* cert = X509_STORE_CTX_get_current_cert(ctx.native_handle());
X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 256);
SLOGD << "Verifying " << subject_name;
#endif
return preverified;
}
#endif
<commit_msg>pushnotificationservice.cc: only add files with .pem suffix for ios push notifications certificates<commit_after>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010-2015 Belledonne Communications SARL, All rights reserved.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <sys/types.h>
#include <dirent.h>
#include "pushnotificationservice.hh"
#include "pushnotificationclient.hh"
#include "common.hh"
#include <boost/bind.hpp>
#include <sstream>
static const char *APN_DEV_ADDRESS = "gateway.sandbox.push.apple.com";
static const char *APN_PROD_ADDRESS = "gateway.push.apple.com";
static const char *APN_PORT = "2195";
static const char *GPN_ADDRESS = "android.googleapis.com";
static const char *GPN_PORT = "443";
static const char *WPPN_PORT = "80";
using namespace ::std;
namespace ssl = boost::asio::ssl;
int PushNotificationService::sendRequest(const std::shared_ptr<PushNotificationRequest> &pn) {
std::shared_ptr<PushNotificationClient> client=mClients[pn->getAppIdentifier()];
if (client==0){
if (pn->getType().compare(string("wp"))==0) {
string wpClient = pn->getAppIdentifier();
std::shared_ptr<ssl::context> ctx(new ssl::context(mIOService, ssl::context::sslv23_client));
boost::system::error_code err;
ctx->set_options(ssl::context::default_workarounds, err);
ctx->set_verify_mode(ssl::context::verify_none);
mClients[wpClient] = std::make_shared<PushNotificationClient>(wpClient, this, ctx, pn->getAppIdentifier(), WPPN_PORT, mMaxQueueSize, false);
LOGD("Creating PN client for %s",pn->getAppIdentifier().c_str());
client = mClients[wpClient];
} else {
LOGE("No push notification certificate for client %s",pn->getAppIdentifier().c_str());
return -1;
}
}
//this method is called from flexisip main thread, while service is running in its own thread.
//To avoid using dedicated mutex, use the server post() method to delegate the processing of the push notification to the service thread.
mIOService.post(std::bind(&PushNotificationClient::sendRequest,client,pn));
return 0;
}
void PushNotificationService::start() {
if (mThread && !mThread->joinable()) {
delete mThread;
mThread = NULL;
}
if (mThread == NULL) {
LOGD("Start PushNotificationService");
mHaveToStop = false;
mThread = new thread(&PushNotificationService::run, this);
}
}
void PushNotificationService::stop() {
if (mThread != NULL) {
LOGD("Stopping PushNotificationService");
mHaveToStop = true;
mIOService.stop();
if (mThread->joinable()) {
mThread->join();
}
delete mThread;
mThread = NULL;
}
}
void PushNotificationService::waitEnd() {
if (mThread != NULL) {
LOGD("Waiting for PushNotificationService to end");
bool finished = false;
while (!finished) {
finished = true;
map<string, std::shared_ptr<PushNotificationClient> >::const_iterator it;
for (it = mClients.begin(); it != mClients.end(); ++it) {
if (!it->second->isIdle()) {
finished = false;
break;
}
}
}
usleep(100000); // avoid eating all cpu for nothing
}
}
void PushNotificationService::setupErrorClient(){
// Error client
std::shared_ptr<ssl::context> ctx(new ssl::context(mIOService, ssl::context::sslv23_client));
boost::system::error_code err;
ctx->set_options(ssl::context::default_workarounds, err);
ctx->set_verify_mode(ssl::context::verify_none);
mClients["error"]=std::make_shared<PushNotificationClient>("error", this, ctx, "127.0.0.1", "1", mMaxQueueSize, false);
}
void PushNotificationService::setupGenericClient(const url_t *url){
std::shared_ptr<ssl::context> ctx(new ssl::context(mIOService, ssl::context::sslv23_client));
boost::system::error_code err;
ctx->set_options(ssl::context::default_workarounds, err);
ctx->set_verify_mode(ssl::context::verify_none);
mClients["generic"]=std::make_shared<PushNotificationClient>("generic", this, ctx, url->url_host, url_port(url), mMaxQueueSize, false);
}
void PushNotificationService::setupiOSClient(const std::string &certdir, const std::string &cafile) {
struct dirent *dirent;
DIR *dirp;
dirp=opendir(certdir.c_str());
if (dirp==NULL){
LOGE("Could not open push notification certificates directory (%s): %s",certdir.c_str(),strerror(errno));
return;
}
SLOGD << "Searching push notification client on dir [" << certdir << "]";
while(true){
errno = 0;
if((dirent=readdir(dirp))==NULL) {
if(errno) SLOGE << "Cannot read dir [" << certdir << "] because [" << strerror(errno) << "]";
break;
}
string cert=string(dirent->d_name);
//only consider files which end with .pem
if(cert.compare(".") == 0 || cert.compare("..") == 0 || (cert.compare (cert.length() - ".pem".length(), ".pem".length(), ".pem") != 0)) {
continue;
}
string certpath= string(certdir)+"/"+cert;
std::shared_ptr<ssl::context> context(new ssl::context(mIOService, ssl::context::sslv23_client));
boost::system::error_code error;
context->set_options(ssl::context::default_workarounds, error);
context->set_password_callback(bind(&PushNotificationService::handle_password_callback, this, _1, _2));
if (!cafile.empty()) {
context->set_verify_mode(ssl::context::verify_peer);
#if BOOST_VERSION >= 104800
context->set_verify_callback(bind(&PushNotificationService::handle_verify_callback, this, _1, _2));
#endif
context->load_verify_file(cafile, error);
if (error) {
LOGE("load_verify_file: %s",error.message().c_str());
continue;
}
} else {
context->set_verify_mode(ssl::context::verify_none);
}
context->add_verify_path("/etc/ssl/certs");
if (!cert.empty()) {
context->use_certificate_file(certpath, ssl::context::file_format::pem, error);
if (error) {
LOGE("use_certificate_file %s: %s",certpath.c_str(), error.message().c_str());
continue;
}
}
string key=certpath;
if (!key.empty()) {
context->use_private_key_file(key, ssl::context::file_format::pem, error);
if (error) {
LOGE("use_private_key_file %s: %s", certpath.c_str(), error.message().c_str());
continue;
}
}
string certName = cert.substr(0, cert.size() - 4); // Remove .pem at the end of cert
const char *apn_server;
if (certName.find(".dev")!=string::npos)
apn_server=APN_DEV_ADDRESS;
else apn_server=APN_PROD_ADDRESS;
mClients[certName]=std::make_shared<PushNotificationClient>(cert, this, context, apn_server, APN_PORT, mMaxQueueSize, true);
SLOGD << "Adding ios push notification client [" << certName << "]";
}
closedir(dirp);
}
void PushNotificationService::setupAndroidClient(const std::map<std::string, std::string> googleKeys) {
map<string, string>::const_iterator it;
for (it = googleKeys.begin(); it != googleKeys.end(); ++it) {
string android_app_id = it->first;
std::shared_ptr<ssl::context> ctx(new ssl::context(mIOService, ssl::context::sslv23_client));
boost::system::error_code err;
ctx->set_options(ssl::context::default_workarounds, err);
ctx->set_verify_mode(ssl::context::verify_none);
mClients[android_app_id]=std::make_shared<PushNotificationClient>("google", this, ctx, GPN_ADDRESS, GPN_PORT, mMaxQueueSize, true);
SLOGD << "Adding android push notification client [" << android_app_id << "]";
}
}
PushNotificationService::PushNotificationService(int maxQueueSize) :
mIOService(), mThread(NULL), mMaxQueueSize(maxQueueSize), mClients(), mCountFailed(NULL), mCountSent(NULL) {
setupErrorClient();
}
PushNotificationService::~PushNotificationService() {
stop();
}
int PushNotificationService::run() {
LOGD("PushNotificationService Start");
boost::asio::io_service::work work(mIOService);
mIOService.run();
LOGD("PushNotificationService End");
return 0;
}
void PushNotificationService::clientEnded() {
}
boost::asio::io_service &PushNotificationService::getService() {
return mIOService;
}
string PushNotificationService::handle_password_callback(size_t max_length, ssl::context_base::password_purpose purpose) const {
return mPassword;
}
#if BOOST_VERSION >= 104800
bool PushNotificationService::handle_verify_callback(bool preverified, ssl::verify_context& ctx) const {
char subject_name[256];
#if not(__GNUC__ == 4 && __GNUC_MINOR__ < 5 )
SLOGD << "Verifying " << [&] () {
X509* cert = X509_STORE_CTX_get_current_cert(ctx.native_handle());
X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 256);
return subject_name;
}();
#else
X509* cert = X509_STORE_CTX_get_current_cert(ctx.native_handle());
X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 256);
SLOGD << "Verifying " << subject_name;
#endif
return preverified;
}
#endif
<|endoftext|>
|
<commit_before>#include "common/RhoPort.h"
extern "C" void Init_System();
extern "C" void Init_Network();
extern "C" void Init_SQLite3();
extern "C" void Init_Log();
extern "C" void Init_WebView();
extern "C" void Init_WebView_extension();
extern "C" void Init_Application();
extern "C" void Init_NativeToolbar();
extern "C" void Init_NativeToolbar_extension();
extern "C" void Init_NativeTabbar();
extern "C" void Init_NativeTabbar_extension();
extern "C" void Init_Navbar();
extern "C" void Init_Notification();
extern "C" void Init_RhoFile();
extern "C" void Init_NativeMenuBar();
extern "C" void Init_Led();
extern "C" void Init_Push();
extern "C" void Init_CoreAPI_Extension()
{
Init_System();
Init_Application();
Init_Network();
Init_SQLite3();
Init_Log();
#if defined(OS_MACOSX) || defined(OS_WINDOWS_DESKTOP) || defined(OS_WINCE) || defined(OS_ANDROID)
Init_WebView();
#elif defined(OS_WP8)
Init_WebView_extension();
#endif
#if defined(OS_WINDOWS_DESKTOP) || defined(OS_WINCE) || (defined(OS_MACOSX) && defined(RHODES_EMULATOR)) || defined(OS_ANDROID) || defined(OS_MACOSX)
Init_NativeToolbar();
Init_NativeTabbar();
#elif defined(OS_WP8)
Init_NativeToolbar_extension();
Init_NativeTabbar_extension();
#endif
#if defined(OS_MACOSX) || defined(RHODES_EMULATOR)
Init_Navbar();
#endif
#if defined(OS_WINDOWS_DESKTOP) || defined(RHODES_EMULATOR) || defined(OS_WINCE) || defined(OS_MACOSX) || defined(OS_ANDROID)
Init_Notification();
#endif
#if defined(OS_MACOSX) || defined(OS_ANDROID) || defined(WINDOWS_PLATFORM)
Init_RhoFile();
#endif
#if defined(OS_WINDOWS_DESKTOP) || defined(OS_WINCE) || defined(RHODES_EMULATOR)
Init_NativeMenuBar();
#endif
#if defined(OS_WINCE) || defined(OS_ANDROID)
//Init_Led();
#endif
#if defined(OS_ANDROID) || defined(OS_WINCE) || defined(OS_MACOSX) || defined(OS_WINDOWS_DESKTOP)
Init_Push();
#endif
}
<commit_msg>disabled push for rho_simulator<commit_after>#include "common/RhoPort.h"
extern "C" void Init_System();
extern "C" void Init_Network();
extern "C" void Init_SQLite3();
extern "C" void Init_Log();
extern "C" void Init_WebView();
extern "C" void Init_WebView_extension();
extern "C" void Init_Application();
extern "C" void Init_NativeToolbar();
extern "C" void Init_NativeToolbar_extension();
extern "C" void Init_NativeTabbar();
extern "C" void Init_NativeTabbar_extension();
extern "C" void Init_Navbar();
extern "C" void Init_Notification();
extern "C" void Init_RhoFile();
extern "C" void Init_NativeMenuBar();
extern "C" void Init_Led();
extern "C" void Init_Push();
extern "C" void Init_CoreAPI_Extension()
{
Init_System();
Init_Application();
Init_Network();
Init_SQLite3();
Init_Log();
#if defined(OS_MACOSX) || defined(OS_WINDOWS_DESKTOP) || defined(OS_WINCE) || defined(OS_ANDROID)
Init_WebView();
#elif defined(OS_WP8)
Init_WebView_extension();
#endif
#if defined(OS_WINDOWS_DESKTOP) || defined(OS_WINCE) || (defined(OS_MACOSX) && defined(RHODES_EMULATOR)) || defined(OS_ANDROID) || defined(OS_MACOSX)
Init_NativeToolbar();
Init_NativeTabbar();
#elif defined(OS_WP8)
Init_NativeToolbar_extension();
Init_NativeTabbar_extension();
#endif
#if defined(OS_MACOSX) || defined(RHODES_EMULATOR)
Init_Navbar();
#endif
#if defined(OS_WINDOWS_DESKTOP) || defined(RHODES_EMULATOR) || defined(OS_WINCE) || defined(OS_MACOSX) || defined(OS_ANDROID)
Init_Notification();
#endif
#if defined(OS_MACOSX) || defined(OS_ANDROID) || defined(WINDOWS_PLATFORM)
Init_RhoFile();
#endif
#if defined(OS_WINDOWS_DESKTOP) || defined(OS_WINCE) || defined(RHODES_EMULATOR)
Init_NativeMenuBar();
#endif
#if defined(OS_WINCE) || defined(OS_ANDROID)
//Init_Led();
#endif
#if defined(OS_ANDROID) || defined(OS_WINCE) || defined(OS_MACOSX) || (defined(OS_WINDOWS_DESKTOP) && !defined(RHODES_EMULATOR))
Init_Push();
#endif
}
<|endoftext|>
|
<commit_before>//
// (c) 2014 Raphael Bialon <Raphael.Bialon@hhu.de>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program 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 program. If not, see http://www.gnu.org/licenses/.
//
#include "TbusBaseQueue.h"
#include "TbusQueueDatarateValue.h"
#include "TbusQueueDelayValue.h"
#include "omnetpp.h"
#include <algorithm>
/**
* Set up.
* Instantiates selfMessage
*/
template<class T> TbusBaseQueue<T>::TbusBaseQueue(TbusQueueSelection selection) :
selfMessage(NULL, 0),
queueSelection(selection),
queueStatus(INACTIVE) {}
/**
* Empty destructor, clean up is done in finish().
* @see TbusBaseQueue<T>::finish()
*/
template<class T> TbusBaseQueue<T>::~TbusBaseQueue() {}
/**
* Sets gate indices.
*/
template<class T> void TbusBaseQueue<T>::initialize() {
inGate = findGate("inGate");
outGate = findGate("outGate");
}
template<class T> void TbusBaseQueue<T>::setQueueControlCallback(TbusQueueControlCallback* qcCallback) {
callback = qcCallback;
}
/**
* Sets the TBUS packet queue's queue length
* @param queueLength Queue length
*/
template<class T> void TbusBaseQueue<T>::setQueueLength(int64_t queueLength) {
queue.setQueueLength(queueLength);
}
/**
* Set the status for value updates.
* @param status Value updates status
*/
template<class T> void TbusBaseQueue<T>::setQueueStatus(TbusQueueStatus status) {
if (status != queueStatus) {
// Only update if different
queueStatus = status;
// Make queue control aware of change
callback->queueStatusChanged(queueSelection);
}
}
/**
* Get this queues status.
* @return Queue status
*/
template<class T> TbusQueueStatus TbusBaseQueue<T>::getQueueStatus() const {
return queueStatus;
}
/**
* Handles the message accordingly if it is a self message or a packet.
* @param msg Message to handle
*/
template<class T> void TbusBaseQueue<T>::handleMessage(cMessage* msg) {
if (msg->isSelfMessage()) {
handleSelfMessage(msg);
} else {
cPacket* packet = check_and_cast<cPacket*>(msg);
addPacketToQueue(packet);
}
}
/**
* Sends the front of queue and inspects the next packets' earliest delivery time, schedules accordingly.
* @param msg self message
*/
template<class T> void TbusBaseQueue<T>::handleSelfMessage(cMessage* msg) {
// First, send the front packet
sendFrontOfQueue();
//Only leave current value
clearAndDeleteValues(TBUS_CLEAR_ALL_EXCEPT_FRONT);
// Then check the next one and/or reschedule
if (!queue.isEmpty()) {
// Re-calculate earliest deliveries
calculateEarliestDeliveries();
}
}
/**
* Adds a packet to the queue, then starts the sending process (if there is none).
* @param packet packet to add
*/
template <class T> bool TbusBaseQueue<T>::addPacketToQueue(cPacket* packet) {
bool result = queue.insertTbusPacket(packet);
if (result) {
// Only act if packet could be inserted
if (queue.length() == 1) {
// First packet in queue, set this queue as active
setQueueStatus(ACTIVE);
}
// Only calculate now when we have network characteristics
if (!values.empty()) {
calculateEarliestDeliveryForPacket(packet);
if (!selfMessage.isScheduled()) {
adaptSelfMessage();
}
}
}
return result;
}
/**
* Cancels the current self message (if any), recalculates earliest deliveries and schedules a new self message.
*/
template<class T> void TbusBaseQueue<T>::adaptSelfMessage() {
ASSERT2(queue.length() > 0, "Queue has to have length > 0!");
TbusQueueControlInfo* controlInfo = check_and_cast<TbusQueueControlInfo*>(queue.front()->getControlInfo());
if (selfMessage.isScheduled()) {
cancelEvent(&selfMessage);
}
// Take now or a future time as next schedule
simtime_t nextSchedule = SimTime(std::max(simTime().inUnit(SIMTIME_NS), controlInfo->getEarliestDelivery().inUnit(SIMTIME_NS)), SIMTIME_NS);
scheduleAt(nextSchedule, &selfMessage);
}
/**
* Removes the front packet from the queue and sends it to the out gate.
* Also clears all but the current value.
*/
template<class T> void TbusBaseQueue<T>::sendFrontOfQueue() {
cPacket* packet = queue.pop();
if (queue.empty()) {
// Last packet in queue, set queue inactive
setQueueStatus(INACTIVE);
}
TbusQueueControlInfo* controlInfo = check_and_cast<TbusQueueControlInfo*>(packet->getControlInfo());
ASSERT2(controlInfo->getEarliestDelivery() <= simTime(), "Sending packet earlier than expected!");
EV << this->getName() << ": dispatching packet " << packet << " at " << simTime() << std::endl;
#ifdef TBUS_DEBUG
std::cout << simTime() << " - " << this->getName() << ": " << packet << " sent after " << (simTime() - controlInfo->getQueueArrival()) << ", added at " << controlInfo->getQueueArrival() << endl;
#endif /* TBUS_DEBUG */
send(packet, outGate);
}
/**
* Adds the new value to the list if there are ongoing transmissions or uses it as the new value if there are none.
* @param newValue value to update to
*/
template<class T> void TbusBaseQueue<T>::updateValue(T* newValue) {
Enter_Method("updateValue()");
if (values.empty() || values.front() != newValue) {
// Clear old values
if (queue.isEmpty()) {
clearAndDeleteValues();
}
// Store new value
values.push_front(newValue);
// If there are ongoing transmissions, update their earliest deliveries
if (!queue.isEmpty()) {
calculateEarliestDeliveries();
}
} else {
delete newValue;
}
}
/**
* Templated function used for value deletion in std::for_each
* @param value Value to delete
*/
template<class T> void deleteValue(T* value) {
delete value;
}
/**
* Deletes all value objects and clears the deque
*/
template<class T> void TbusBaseQueue<T>::clearAndDeleteValues(const TbusClearMethod method) {
T* firstValue;
if (method == TBUS_CLEAR_ALL_EXCEPT_FRONT) {
firstValue = new T(*(values.front()));
}
// Remove all values and clear the values
std::for_each(values.begin(), values.end(), deleteValue<T>);
values.clear();
if (method == TBUS_CLEAR_ALL_EXCEPT_FRONT) {
values.push_front(firstValue);
}
}
/**
* Called upon simulation end.
* Releases selfmessage and cancels any future self message events.
* Clears the queue of packets.
*/
template<class T> void TbusBaseQueue<T>::finish() {
// Simulation Cleanup
if (selfMessage.isScheduled()) {
cancelEvent(&selfMessage);
}
clearAndDeleteValues();
queue.clear();
}
// Template instantiation for linker
template class TbusBaseQueue<TbusQueueDatarateValue>;
template class TbusBaseQueue<TbusQueueDelayValue>;
<commit_msg>Fix application log output<commit_after>//
// (c) 2014 Raphael Bialon <Raphael.Bialon@hhu.de>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program 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 program. If not, see http://www.gnu.org/licenses/.
//
#include "TbusBaseQueue.h"
#include "TbusQueueDatarateValue.h"
#include "TbusQueueDelayValue.h"
#include "omnetpp.h"
#include <algorithm>
/**
* Set up.
* Instantiates selfMessage
*/
template<class T> TbusBaseQueue<T>::TbusBaseQueue(TbusQueueSelection selection) :
selfMessage(NULL, 0),
queueSelection(selection),
queueStatus(INACTIVE) {}
/**
* Empty destructor, clean up is done in finish().
* @see TbusBaseQueue<T>::finish()
*/
template<class T> TbusBaseQueue<T>::~TbusBaseQueue() {}
/**
* Sets gate indices.
*/
template<class T> void TbusBaseQueue<T>::initialize() {
inGate = findGate("inGate");
outGate = findGate("outGate");
}
template<class T> void TbusBaseQueue<T>::setQueueControlCallback(TbusQueueControlCallback* qcCallback) {
callback = qcCallback;
}
/**
* Sets the TBUS packet queue's queue length
* @param queueLength Queue length
*/
template<class T> void TbusBaseQueue<T>::setQueueLength(int64_t queueLength) {
queue.setQueueLength(queueLength);
}
/**
* Set the status for value updates.
* @param status Value updates status
*/
template<class T> void TbusBaseQueue<T>::setQueueStatus(TbusQueueStatus status) {
if (status != queueStatus) {
// Only update if different
queueStatus = status;
// Make queue control aware of change
callback->queueStatusChanged(queueSelection);
}
}
/**
* Get this queues status.
* @return Queue status
*/
template<class T> TbusQueueStatus TbusBaseQueue<T>::getQueueStatus() const {
return queueStatus;
}
/**
* Handles the message accordingly if it is a self message or a packet.
* @param msg Message to handle
*/
template<class T> void TbusBaseQueue<T>::handleMessage(cMessage* msg) {
if (msg->isSelfMessage()) {
handleSelfMessage(msg);
} else {
cPacket* packet = check_and_cast<cPacket*>(msg);
addPacketToQueue(packet);
}
}
/**
* Sends the front of queue and inspects the next packets' earliest delivery time, schedules accordingly.
* @param msg self message
*/
template<class T> void TbusBaseQueue<T>::handleSelfMessage(cMessage* msg) {
// First, send the front packet
sendFrontOfQueue();
//Only leave current value
clearAndDeleteValues(TBUS_CLEAR_ALL_EXCEPT_FRONT);
// Then check the next one and/or reschedule
if (!queue.isEmpty()) {
// Re-calculate earliest deliveries
calculateEarliestDeliveries();
}
}
/**
* Adds a packet to the queue, then starts the sending process (if there is none).
* @param packet packet to add
*/
template <class T> bool TbusBaseQueue<T>::addPacketToQueue(cPacket* packet) {
bool result = queue.insertTbusPacket(packet);
if (result) {
// Only act if packet could be inserted
if (queue.length() == 1) {
// First packet in queue, set this queue as active
setQueueStatus(ACTIVE);
}
// Only calculate now when we have network characteristics
if (!values.empty()) {
calculateEarliestDeliveryForPacket(packet);
if (!selfMessage.isScheduled()) {
adaptSelfMessage();
}
}
}
return result;
}
/**
* Cancels the current self message (if any), recalculates earliest deliveries and schedules a new self message.
*/
template<class T> void TbusBaseQueue<T>::adaptSelfMessage() {
ASSERT2(queue.length() > 0, "Queue has to have length > 0!");
TbusQueueControlInfo* controlInfo = check_and_cast<TbusQueueControlInfo*>(queue.front()->getControlInfo());
if (selfMessage.isScheduled()) {
cancelEvent(&selfMessage);
}
// Take now or a future time as next schedule
simtime_t nextSchedule = SimTime(std::max(simTime().inUnit(SIMTIME_NS), controlInfo->getEarliestDelivery().inUnit(SIMTIME_NS)), SIMTIME_NS);
scheduleAt(nextSchedule, &selfMessage);
}
/**
* Removes the front packet from the queue and sends it to the out gate.
* Also clears all but the current value.
*/
template<class T> void TbusBaseQueue<T>::sendFrontOfQueue() {
cPacket* packet = queue.pop();
if (queue.empty()) {
// Last packet in queue, set queue inactive
setQueueStatus(INACTIVE);
}
TbusQueueControlInfo* controlInfo = check_and_cast<TbusQueueControlInfo*>(packet->getControlInfo());
ASSERT2(controlInfo->getEarliestDelivery() <= simTime(), "Sending packet earlier than expected!");
EV << this->getName() << ": dispatching packet " << packet << " at " << simTime() << std::endl;
#ifdef TBUS_DEBUG
std::cout << simTime() << " - " << this->getName() << ": " << packet << " sent after " << (simTime() - controlInfo->getQueueArrival()) << ", added at " << controlInfo->getQueueArrival() << endl;
#endif /* TBUS_DEBUG */
send(packet, outGate);
}
/**
* Adds the new value to the list if there are ongoing transmissions or uses it as the new value if there are none.
* @param newValue value to update to
*/
template<class T> void TbusBaseQueue<T>::updateValue(T* newValue) {
Enter_Method("updateValue()");
if (values.empty() || values.front() != newValue) {
// Clear old values
if (queue.isEmpty()) {
clearAndDeleteValues();
}
// Store new value
values.push_front(newValue);
// If there are ongoing transmissions, update their earliest deliveries
if (!queue.isEmpty()) {
calculateEarliestDeliveries();
}
} else {
delete newValue;
}
}
/**
* Templated function used for value deletion in std::for_each
* @param value Value to delete
*/
template<class T> void deleteValue(T* value) {
delete value;
}
/**
* Deletes all value objects and clears the deque
*/
template<class T> void TbusBaseQueue<T>::clearAndDeleteValues(const TbusClearMethod method) {
T* firstValue;
if (method == TBUS_CLEAR_ALL_EXCEPT_FRONT) {
firstValue = new T(*(values.front()));
}
// Remove all values and clear the values
std::for_each(values.begin(), values.end(), deleteValue<T>);
values.clear();
if (method == TBUS_CLEAR_ALL_EXCEPT_FRONT) {
values.push_front(firstValue);
}
}
/**
* Called upon simulation end.
* Releases selfmessage and cancels any future self message events.
* Clears the queue of packets.
*/
template<class T> void TbusBaseQueue<T>::finish() {
// Simulation Cleanup
if (selfMessage.isScheduled()) {
cancelEvent(&selfMessage);
}
clearAndDeleteValues();
queue.clear();
}
// Template instantiation for linker
template class TbusBaseQueue<TbusQueueDatarateValue>;
template class TbusBaseQueue<TbusQueueDelayValue>;
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
// //
// AliFemtoCutMonitorPairKT - the cut monitor for particles to study //
// the difference between reconstructed and true momentum //
// rmaselek@cern.ch //
////////////////////////////////////////////////////////////////////////////////
#include "AliFemtoCutMonitorPairKT.h"
#include "AliFemtoModelHiddenInfo.h"
#include <TH1D.h>
#include <TH2D.h>
#include <TList.h>
#include <TMath.h>
#include "AliFemtoPair.h"
AliFemtoCutMonitorPairKT::AliFemtoCutMonitorPairKT():
fkT(0),
fpTdiff(0),
fpTsum(0),
fMinv(0),
fQinv(0)
{
// Default constructor
fkT = new TH1D("kT", "k_T ", 100, 0, 4.0);
fpTdiff = new TH1D("pTdiff", "k_T vs Q_inv", 100, 0, 4.0);
fpTsum = new TH1D("pTsum", "p_T", 100, 0, 8.0);
fMinv = new TH1D("Minv", "m_inv dist", 1000, 0.0, 10.0);
fQinv = new TH1D("Qinv", "q_inv dist", 100, 0.0, 10.0);
}
AliFemtoCutMonitorPairKT::AliFemtoCutMonitorPairKT(const char *aName, float low_limit, float high_limit):
fkT(0),
fpTsum(0),
fpTdiff(0),
fMinv(0),
fQinv(0)
{
// Normal constructor
char name[200];
snprintf(name, 200, "kT%s", aName);
fkT = new TH1D(name, "k_T dist", 100, 0, 4.0);
snprintf(name, 200, "pTdiff%s", aName);
fpTdiff = new TH1D(name, "p_t diff dist", 100, 0, 4.0);
snprintf(name, 200, "pTsum%s", aName);
fpTsum = new TH1D(name, "p_T sum dist", 100, 0, 8.0);
snprintf(name, 200, "fMinv%s", aName);
fMinv = new TH1D(name, "m_inv dist", 1000, 0.0, 10.0);
snprintf(name, 200, "fQinv%s", aName);
fQinv = new TH1D(name, "q_inv dist", 1000, 0.0, 10.0);
}
AliFemtoCutMonitorPairKT::AliFemtoCutMonitorPairKT(const AliFemtoCutMonitorPairKT &aCut):
fkT(0),
fpTdiff(0),
fpTsum(0),
fMinv(0),
fQinv(0)
{
// copy constructor
fkT = new TH1D(*aCut.fkT);
fpTdiff = new TH1D(*aCut.fpTdiff);
fpTsum = new TH1D(*aCut.fpTsum);
fMinv = new TH1D(*aCut.fMinv);
fQinv = new TH1D(*aCut.fQinv);
}
AliFemtoCutMonitorPairKT::~AliFemtoCutMonitorPairKT()
{
// Destructor
delete fkT;
delete fpTdiff;
delete fpTsum;
delete fMinv;
delete fQinv;
}
AliFemtoCutMonitorPairKT& AliFemtoCutMonitorPairKT::operator=(const AliFemtoCutMonitorPairKT& aCut)
{
// assignment operator
if (this == &aCut)
return *this;
if (fkT) delete fkT;
fkT = new TH1D(*aCut.fkT);
if (fpTdiff) delete fpTdiff;
fpTdiff = new TH1D(*aCut.fpTdiff);
if (fpTsum) delete fpTsum;
fpTsum = new TH1D(*aCut.fpTsum);
if (fMinv) delete fMinv;
fMinv = new TH1D(*aCut.fMinv);
if (fQinv) delete fQinv;
fQinv = new TH1D(*aCut.fQinv);
return *this;
}
AliFemtoString AliFemtoCutMonitorPairKT::Report(){
// Prepare report from the execution
string stemp = "*** AliFemtoCutMonitorPairKT report";
AliFemtoString returnThis = stemp;
return returnThis;
}
void AliFemtoCutMonitorPairKT::Fill(const AliFemtoPair* aPair)
{
double pt1 = aPair->Track1()->Track()->Pt();
double pt2 = aPair->Track2()->Track()->Pt();
double kt = aPair->KT();
double Q_inv = aPair -> QInv();
double M_inv = aPair -> MInv();
double pt_sum = pt1 + pt2;
double pt_diff = TMath::Abs(pt1 - pt2);
fpTsum -> Fill(pt_sum);
fpTdiff -> Fill(pt_diff);
fkT -> Fill(kt);
fMinv -> Fill(M_inv);
fQinv->Fill(Q_inv);
// const PID1 int = aPair -> Track1() -> Track() -> GetPDGPid();
// const PID2 int = aPair -> Track2() -> Track() -> GetPDGPid();
// fPID->Fill(PID1);
// fPID->Fill(PID2);
}
void AliFemtoCutMonitorPairKT::Write()
{
// Write out the relevant histograms
fpTsum->Write();
fpTdiff->Write();
fkT->Write();
fMinv->Write();
fQinv->Write();
}
TList *AliFemtoCutMonitorPairKT::GetOutputList()
{
TList *tOutputList = new TList();
tOutputList->Add(fpTsum);
tOutputList->Add(fpTdiff);
tOutputList->Add(fkT);
tOutputList->Add(fMinv);
tOutputList->Add(fQinv);
return tOutputList;
}
<commit_msg>PWGCF: AliFemtoCutMonitorPairKT - Fixed initailizer order warnings & corrected inherited copy constructor<commit_after>////////////////////////////////////////////////////////////////////////////////
// //
// AliFemtoCutMonitorPairKT - the cut monitor for particles to study //
// the difference between reconstructed and true momentum //
// rmaselek@cern.ch //
////////////////////////////////////////////////////////////////////////////////
#include "AliFemtoCutMonitorPairKT.h"
#include "AliFemtoModelHiddenInfo.h"
#include <TH1D.h>
#include <TH2D.h>
#include <TList.h>
#include <TMath.h>
#include "AliFemtoPair.h"
AliFemtoCutMonitorPairKT::AliFemtoCutMonitorPairKT():
fkT(0),
fpTsum(0),
fpTdiff(0),
fQinv(0),
fMinv(0)
{
// Default constructor
fkT = new TH1D("kT", "k_T ", 100, 0, 4.0);
fpTdiff = new TH1D("pTdiff", "k_T vs Q_inv", 100, 0, 4.0);
fpTsum = new TH1D("pTsum", "p_T", 100, 0, 8.0);
fMinv = new TH1D("Minv", "m_inv dist", 1000, 0.0, 10.0);
fQinv = new TH1D("Qinv", "q_inv dist", 100, 0.0, 10.0);
}
AliFemtoCutMonitorPairKT::AliFemtoCutMonitorPairKT(const char *aName, float low_limit, float high_limit):
fkT(0),
fpTsum(0),
fpTdiff(0),
fQinv(0),
fMinv(0)
{
// Normal constructor
char name[200];
snprintf(name, 200, "kT%s", aName);
fkT = new TH1D(name, "k_T dist", 100, 0, 4.0);
snprintf(name, 200, "pTdiff%s", aName);
fpTdiff = new TH1D(name, "p_t diff dist", 100, 0, 4.0);
snprintf(name, 200, "pTsum%s", aName);
fpTsum = new TH1D(name, "p_T sum dist", 100, 0, 8.0);
snprintf(name, 200, "fMinv%s", aName);
fMinv = new TH1D(name, "m_inv dist", 1000, 0.0, 10.0);
snprintf(name, 200, "fQinv%s", aName);
fQinv = new TH1D(name, "q_inv dist", 1000, 0.0, 10.0);
}
AliFemtoCutMonitorPairKT::AliFemtoCutMonitorPairKT(const AliFemtoCutMonitorPairKT &aCut):
AliFemtoCutMonitor(aCut),
fkT(0),
fpTsum(0),
fpTdiff(0),
fQinv(0),
fMinv(0)
{
// copy constructor
fkT = new TH1D(*aCut.fkT);
fpTdiff = new TH1D(*aCut.fpTdiff);
fpTsum = new TH1D(*aCut.fpTsum);
fMinv = new TH1D(*aCut.fMinv);
fQinv = new TH1D(*aCut.fQinv);
}
AliFemtoCutMonitorPairKT::~AliFemtoCutMonitorPairKT()
{
// Destructor
delete fkT;
delete fpTdiff;
delete fpTsum;
delete fMinv;
delete fQinv;
}
AliFemtoCutMonitorPairKT& AliFemtoCutMonitorPairKT::operator=(const AliFemtoCutMonitorPairKT& aCut)
{
// assignment operator
if (this == &aCut)
return *this;
AliFemtoCutMonitor::operator=(aCut);
if (fkT) delete fkT;
fkT = new TH1D(*aCut.fkT);
if (fpTdiff) delete fpTdiff;
fpTdiff = new TH1D(*aCut.fpTdiff);
if (fpTsum) delete fpTsum;
fpTsum = new TH1D(*aCut.fpTsum);
if (fMinv) delete fMinv;
fMinv = new TH1D(*aCut.fMinv);
if (fQinv) delete fQinv;
fQinv = new TH1D(*aCut.fQinv);
return *this;
}
AliFemtoString AliFemtoCutMonitorPairKT::Report(){
// Prepare report from the execution
string stemp = "*** AliFemtoCutMonitorPairKT report";
AliFemtoString returnThis = stemp;
return returnThis;
}
void AliFemtoCutMonitorPairKT::Fill(const AliFemtoPair* aPair)
{
double pt1 = aPair->Track1()->Track()->Pt();
double pt2 = aPair->Track2()->Track()->Pt();
double kt = aPair->KT();
double Q_inv = aPair -> QInv();
double M_inv = aPair -> MInv();
double pt_sum = pt1 + pt2;
double pt_diff = TMath::Abs(pt1 - pt2);
fpTsum -> Fill(pt_sum);
fpTdiff -> Fill(pt_diff);
fkT -> Fill(kt);
fMinv -> Fill(M_inv);
fQinv->Fill(Q_inv);
// const PID1 int = aPair -> Track1() -> Track() -> GetPDGPid();
// const PID2 int = aPair -> Track2() -> Track() -> GetPDGPid();
// fPID->Fill(PID1);
// fPID->Fill(PID2);
}
void AliFemtoCutMonitorPairKT::Write()
{
// Write out the relevant histograms
fpTsum->Write();
fpTdiff->Write();
fkT->Write();
fMinv->Write();
fQinv->Write();
}
TList *AliFemtoCutMonitorPairKT::GetOutputList()
{
TList *tOutputList = new TList();
tOutputList->Add(fpTsum);
tOutputList->Add(fpTdiff);
tOutputList->Add(fkT);
tOutputList->Add(fMinv);
tOutputList->Add(fQinv);
return tOutputList;
}
<|endoftext|>
|
<commit_before>// coding: utf-8
/* Copyright (c) 2014, Electronic Kiwi, daniel-k
* All Rights Reserved.
*
* The file is part of the xpcc-playground and is released under the 3-clause BSD
* license. See the file `LICENSE` for the full license governing this code.
*/
#include <xpcc/architecture.hpp>
#include <xpcc/debug/logger.hpp>
#include <nrf24.hpp>
using namespace xpcc::stm32;
typedef GpioOutputD15 LedBlue; // User LED 6
typedef LedBlue Led;
xpcc::IODeviceWrapper< Usart2 > loggerDevice;
xpcc::log::Logger xpcc::log::error(loggerDevice);
xpcc::log::Logger xpcc::log::warning(loggerDevice);
xpcc::log::Logger xpcc::log::info(loggerDevice);
xpcc::log::Logger xpcc::log::debug(loggerDevice);
// Set the log level
#undef XPCC_LOG_LEVEL
#define XPCC_LOG_LEVEL xpcc::log::DEBUG
static constexpr bool isReceiverNotTransmitter = false;
typedef SystemClock<Pll<ExternalCrystal<MHz8>, MHz48, MHz48> > defaultSystemClock;
struct
Fake8MHzSystemClock
{
static constexpr int Usart2 = MHz16;
};
MAIN_FUNCTION
{
//defaultSystemClock::enable();
Led::setOutput(xpcc::Gpio::Low);
// Initialize Usart
GpioOutputA2::connect(Usart2::Tx);
GpioInputA3::connect(Usart2::Rx, Gpio::InputType::PullUp);
Usart2::initialize<Fake8MHzSystemClock, 115200>(10);
XPCC_LOG_INFO << "Nrf24L01+ Test" << xpcc::endl;
if(isReceiverNotTransmitter) {
///////////// Receiver /////////////////////////////////////////////////////
XPCC_LOG_INFO << "acting as receiver" << xpcc::endl;
uint8_t data_array[4];
const uint8_t tx_address[5] = {0xD7,0xD7,0xD7,0xD7,0xD7};
const uint8_t rx_address[5] = {0xE7,0xE7,0xE7,0xE7,0xE7};
nrf24_init();
XPCC_LOG_DEBUG << "called nrf24_init()..." << xpcc::endl;
nrf24_config(2,4);
XPCC_LOG_DEBUG << "called nrf24_config(2,4)..." << xpcc::endl;
nrf24_tx_address(tx_address);
XPCC_LOG_DEBUG << "called nrf24_tx_address({0xD7,0xD7,0xD7,0xD7,0xD7})..." << xpcc::endl;
nrf24_rx_address(rx_address);
XPCC_LOG_DEBUG << "called nrf24_rx_address({0xE7,0xE7,0xE7,0xE7,0xE7})..." << xpcc::endl;
} else {
///////////// Transmitter //////////////////////////////////////////////////
XPCC_LOG_INFO << "acting as transmitter" << xpcc::endl;
uint8_t temp;
uint8_t q = 0;
uint8_t data_array[4];
uint8_t tx_address[5] = {0xE7,0xE7,0xE7,0xE7,0xE7};
uint8_t rx_address[5] = {0xD7,0xD7,0xD7,0xD7,0xD7};
/* init hardware pins */
nrf24_init();
XPCC_LOG_INFO << "nrf24_init() done" << xpcc::endl;
/* Channel #2 , payload length: 4 */
nrf24_config(2,4);
XPCC_LOG_INFO << "nrf24_config(2,4) done" << xpcc::endl;
/* Set the device addresses */
nrf24_tx_address(tx_address);
XPCC_LOG_INFO << "nrf24_tx_address(tx_address) done" << xpcc::endl;
nrf24_rx_address(rx_address);
XPCC_LOG_INFO << "nrf24_rx_address(rx_address) done" << xpcc::endl;
while(1)
{
/* Fill the data buffer */
data_array[0] = 0x00;
data_array[1] = 0xAA;
data_array[2] = 0x55;
data_array[3] = q++;
/* Automatically goes to TX mode */
nrf24_send(data_array);
XPCC_LOG_INFO << "nrf24_send(data_array) done" << xpcc::endl;
/* Wait for transmission to end */
while(nrf24_isSending());
XPCC_LOG_INFO << "nrf24_isSending() done" << xpcc::endl;
/* Make analysis on last tranmission attempt */
temp = nrf24_lastMessageStatus();
XPCC_LOG_INFO << "nrf24_lastMessageStatus() done" << xpcc::endl;
if(temp == NRF24_TRANSMISSON_OK)
{
XPCC_LOG_INFO << "> Tranmission went OK" << xpcc::endl;
}
else if(temp == NRF24_MESSAGE_LOST)
{
XPCC_LOG_INFO << "> Message is lost ..." << xpcc::endl;
}
/* Retranmission count indicates the tranmission quality */
temp = nrf24_retransmissionCount();
XPCC_LOG_INFO << "> Retranmission count: " << temp << xpcc::endl;
/* Optionally, go back to RX mode ... */
nrf24_powerUpRx();
XPCC_LOG_INFO << "nrf24_powerUpRx() done" << xpcc::endl;
/* Or you might want to power down after TX */
// nrf24_powerDown();
/* Wait a little ... */
_delay_ms(10);
}
while (1)
{
if(nrf24_dataReady())
{
nrf24_getData(data_array);
XPCC_LOG_INFO << "Msg: 0x" << xpcc::hex
<< data_array[0] << data_array[1] << data_array[2]
<< data_array[3] << xpcc::endl;
}
Led::toggle();
xpcc::delay_ms(100);
}
while (1)
{
Led::toggle();
xpcc::delay_ms(100);
}
}
}
<commit_msg>correct receiver while loop<commit_after>// coding: utf-8
/* Copyright (c) 2014, Electronic Kiwi, daniel-k
* All Rights Reserved.
*
* The file is part of the xpcc-playground and is released under the 3-clause BSD
* license. See the file `LICENSE` for the full license governing this code.
*/
#include <xpcc/architecture.hpp>
#include <xpcc/debug/logger.hpp>
#include <nrf24.hpp>
using namespace xpcc::stm32;
typedef GpioOutputD15 LedBlue; // User LED 6
typedef LedBlue Led;
xpcc::IODeviceWrapper< Usart2 > loggerDevice;
xpcc::log::Logger xpcc::log::error(loggerDevice);
xpcc::log::Logger xpcc::log::warning(loggerDevice);
xpcc::log::Logger xpcc::log::info(loggerDevice);
xpcc::log::Logger xpcc::log::debug(loggerDevice);
// Set the log level
#undef XPCC_LOG_LEVEL
#define XPCC_LOG_LEVEL xpcc::log::DEBUG
static constexpr bool isReceiverNotTransmitter = false;
typedef SystemClock<Pll<ExternalCrystal<MHz8>, MHz48, MHz48> > defaultSystemClock;
struct
Fake8MHzSystemClock
{
static constexpr int Usart2 = MHz16;
};
MAIN_FUNCTION
{
//defaultSystemClock::enable();
Led::setOutput(xpcc::Gpio::Low);
// Initialize Usart
GpioOutputA2::connect(Usart2::Tx);
GpioInputA3::connect(Usart2::Rx, Gpio::InputType::PullUp);
Usart2::initialize<Fake8MHzSystemClock, 115200>(10);
XPCC_LOG_INFO << "Nrf24L01+ Test" << xpcc::endl;
if(isReceiverNotTransmitter) {
///////////// Receiver /////////////////////////////////////////////////////
XPCC_LOG_INFO << "acting as receiver" << xpcc::endl;
uint8_t data_array[4];
const uint8_t tx_address[5] = {0xD7,0xD7,0xD7,0xD7,0xD7};
const uint8_t rx_address[5] = {0xE7,0xE7,0xE7,0xE7,0xE7};
nrf24_init();
XPCC_LOG_DEBUG << "called nrf24_init()..." << xpcc::endl;
nrf24_config(2,4);
XPCC_LOG_DEBUG << "called nrf24_config(2,4)..." << xpcc::endl;
nrf24_tx_address(tx_address);
XPCC_LOG_DEBUG << "called nrf24_tx_address({0xD7,0xD7,0xD7,0xD7,0xD7})..." << xpcc::endl;
nrf24_rx_address(rx_address);
XPCC_LOG_DEBUG << "called nrf24_rx_address({0xE7,0xE7,0xE7,0xE7,0xE7})..." << xpcc::endl;
while (1)
{
if(nrf24_dataReady())
{
nrf24_getData(data_array);
XPCC_LOG_INFO << "Msg: 0x" << xpcc::hex
<< data_array[0] << data_array[1] << data_array[2]
<< data_array[3] << xpcc::endl;
}
Led::toggle();
xpcc::delay_ms(100);
}
} else {
///////////// Transmitter //////////////////////////////////////////////////
XPCC_LOG_INFO << "acting as transmitter" << xpcc::endl;
uint8_t temp;
uint8_t q = 0;
uint8_t data_array[4];
uint8_t tx_address[5] = {0xE7,0xE7,0xE7,0xE7,0xE7};
uint8_t rx_address[5] = {0xD7,0xD7,0xD7,0xD7,0xD7};
/* init hardware pins */
nrf24_init();
XPCC_LOG_INFO << "nrf24_init() done" << xpcc::endl;
/* Channel #2 , payload length: 4 */
nrf24_config(2,4);
XPCC_LOG_INFO << "nrf24_config(2,4) done" << xpcc::endl;
/* Set the device addresses */
nrf24_tx_address(tx_address);
XPCC_LOG_INFO << "nrf24_tx_address(tx_address) done" << xpcc::endl;
nrf24_rx_address(rx_address);
XPCC_LOG_INFO << "nrf24_rx_address(rx_address) done" << xpcc::endl;
while(1)
{
/* Fill the data buffer */
data_array[0] = 0x00;
data_array[1] = 0xAA;
data_array[2] = 0x55;
data_array[3] = q++;
/* Automatically goes to TX mode */
nrf24_send(data_array);
XPCC_LOG_INFO << "nrf24_send(data_array) done" << xpcc::endl;
/* Wait for transmission to end */
while(nrf24_isSending());
XPCC_LOG_INFO << "nrf24_isSending() done" << xpcc::endl;
/* Make analysis on last tranmission attempt */
temp = nrf24_lastMessageStatus();
XPCC_LOG_INFO << "nrf24_lastMessageStatus() done" << xpcc::endl;
if(temp == NRF24_TRANSMISSON_OK)
{
XPCC_LOG_INFO << "> Tranmission went OK" << xpcc::endl;
}
else if(temp == NRF24_MESSAGE_LOST)
{
XPCC_LOG_INFO << "> Message is lost ..." << xpcc::endl;
}
/* Retranmission count indicates the tranmission quality */
temp = nrf24_retransmissionCount();
XPCC_LOG_INFO << "> Retranmission count: " << temp << xpcc::endl;
/* Optionally, go back to RX mode ... */
nrf24_powerUpRx();
XPCC_LOG_INFO << "nrf24_powerUpRx() done" << xpcc::endl;
/* Or you might want to power down after TX */
// nrf24_powerDown();
/* Wait a little ... */
_delay_ms(10);
Led::toggle();
}
}
while (1)
{
Led::toggle();
xpcc::delay_ms(100);
}
}
<|endoftext|>
|
<commit_before>// -------------------------------------------------------------------------
// @FileName : NFCDataBaseModule.h
// @Author : LvSheng.Huang
// @Date : 2012-12-15
// @Module : NFCDataBaseModule
// Row,Col; ; ; ; ; ; ;
// -------------------------------------------------------------------------
//#include "stdafx.h"
#include <algorithm>
#include "NFCMysqlDriver.h"
#include "NFCMysqlClusterModule.h"
std::string NFCMysqlClusterModule::strDefaultKey = "id";
std::string NFCMysqlClusterModule::strDefaultTable = "role_info";
NFCMysqlClusterModule::NFCMysqlClusterModule(NFIPluginManager* p)
{
pPluginManager = p;
}
NFCMysqlClusterModule::~NFCMysqlClusterModule()
{
}
bool NFCMysqlClusterModule::Init()
{
// m_pShareMemoryModule = dynamic_cast<NFIShareMemoryModule*>(pPluginManager->FindModule("NFCShareMemoryModule"));
//
// otl_connect::otl_initialize();
//
// bool bLoad = mConfig.Load(mstrDataBaseConfigFile);
//
// mstrUID = mConfig["UID"].str();
// mstrPWD = mConfig["PWD"].str();
// mstrDSN = mConfig["DSN"].str();
// mstrMasterName = mConfig["MST"].str();
//
// mstrAccountTableName = mConfig["AccountTBL"].str();
// mstrPlayerTableName = mConfig["RoleTBL"].str();
// mstrGlobalTableName = mConfig["GlobalTBL"].str();
//
//
// m_pDataBaseDriver->OTLConnect(mstrUID, mstrPWD, mstrDSN, motlConnect);
return true;
}
bool NFCMysqlClusterModule::Shut()
{
//m_pDataBaseDriver->OTLDisconnect(motlConnect);
return true;
}
bool NFCMysqlClusterModule::AfterInit()
{
m_pMysqlConnectMgrManager = dynamic_cast<NFIMysqlConnectMgrModule*>(pPluginManager->FindModule("NFCMysqlConnectMgrModule"));
assert(NULL != m_pMysqlConnectMgrManager);
return true;
}
bool NFCMysqlClusterModule::Execute(const float fLasFrametime, const float fStartedTime)
{
return true;
}
bool NFCMysqlClusterModule::Updata( const std::string& strKey, const std::vector<std::string>& fieldVec, const std::vector<std::string>& valueVec )
{
return Updata(strDefaultTable, strKey, fieldVec, valueVec);
}
bool NFCMysqlClusterModule::Updata( const std::string& strRecordName, const std::string& strKey, const std::vector<std::string>& fieldVec, const std::vector<std::string>& valueVec )
{
mysqlpp::Connection* pConnection = m_pMysqlConnectMgrManager->GetMysqlDriver()->GetConnection();
if (NULL == pConnection)
{
return false;
}
bool bExist = false;
if (!Exists(strRecordName, strKey, bExist))
{
return false;
}
if (fieldVec.size() != valueVec.size())
{
return false;
}
std::ostringstream strSQL;
if (bExist)
{
// update
strSQL << "UPDATE " << strRecordName << " ";
for (int i = 0; i < fieldVec.size(); ++i)
{
if (i == 0)
{
strSQL << fieldVec[i] << " = " << valueVec[i];
}
else
{
strSQL << "," << fieldVec[i] << " = " << valueVec[i];
}
}
}
else
{
// insert
strSQL << "INSERT INTO " << strRecordName << "(";
for (int i = 0; i < fieldVec.size(); ++i)
{
if (i == 0)
{
strSQL << fieldVec[i];
}
else
{
strSQL << ", " << fieldVec[i];
}
}
strSQL << ") VALUES(";
for (int i = 0; i < valueVec.size(); ++i)
{
if (i == 0)
{
strSQL << mysqlpp::quote << valueVec[i];
}
else
{
strSQL << ", " << mysqlpp::quote << valueVec[i];
}
}
strSQL << ")";
}
strSQL << ";";
NFMYSQLTRYBEGIN
std::ostringstream stream;
stream << "DELETE FROM " << strRecordName << " WHERE " << strDefaultKey << " = " << mysqlpp::quote << strKey << ";";
mysqlpp::Query query = pConnection->query(stream.str());
query.reset();
NFMYSQLTRYEND("update or insert error")
return true;
}
bool NFCMysqlClusterModule::Query( const std::string& strKey, const std::vector<std::string>& fieldVec, std::vector<std::string>& valueVec )
{
return Query(strDefaultTable, strKey, fieldVec, valueVec);
}
bool NFCMysqlClusterModule::Query( const std::string& strRecordName, const std::string& strKey, const std::vector<std::string>& fieldVec, std::vector<std::string>& valueVec )
{
mysqlpp::Connection* pConnection = m_pMysqlConnectMgrManager->GetMysqlDriver()->GetConnection();
if (NULL == pConnection)
{
return false;
}
NFMYSQLTRYBEGIN
std::ostringstream stream;
stream << "SELECT ";
for (std::vector<std::string>::const_iterator iter = fieldVec.begin(); iter != fieldVec.end(); ++iter)
{
if (iter == fieldVec.begin())
{
stream << *iter;
}
else
{
stream << "," << *iter;
}
}
stream << " FROM " << strRecordName << " WHERE " << strDefaultKey << " = " << mysqlpp::quote << strKey << ";";
mysqlpp::Query query = pConnection->query(stream.str());
mysqlpp::StoreQueryResult xResult = query.store();
query.reset();
if (xResult.empty() || !xResult)
{
return false;
}
// xResultӦֻһеģΪԺֵܳĶѭ
for (int i = 0; i < xResult.size(); ++i)
{
for (int j = 0; j < fieldVec.size(); ++j)
{
const std::string& strFieldName = fieldVec[j];
std::string strValue(xResult[i][strFieldName.data()].data(), xResult[i][strFieldName.data()].length());
valueVec.push_back(strValue);
}
}
NFMYSQLTRYEND("query error")
return true;
}
bool NFCMysqlClusterModule::Delete( const std::string& strKey )
{
return Delete(strDefaultTable, strKey);
}
bool NFCMysqlClusterModule::Delete( const std::string& strRecordName, const std::string& strKey )
{
mysqlpp::Connection* pConnection = m_pMysqlConnectMgrManager->GetMysqlDriver()->GetConnection();
if (NULL == pConnection)
{
return false;
}
NFMYSQLTRYBEGIN
std::ostringstream stream;
stream << "DELETE FROM " << strRecordName << " WHERE " << strDefaultKey << " = " << mysqlpp::quote << strKey << ";";
mysqlpp::Query query = pConnection->query(stream.str());
query.reset();
NFMYSQLTRYEND("delete error")
return true;
}
bool NFCMysqlClusterModule::Exists( const std::string& strKey, bool& bExit )
{
//select 1 from table where col_name = col_value limit 1;
return Exists(strDefaultTable, strKey, bExit);
}
bool NFCMysqlClusterModule::Exists( const std::string& strRecordName, const std::string& strKey, bool& bExit )
{
mysqlpp::Connection* pConnection = m_pMysqlConnectMgrManager->GetMysqlDriver()->GetConnection();
if (NULL == pConnection)
{
return false;
}
NFMYSQLTRYBEGIN
std::ostringstream stream;
stream << "SELECT 1 FROM " << strRecordName << " WHERE " << strDefaultKey << " = " << mysqlpp::quote << strKey << " LIMIT 1;";
mysqlpp::Query query = pConnection->query(stream.str());
mysqlpp::StoreQueryResult result = query.store();
query.reset();
if (!result || result.empty())
{
bExit = false;
return false;
}
NFMYSQLTRYEND("exist error")
bExit = true;
return true;
}
bool NFCMysqlClusterModule::Select( const std::string& strKey, const std::vector<std::string>& fieldVec, std::vector<std::string>& valueVec )
{
return false;
}
bool NFCMysqlClusterModule::Select( const std::string& strRecordName, const std::string& strKey, const std::vector<std::string>& fieldVec, std::vector<std::string>& valueVec )
{
return false;
}<commit_msg>fix sql sentence<commit_after>// -------------------------------------------------------------------------
// @FileName : NFCDataBaseModule.h
// @Author : LvSheng.Huang
// @Date : 2012-12-15
// @Module : NFCDataBaseModule
// Row,Col; ; ; ; ; ; ;
// -------------------------------------------------------------------------
//#include "stdafx.h"
#include <algorithm>
#include "NFCMysqlDriver.h"
#include "NFCMysqlClusterModule.h"
std::string NFCMysqlClusterModule::strDefaultKey = "id";
std::string NFCMysqlClusterModule::strDefaultTable = "role_info";
NFCMysqlClusterModule::NFCMysqlClusterModule(NFIPluginManager* p)
{
pPluginManager = p;
}
NFCMysqlClusterModule::~NFCMysqlClusterModule()
{
}
bool NFCMysqlClusterModule::Init()
{
// m_pShareMemoryModule = dynamic_cast<NFIShareMemoryModule*>(pPluginManager->FindModule("NFCShareMemoryModule"));
//
// otl_connect::otl_initialize();
//
// bool bLoad = mConfig.Load(mstrDataBaseConfigFile);
//
// mstrUID = mConfig["UID"].str();
// mstrPWD = mConfig["PWD"].str();
// mstrDSN = mConfig["DSN"].str();
// mstrMasterName = mConfig["MST"].str();
//
// mstrAccountTableName = mConfig["AccountTBL"].str();
// mstrPlayerTableName = mConfig["RoleTBL"].str();
// mstrGlobalTableName = mConfig["GlobalTBL"].str();
//
//
// m_pDataBaseDriver->OTLConnect(mstrUID, mstrPWD, mstrDSN, motlConnect);
return true;
}
bool NFCMysqlClusterModule::Shut()
{
//m_pDataBaseDriver->OTLDisconnect(motlConnect);
return true;
}
bool NFCMysqlClusterModule::AfterInit()
{
m_pMysqlConnectMgrManager = dynamic_cast<NFIMysqlConnectMgrModule*>(pPluginManager->FindModule("NFCMysqlConnectMgrModule"));
assert(NULL != m_pMysqlConnectMgrManager);
return true;
}
bool NFCMysqlClusterModule::Execute(const float fLasFrametime, const float fStartedTime)
{
return true;
}
bool NFCMysqlClusterModule::Updata( const std::string& strKey, const std::vector<std::string>& fieldVec, const std::vector<std::string>& valueVec )
{
return Updata(strDefaultTable, strKey, fieldVec, valueVec);
}
bool NFCMysqlClusterModule::Updata( const std::string& strRecordName, const std::string& strKey, const std::vector<std::string>& fieldVec, const std::vector<std::string>& valueVec )
{
mysqlpp::Connection* pConnection = m_pMysqlConnectMgrManager->GetMysqlDriver()->GetConnection();
if (NULL == pConnection)
{
return false;
}
bool bExist = false;
if (!Exists(strRecordName, strKey, bExist))
{
return false;
}
if (fieldVec.size() != valueVec.size())
{
return false;
}
NFMYSQLTRYBEGIN
mysqlpp::Query query = pConnection->query();
if (bExist)
{
// update
query << "UPDATE " << strRecordName << " ";
for (int i = 0; i < fieldVec.size(); ++i)
{
if (i == 0)
{
query << fieldVec[i] << " = " << valueVec[i];
}
else
{
query << "," << fieldVec[i] << " = " << valueVec[i];
}
}
}
else
{
// insert
query << "INSERT INTO " << strRecordName << "(";
for (int i = 0; i < fieldVec.size(); ++i)
{
if (i == 0)
{
query << fieldVec[i];
}
else
{
query << ", " << fieldVec[i];
}
}
query << ") VALUES(";
for (int i = 0; i < valueVec.size(); ++i)
{
if (i == 0)
{
query << mysqlpp::quote << valueVec[i];
}
else
{
query << ", " << mysqlpp::quote << valueVec[i];
}
}
query << ")";
}
query << ";";
query.execute();
query.reset();
NFMYSQLTRYEND("update or insert error")
return true;
}
bool NFCMysqlClusterModule::Query( const std::string& strKey, const std::vector<std::string>& fieldVec, std::vector<std::string>& valueVec )
{
return Query(strDefaultTable, strKey, fieldVec, valueVec);
}
bool NFCMysqlClusterModule::Query( const std::string& strRecordName, const std::string& strKey, const std::vector<std::string>& fieldVec, std::vector<std::string>& valueVec )
{
mysqlpp::Connection* pConnection = m_pMysqlConnectMgrManager->GetMysqlDriver()->GetConnection();
if (NULL == pConnection)
{
return false;
}
NFMYSQLTRYBEGIN
mysqlpp::Query query = pConnection->query();
query << "SELECT ";
for (std::vector<std::string>::const_iterator iter = fieldVec.begin(); iter != fieldVec.end(); ++iter)
{
if (iter == fieldVec.begin())
{
query << *iter;
}
else
{
query << "," << *iter;
}
}
query << " FROM " << strRecordName << " WHERE " << strDefaultKey << " = " << mysqlpp::quote << strKey << ";";
query.execute();
mysqlpp::StoreQueryResult xResult = query.store();
query.reset();
if (xResult.empty() || !xResult)
{
return false;
}
// xResultӦֻһеģΪԺֵܳĶѭ
for (int i = 0; i < xResult.size(); ++i)
{
for (int j = 0; j < fieldVec.size(); ++j)
{
const std::string& strFieldName = fieldVec[j];
std::string strValue(xResult[i][strFieldName.data()].data(), xResult[i][strFieldName.data()].length());
valueVec.push_back(strValue);
}
}
NFMYSQLTRYEND("query error")
return true;
}
bool NFCMysqlClusterModule::Delete( const std::string& strKey )
{
return Delete(strDefaultTable, strKey);
}
bool NFCMysqlClusterModule::Delete( const std::string& strRecordName, const std::string& strKey )
{
mysqlpp::Connection* pConnection = m_pMysqlConnectMgrManager->GetMysqlDriver()->GetConnection();
if (NULL == pConnection)
{
return false;
}
NFMYSQLTRYBEGIN
mysqlpp::Query query = pConnection->query();
query << "DELETE FROM " << strRecordName << " WHERE " << strDefaultKey << " = " << mysqlpp::quote << strKey << ";";
query.execute();
query.reset();
NFMYSQLTRYEND("delete error")
return true;
}
bool NFCMysqlClusterModule::Exists( const std::string& strKey, bool& bExit )
{
//select 1 from table where col_name = col_value limit 1;
return Exists(strDefaultTable, strKey, bExit);
}
bool NFCMysqlClusterModule::Exists( const std::string& strRecordName, const std::string& strKey, bool& bExit )
{
mysqlpp::Connection* pConnection = m_pMysqlConnectMgrManager->GetMysqlDriver()->GetConnection();
if (NULL == pConnection)
{
return false;
}
NFMYSQLTRYBEGIN
mysqlpp::Query query = pConnection->query();
query << "SELECT 1 FROM " << strRecordName << " WHERE " << strDefaultKey << " = " << mysqlpp::quote << strKey << " LIMIT 1;";
query.execute();
mysqlpp::StoreQueryResult result = query.store();
query.reset();
if (!result || result.empty())
{
bExit = false;
return false;
}
NFMYSQLTRYEND("exist error")
bExit = true;
return true;
}
bool NFCMysqlClusterModule::Select( const std::string& strKey, const std::vector<std::string>& fieldVec, std::vector<std::string>& valueVec )
{
return false;
}
bool NFCMysqlClusterModule::Select( const std::string& strRecordName, const std::string& strKey, const std::vector<std::string>& fieldVec, std::vector<std::string>& valueVec )
{
return false;
}<|endoftext|>
|
<commit_before>/*
* This source file is part of ARK
* For the latest info, see https://github.com/ArkNX
*
* Copyright (c) 2013-2019 ArkNX authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <args/args.hxx>
#include "base/AFBaseStruct.hpp"
#include "base/AFMacros.hpp"
#include "base/AFDateTime.hpp"
#include "base/AFMisc.hpp"
#include "base/AFCDataList.hpp"
#include "AFCPluginManager.h"
using namespace ark;
bool g_exit_loop = false;
std::thread g_cmd_thread;
#if ARK_PLATFORM == PLATFORM_WIN
//mini-dump
void CreateDumpFile(const std::string& strDumpFilePathName, EXCEPTION_POINTERS* pException)
{
HANDLE hDumpFile = CreateFile(strDumpFilePathName.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
MINIDUMP_EXCEPTION_INFORMATION dumpInfo;
dumpInfo.ExceptionPointers = pException;
dumpInfo.ThreadId = GetCurrentThreadId();
dumpInfo.ClientPointers = TRUE;
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL);
CloseHandle(hDumpFile);
}
long ApplicationCrashHandler(EXCEPTION_POINTERS* pException)
{
AFDateTime now;
std::string dump_name = ARK_FORMAT("{}-{:04d}{:02d}{:02d}_{:02d}_{:02d}_{:02d}.dmp",
AFCPluginManager::get()->AppName(),
now.GetYear(), now.GetMonth(), now.GetDay(),
now.GetHour(), now.GetMinute(), now.GetSecond());
CreateDumpFile(dump_name.c_str(), pException);
FatalAppExit(-1, dump_name.c_str());
return EXCEPTION_EXECUTE_HANDLER;
}
#endif
void CloseXButton()
{
#if ARK_PLATFORM == PLATFORM_WIN
HWND hWnd = GetConsoleWindow();
if (hWnd)
{
HMENU hMenu = GetSystemMenu(hWnd, FALSE);
EnableMenuItem(hMenu, SC_CLOSE, MF_DISABLED | MF_BYCOMMAND);
}
#else
//Do nothing
#endif
}
void InitDaemon()
{
#if ARK_PLATFORM == PLATFORM_UNIX
int ret = daemon(1, 0);
ARK_ASSERT_NO_EFFECT(ret == 0);
// ignore signals
signal(SIGINT, SIG_IGN);
signal(SIGHUP, SIG_IGN);
signal(SIGQUIT, SIG_IGN);
signal(SIGPIPE, SIG_IGN);
signal(SIGTTOU, SIG_IGN);
signal(SIGTTIN, SIG_IGN);
signal(SIGTERM, SIG_IGN);
#endif
}
void PrintLogo()
{
#if ARK_PLATFORM == PLATFORM_WIN
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
#endif
std::string logo = R"(
**********************************************************************
___ _ _ _ _ _
/ _ \ __ _ _ _ __| | | | | _____ __ / \ _ __| | __
| | | |/ _` | | | |/ _` | |_| |/ _ \ \/ / _____ / _ \ | '__| |/ /
| |_| | (_| | |_| | (_| | _ | __/> < |_____| / ___ \| | | <
\__\_\\__,_|\__,_|\__,_|_| |_|\___/_/\_\ /_/ \_\_| |_|\_\
Copyright 2018 (c) QuadHex. All Rights Reserved.
Website: https://quadhex.io
Github: https://github.com/ArkNX
Gitee: https://gitee.com/QuadHex
**********************************************************************
)";
CONSOLE_INFO_LOG << logo << std::endl;
#if ARK_PLATFORM == PLATFORM_WIN
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
#endif
}
void ThreadFunc()
{
while (!g_exit_loop)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
std::string s;
std::cin >> s;
s = AFMisc::ToLower(s);
if (s == "exit")
{
g_exit_loop = true;
}
}
}
void CreateBackThread()
{
g_cmd_thread = std::thread(std::bind(&ThreadFunc));
}
#if ARK_PLATFORM == PLATFORM_UNIX
extern char** environ;
class environ_guard
{
public:
~environ_guard()
{
if (env_buf)
{
delete[] env_buf;
env_buf = nullptr;
}
if (environ)
{
delete[] environ;
environ = nullptr;
}
}
char* env_buf;
char** environ;
};
environ_guard g_new_environ_guard{ nullptr, nullptr };
int realloc_environ()
{
int var_count = 0;
int env_size = 0;
do
{
char** ep = environ;
while (*ep)
{
env_size += std::strlen(*ep) + 1;
++var_count;
++ep;
}
} while (false);
char* new_env_buf = new char[env_size];
std::memcpy((void*)new_env_buf, (void*)*environ, env_size);
char** new_env = new char* [var_count + 1];
do
{
int var = 0;
int offset = 0;
char** ep = environ;
while (*ep)
{
new_env[var++] = (new_env_buf + offset);
offset += std::strlen(*ep) + 1;
++ep;
}
} while (false);
new_env[var_count] = 0;
// RAII to prevent memory leak
g_new_environ_guard = environ_guard{ new_env_buf, new_env };
environ = new_env;
return env_size;
}
void setproctitle(const char* title, int argc, char** argv)
{
int argv_size = 0;
for (int i = 0; i < argc; ++i)
{
int len = std::strlen(argv[i]);
std::memset(argv[i], 0, len);
argv_size += len;
}
int to_be_copied = std::strlen(title);
if (argv_size <= to_be_copied)
{
int env_size = realloc_environ();
if (env_size < to_be_copied)
{
to_be_copied = env_size;
}
}
std::strncpy(argv[0], title, to_be_copied);
*(argv[0] + to_be_copied) = 0;
}
#endif
bool ParseArgs(int argc, char* argv[])
{
args::ArgumentParser parser("Here is ark plugin loader argument tools", "If you have any questions, please report an issue in GitHub.");
args::HelpFlag help(parser, "help", "Display the help menu", {'h', "help"});
args::ActionFlag xbutton(parser, "close", "Close [x] button in Windows", { 'x' }, []()
{
#if ARK_PLATFORM == PLATFORM_WIN
SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ApplicationCrashHandler);
CloseXButton();
#endif
});
args::ActionFlag daemon(parser, "daemon", "Run application as daemon", { 'd' }, []()
{
#if ARK_PLATFORM == PLATFORM_UNIX
InitDaemon();
#endif
});
args::ValueFlag<std::string> busid(parser, "busid", "Set application id(like IP address: 8.8.8.8)", { 'b', "busid" }, "8.8.8.8", args::Options::Required | args::Options::Single);
args::ValueFlag<std::string> name(parser, "name", "Set application name", { 'n', "name" }, "my-server", args::Options::Required | args::Options::Single);
args::ValueFlag<std::string> plugin_cfg(parser, "plugin config path", "Set application plugin config", { 'p', "plugin" }, "plugin.xml", args::Options::Required | args::Options::Single);
std::string default_log_path = ARK_FORMAT("..{}binlog", ARK_FOLDER_SEP);
args::ValueFlag<std::string> logpath(parser, "logpath", "Set application log output path", { 'l', "logpath" }, default_log_path, args::Options::Required | args::Options::Single);
//start parse argument list
try
{
parser.ParseCLI(argc, argv);
}
catch (args::Help)
{
CONSOLE_ERROR_LOG << parser;
return false;
}
catch (args::ParseError& e)
{
CONSOLE_ERROR_LOG << e.what() << std::endl;
CONSOLE_ERROR_LOG << parser;
return false;
}
catch (args::ValidationError& e)
{
CONSOLE_ERROR_LOG << e.what() << std::endl;
CONSOLE_ERROR_LOG << parser;
return false;
}
//Set bus id
if (busid)
{
AFCDataList temp_bus_id;
if (!temp_bus_id.Split(busid.Get(), "."))
{
CONSOLE_ERROR_LOG << "bus id is invalid, it likes 8.8.8.8" << std::endl;
return false;
}
AFBusAddr busaddr;
busaddr.channel_id = ARK_LEXICAL_CAST<int>(temp_bus_id.String(0));
busaddr.zone_id = ARK_LEXICAL_CAST<int>(temp_bus_id.String(1));
busaddr.proc_id = ARK_LEXICAL_CAST<int>(temp_bus_id.String(2));
busaddr.inst_id = ARK_LEXICAL_CAST<int>(temp_bus_id.String(3));
AFCPluginManager::get()->SetBusID(busaddr.bus_id);
}
else
{
return false;
}
//Set app name
if (name)
{
AFCPluginManager::get()->SetAppName(name.Get());
std::string process_name = ARK_FORMAT("{}-{}-{}", name.Get(), busid.Get(), AFCPluginManager::get()->BusID());
//Set process name
#if ARK_PLATFORM == PLATFORM_WIN
SetConsoleTitle(process_name.c_str());
#elif ARK_PLATFORM == PLATFORM_UNIX
//setproctitle(process_name.c_str(), argc, argv);
#endif
}
else
{
return false;
}
//Set plugin file
if (plugin_cfg)
{
AFCPluginManager::get()->SetPluginConf(plugin_cfg.Get());
}
else
{
return false;
}
if (logpath)
{
AFCPluginManager::get()->SetLogPath(logpath.Get());
}
else
{
return false;
}
//Create back thread, for some command
CreateBackThread();
return true;
}
void MainLoop()
{
#if ARK_PLATFORM == PLATFORM_WIN
__try
{
AFCPluginManager::get()->Update();
}
__except (ApplicationCrashHandler(GetExceptionInformation()))
{
//Do nothing for now.
}
#else
AFCPluginManager::get()->Update();
#endif
}
int main(int argc, char* argv[])
{
if (!ParseArgs(argc, argv))
{
CONSOLE_INFO_LOG << "Application parameter is invalid, please check it..." << std::endl;
return 0;
}
PrintLogo();
ARK_ASSERT_RET_VAL(AFCPluginManager::get()->Init(), -1);
ARK_ASSERT_RET_VAL(AFCPluginManager::get()->PostInit(), -1);
ARK_ASSERT_RET_VAL(AFCPluginManager::get()->CheckConfig(), -1);
ARK_ASSERT_RET_VAL(AFCPluginManager::get()->PreUpdate(), -1);
while (!g_exit_loop)
{
for (;; std::this_thread::sleep_for(std::chrono::milliseconds(1)))
{
if (g_exit_loop)
{
break;
}
MainLoop();
}
}
AFCPluginManager::get()->PreShut();
AFCPluginManager::get()->Shut();
g_cmd_thread.join();
return 0;
}
<commit_msg>renew the logo<commit_after>/*
* This source file is part of ARK
* For the latest info, see https://github.com/ArkNX
*
* Copyright (c) 2013-2019 ArkNX authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <args/args.hxx>
#include "base/AFBaseStruct.hpp"
#include "base/AFMacros.hpp"
#include "base/AFDateTime.hpp"
#include "base/AFMisc.hpp"
#include "base/AFCDataList.hpp"
#include "AFCPluginManager.h"
using namespace ark;
bool g_exit_loop = false;
std::thread g_cmd_thread;
#if ARK_PLATFORM == PLATFORM_WIN
//mini-dump
void CreateDumpFile(const std::string& strDumpFilePathName, EXCEPTION_POINTERS* pException)
{
HANDLE hDumpFile = CreateFile(strDumpFilePathName.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
MINIDUMP_EXCEPTION_INFORMATION dumpInfo;
dumpInfo.ExceptionPointers = pException;
dumpInfo.ThreadId = GetCurrentThreadId();
dumpInfo.ClientPointers = TRUE;
MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL);
CloseHandle(hDumpFile);
}
long ApplicationCrashHandler(EXCEPTION_POINTERS* pException)
{
AFDateTime now;
std::string dump_name = ARK_FORMAT("{}-{:04d}{:02d}{:02d}_{:02d}_{:02d}_{:02d}.dmp",
AFCPluginManager::get()->AppName(),
now.GetYear(), now.GetMonth(), now.GetDay(),
now.GetHour(), now.GetMinute(), now.GetSecond());
CreateDumpFile(dump_name.c_str(), pException);
FatalAppExit(-1, dump_name.c_str());
return EXCEPTION_EXECUTE_HANDLER;
}
#endif
void CloseXButton()
{
#if ARK_PLATFORM == PLATFORM_WIN
HWND hWnd = GetConsoleWindow();
if (hWnd)
{
HMENU hMenu = GetSystemMenu(hWnd, FALSE);
EnableMenuItem(hMenu, SC_CLOSE, MF_DISABLED | MF_BYCOMMAND);
}
#else
//Do nothing
#endif
}
void InitDaemon()
{
#if ARK_PLATFORM == PLATFORM_UNIX
int ret = daemon(1, 0);
ARK_ASSERT_NO_EFFECT(ret == 0);
// ignore signals
signal(SIGINT, SIG_IGN);
signal(SIGHUP, SIG_IGN);
signal(SIGQUIT, SIG_IGN);
signal(SIGPIPE, SIG_IGN);
signal(SIGTTOU, SIG_IGN);
signal(SIGTTIN, SIG_IGN);
signal(SIGTERM, SIG_IGN);
#endif
}
void PrintLogo()
{
#if ARK_PLATFORM == PLATFORM_WIN
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
#endif
std::string logo = R"(
**********************************************************************
_ _
/ \ _ __| | __
/ _ \ | '__| |/ /
/ ___ \| | | <
/_/ \_\_| |_|\_\
Copyright 2018 (c) ArkNX. All Rights Reserved.
Website: https://arknx.com
Github: https://github.com/ArkNX
**********************************************************************
)";
CONSOLE_INFO_LOG << logo << std::endl;
#if ARK_PLATFORM == PLATFORM_WIN
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
#endif
}
void ThreadFunc()
{
while (!g_exit_loop)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
std::string s;
std::cin >> s;
s = AFMisc::ToLower(s);
if (s == "exit")
{
g_exit_loop = true;
}
}
}
void CreateBackThread()
{
g_cmd_thread = std::thread(std::bind(&ThreadFunc));
}
#if ARK_PLATFORM == PLATFORM_UNIX
extern char** environ;
class environ_guard
{
public:
~environ_guard()
{
if (env_buf)
{
delete[] env_buf;
env_buf = nullptr;
}
if (environ)
{
delete[] environ;
environ = nullptr;
}
}
char* env_buf;
char** environ;
};
environ_guard g_new_environ_guard{ nullptr, nullptr };
int realloc_environ()
{
int var_count = 0;
int env_size = 0;
do
{
char** ep = environ;
while (*ep)
{
env_size += std::strlen(*ep) + 1;
++var_count;
++ep;
}
} while (false);
char* new_env_buf = new char[env_size];
std::memcpy((void*)new_env_buf, (void*)*environ, env_size);
char** new_env = new char* [var_count + 1];
do
{
int var = 0;
int offset = 0;
char** ep = environ;
while (*ep)
{
new_env[var++] = (new_env_buf + offset);
offset += std::strlen(*ep) + 1;
++ep;
}
} while (false);
new_env[var_count] = 0;
// RAII to prevent memory leak
g_new_environ_guard = environ_guard{ new_env_buf, new_env };
environ = new_env;
return env_size;
}
void setproctitle(const char* title, int argc, char** argv)
{
int argv_size = 0;
for (int i = 0; i < argc; ++i)
{
int len = std::strlen(argv[i]);
std::memset(argv[i], 0, len);
argv_size += len;
}
int to_be_copied = std::strlen(title);
if (argv_size <= to_be_copied)
{
int env_size = realloc_environ();
if (env_size < to_be_copied)
{
to_be_copied = env_size;
}
}
std::strncpy(argv[0], title, to_be_copied);
*(argv[0] + to_be_copied) = 0;
}
#endif
bool ParseArgs(int argc, char* argv[])
{
args::ArgumentParser parser("Here is ark plugin loader argument tools", "If you have any questions, please report an issue in GitHub.");
args::HelpFlag help(parser, "help", "Display the help menu", {'h', "help"});
args::ActionFlag xbutton(parser, "close", "Close [x] button in Windows", { 'x' }, []()
{
#if ARK_PLATFORM == PLATFORM_WIN
SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ApplicationCrashHandler);
CloseXButton();
#endif
});
args::ActionFlag daemon(parser, "daemon", "Run application as daemon", { 'd' }, []()
{
#if ARK_PLATFORM == PLATFORM_UNIX
InitDaemon();
#endif
});
args::ValueFlag<std::string> busid(parser, "busid", "Set application id(like IP address: 8.8.8.8)", { 'b', "busid" }, "8.8.8.8", args::Options::Required | args::Options::Single);
args::ValueFlag<std::string> name(parser, "name", "Set application name", { 'n', "name" }, "my-server", args::Options::Required | args::Options::Single);
args::ValueFlag<std::string> plugin_cfg(parser, "plugin config path", "Set application plugin config", { 'p', "plugin" }, "plugin.xml", args::Options::Required | args::Options::Single);
std::string default_log_path = ARK_FORMAT("..{}binlog", ARK_FOLDER_SEP);
args::ValueFlag<std::string> logpath(parser, "logpath", "Set application log output path", { 'l', "logpath" }, default_log_path, args::Options::Required | args::Options::Single);
//start parse argument list
try
{
parser.ParseCLI(argc, argv);
}
catch (args::Help)
{
CONSOLE_ERROR_LOG << parser;
return false;
}
catch (args::ParseError& e)
{
CONSOLE_ERROR_LOG << e.what() << std::endl;
CONSOLE_ERROR_LOG << parser;
return false;
}
catch (args::ValidationError& e)
{
CONSOLE_ERROR_LOG << e.what() << std::endl;
CONSOLE_ERROR_LOG << parser;
return false;
}
//Set bus id
if (busid)
{
AFCDataList temp_bus_id;
if (!temp_bus_id.Split(busid.Get(), "."))
{
CONSOLE_ERROR_LOG << "bus id is invalid, it likes 8.8.8.8" << std::endl;
return false;
}
AFBusAddr busaddr;
busaddr.channel_id = ARK_LEXICAL_CAST<int>(temp_bus_id.String(0));
busaddr.zone_id = ARK_LEXICAL_CAST<int>(temp_bus_id.String(1));
busaddr.proc_id = ARK_LEXICAL_CAST<int>(temp_bus_id.String(2));
busaddr.inst_id = ARK_LEXICAL_CAST<int>(temp_bus_id.String(3));
AFCPluginManager::get()->SetBusID(busaddr.bus_id);
}
else
{
return false;
}
//Set app name
if (name)
{
AFCPluginManager::get()->SetAppName(name.Get());
std::string process_name = ARK_FORMAT("{}-{}-{}", name.Get(), busid.Get(), AFCPluginManager::get()->BusID());
//Set process name
#if ARK_PLATFORM == PLATFORM_WIN
SetConsoleTitle(process_name.c_str());
#elif ARK_PLATFORM == PLATFORM_UNIX
//setproctitle(process_name.c_str(), argc, argv);
#endif
}
else
{
return false;
}
//Set plugin file
if (plugin_cfg)
{
AFCPluginManager::get()->SetPluginConf(plugin_cfg.Get());
}
else
{
return false;
}
if (logpath)
{
AFCPluginManager::get()->SetLogPath(logpath.Get());
}
else
{
return false;
}
//Create back thread, for some command
CreateBackThread();
return true;
}
void MainLoop()
{
#if ARK_PLATFORM == PLATFORM_WIN
__try
{
AFCPluginManager::get()->Update();
}
__except (ApplicationCrashHandler(GetExceptionInformation()))
{
//Do nothing for now.
}
#else
AFCPluginManager::get()->Update();
#endif
}
int main(int argc, char* argv[])
{
if (!ParseArgs(argc, argv))
{
CONSOLE_INFO_LOG << "Application parameter is invalid, please check it..." << std::endl;
return 0;
}
PrintLogo();
ARK_ASSERT_RET_VAL(AFCPluginManager::get()->Init(), -1);
ARK_ASSERT_RET_VAL(AFCPluginManager::get()->PostInit(), -1);
ARK_ASSERT_RET_VAL(AFCPluginManager::get()->CheckConfig(), -1);
ARK_ASSERT_RET_VAL(AFCPluginManager::get()->PreUpdate(), -1);
while (!g_exit_loop)
{
for (;; std::this_thread::sleep_for(std::chrono::milliseconds(1)))
{
if (g_exit_loop)
{
break;
}
MainLoop();
}
}
AFCPluginManager::get()->PreShut();
AFCPluginManager::get()->Shut();
g_cmd_thread.join();
return 0;
}
<|endoftext|>
|
<commit_before><commit_msg>Fixed loop issue<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: precompiled_forms.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: obo $ $Date: 2006-09-16 23:46:40 $
*
* 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): Generated on 2006-09-01 17:49:42.358362
#ifdef PRECOMPILED_HEADERS
#endif
<commit_msg>INTEGRATION: CWS pchfix04 (1.2.30); FILE MERGED 2006/11/27 18:21:54 mkretzschmar 1.2.30.1: #i71519# fill in forms pch file. Builds fine on Mac OS X and Linux.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: precompiled_forms.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2007-05-10 16:28:24 $
*
* 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): Generated on 2006-09-01 17:49:42.358362
#ifdef PRECOMPILED_HEADERS
//---MARKER---
#include "sal/config.h"
#include "sal/types.h"
#include "com/sun/star/awt/ActionEvent.hpp"
#include "com/sun/star/awt/FontDescriptor.hpp"
#include "com/sun/star/awt/FontEmphasisMark.hpp"
#include "com/sun/star/awt/FontRelief.hpp"
#include "com/sun/star/awt/ImageStatus.hpp"
#include "com/sun/star/awt/LineEndFormat.hpp"
#include "com/sun/star/awt/MouseButton.hpp"
#include "com/sun/star/awt/MouseEvent.hpp"
#include "com/sun/star/awt/PopupMenuDirection.hpp"
#include "com/sun/star/awt/PosSize.hpp"
#include "com/sun/star/awt/SystemPointer.hpp"
#include "com/sun/star/awt/VclWindowPeerAttribute.hpp"
#include "com/sun/star/awt/XActionListener.hpp"
#include "com/sun/star/awt/XButton.hpp"
#include "com/sun/star/awt/XCheckBox.hpp"
#include "com/sun/star/awt/XComboBox.hpp"
#include "com/sun/star/awt/XControlModel.hpp"
#include "com/sun/star/awt/XDialog.hpp"
#include "com/sun/star/awt/XFocusListener.hpp"
#include "com/sun/star/awt/XImageConsumer.hpp"
#include "com/sun/star/awt/XImageProducer.hpp"
#include "com/sun/star/awt/XItemListener.hpp"
#include "com/sun/star/awt/XListBox.hpp"
#include "com/sun/star/awt/XMouseListener.hpp"
#include "com/sun/star/awt/XRadioButton.hpp"
#include "com/sun/star/awt/XTabControllerModel.hpp"
#include "com/sun/star/awt/XTextComponent.hpp"
#include "com/sun/star/awt/XWindowListener2.hpp"
#include "com/sun/star/beans/NamedValue.hpp"
#include "com/sun/star/beans/Property.hpp"
#include "com/sun/star/beans/PropertyAttribute.hpp"
#include "com/sun/star/beans/PropertyChangeEvent.hpp"
#include "com/sun/star/beans/PropertyValue.hpp"
#include "com/sun/star/beans/XFastPropertySet.hpp"
#include "com/sun/star/beans/XMultiPropertySet.hpp"
#include "com/sun/star/beans/XPropertyChangeListener.hpp"
#include "com/sun/star/beans/XPropertySet.hpp"
#include "com/sun/star/beans/XPropertySetInfo.hpp"
#include "com/sun/star/beans/XPropertyState.hpp"
#include "com/sun/star/container/ElementExistException.hpp"
#include "com/sun/star/container/NoSuchElementException.hpp"
#include "com/sun/star/container/XChild.hpp"
#include "com/sun/star/container/XContainer.hpp"
#include "com/sun/star/container/XContainerListener.hpp"
#include "com/sun/star/container/XEnumeration.hpp"
#include "com/sun/star/container/XEnumerationAccess.hpp"
#include "com/sun/star/container/XIndexAccess.hpp"
#include "com/sun/star/container/XIndexContainer.hpp"
#include "com/sun/star/container/XIndexReplace.hpp"
#include "com/sun/star/container/XNameAccess.hpp"
#include "com/sun/star/container/XNameContainer.hpp"
#include "com/sun/star/container/XNameReplace.hpp"
#include "com/sun/star/container/XNamed.hpp"
#include "com/sun/star/container/XSet.hpp"
#include "com/sun/star/form/DataSelectionType.hpp"
#include "com/sun/star/form/DatabaseParameterEvent.hpp"
#include "com/sun/star/form/FormButtonType.hpp"
#include "com/sun/star/form/FormComponentType.hpp"
#include "com/sun/star/form/FormSubmitEncoding.hpp"
#include "com/sun/star/form/FormSubmitMethod.hpp"
#include "com/sun/star/form/ListSourceType.hpp"
#include "com/sun/star/form/NavigationBarMode.hpp"
#include "com/sun/star/form/TabulatorCycle.hpp"
#include "com/sun/star/form/XApproveActionBroadcaster.hpp"
#include "com/sun/star/form/XApproveActionListener.hpp"
#include "com/sun/star/form/XBoundComponent.hpp"
#include "com/sun/star/form/XBoundControl.hpp"
#include "com/sun/star/form/XChangeBroadcaster.hpp"
#include "com/sun/star/form/XDatabaseParameterBroadcaster2.hpp"
#include "com/sun/star/form/XDatabaseParameterListener.hpp"
#include "com/sun/star/form/XForm.hpp"
#include "com/sun/star/form/XFormComponent.hpp"
#include "com/sun/star/form/XGridColumnFactory.hpp"
#include "com/sun/star/form/XImageProducerSupplier.hpp"
#include "com/sun/star/form/XLoadListener.hpp"
#include "com/sun/star/form/XLoadable.hpp"
#include "com/sun/star/form/XReset.hpp"
#include "com/sun/star/form/XResetListener.hpp"
#include "com/sun/star/form/binding/XBindableValue.hpp"
#include "com/sun/star/form/binding/XListEntryListener.hpp"
#include "com/sun/star/form/binding/XListEntrySink.hpp"
#include "com/sun/star/form/binding/XListEntrySource.hpp"
#include "com/sun/star/form/binding/XValueBinding.hpp"
#include "com/sun/star/form/submission/XSubmission.hpp"
#include "com/sun/star/form/submission/XSubmissionSupplier.hpp"
#include "com/sun/star/form/validation/XValidatableFormComponent.hpp"
#include "com/sun/star/form/validation/XValidator.hpp"
#include "com/sun/star/form/validation/XValidityConstraintListener.hpp"
#include "com/sun/star/frame/FrameSearchFlag.hpp"
#include "com/sun/star/frame/XComponentLoader.hpp"
#include "com/sun/star/frame/XDispatch.hpp"
#include "com/sun/star/frame/XDispatchProvider.hpp"
#include "com/sun/star/frame/XDispatchProviderInterception.hpp"
#include "com/sun/star/frame/XDispatchProviderInterceptor.hpp"
#include "com/sun/star/frame/XStatusListener.hpp"
#include "com/sun/star/graphic/XGraphic.hpp"
#include "com/sun/star/io/NotConnectedException.hpp"
#include "com/sun/star/io/WrongFormatException.hpp"
#include "com/sun/star/io/XActiveDataSink.hpp"
#include "com/sun/star/io/XInputStream.hpp"
#include "com/sun/star/io/XMarkableStream.hpp"
#include "com/sun/star/io/XObjectInputStream.hpp"
#include "com/sun/star/io/XObjectOutputStream.hpp"
#include "com/sun/star/io/XOutputStream.hpp"
#include "com/sun/star/io/XPersistObject.hpp"
#include "com/sun/star/io/XTextInputStream.hpp"
#include "com/sun/star/lang/DisposedException.hpp"
#include "com/sun/star/lang/EventObject.hpp"
#include "com/sun/star/lang/IllegalArgumentException.hpp"
#include "com/sun/star/lang/IndexOutOfBoundsException.hpp"
#include "com/sun/star/lang/WrappedTargetException.hpp"
#include "com/sun/star/lang/XComponent.hpp"
#include "com/sun/star/lang/XEventListener.hpp"
#include "com/sun/star/lang/XInitialization.hpp"
#include "com/sun/star/lang/XMultiServiceFactory.hpp"
#include "com/sun/star/lang/XServiceInfo.hpp"
#include "com/sun/star/lang/XSingleServiceFactory.hpp"
#include "com/sun/star/lang/XTypeProvider.hpp"
#include "com/sun/star/lang/XUnoTunnel.hpp"
#include "com/sun/star/registry/XRegistryKey.hpp"
#include "com/sun/star/script/ScriptEvent.hpp"
#include "com/sun/star/script/ScriptEventDescriptor.hpp"
#include "com/sun/star/script/XEventAttacherManager.hpp"
#include "com/sun/star/sdb/CommandType.hpp"
#include "com/sun/star/sdb/ParametersRequest.hpp"
#include "com/sun/star/sdb/RowSetVetoException.hpp"
#include "com/sun/star/sdb/SQLContext.hpp"
#include "com/sun/star/sdb/SQLErrorEvent.hpp"
#include "com/sun/star/sdb/XColumn.hpp"
#include "com/sun/star/sdb/XColumnUpdate.hpp"
#include "com/sun/star/sdb/XCompletedExecution.hpp"
#include "com/sun/star/sdb/XInteractionSupplyParameters.hpp"
#include "com/sun/star/sdb/XParametersSupplier.hpp"
#include "com/sun/star/sdb/XQueriesSupplier.hpp"
#include "com/sun/star/sdb/XResultSetAccess.hpp"
#include "com/sun/star/sdb/XRowSetApproveBroadcaster.hpp"
#include "com/sun/star/sdb/XRowSetApproveListener.hpp"
#include "com/sun/star/sdb/XSQLErrorBroadcaster.hpp"
#include "com/sun/star/sdb/XSQLErrorListener.hpp"
#include "com/sun/star/sdb/XSQLQueryComposer.hpp"
#include "com/sun/star/sdb/XSQLQueryComposerFactory.hpp"
#include "com/sun/star/sdb/XSingleSelectQueryComposer.hpp"
#include "com/sun/star/sdbc/ColumnValue.hpp"
#include "com/sun/star/sdbc/DataType.hpp"
#include "com/sun/star/sdbc/ResultSetConcurrency.hpp"
#include "com/sun/star/sdbc/ResultSetType.hpp"
#include "com/sun/star/sdbc/SQLException.hpp"
#include "com/sun/star/sdbc/XCloseable.hpp"
#include "com/sun/star/sdbc/XConnection.hpp"
#include "com/sun/star/sdbc/XDataSource.hpp"
#include "com/sun/star/sdbc/XParameters.hpp"
#include "com/sun/star/sdbc/XResultSetUpdate.hpp"
#include "com/sun/star/sdbc/XRowSet.hpp"
#include "com/sun/star/sdbc/XRowSetListener.hpp"
#include "com/sun/star/sdbcx/Privilege.hpp"
#include "com/sun/star/sdbcx/XColumnsSupplier.hpp"
#include "com/sun/star/sdbcx/XDeleteRows.hpp"
#include "com/sun/star/sdbcx/XTablesSupplier.hpp"
#include "com/sun/star/task/XInteractionContinuation.hpp"
#include "com/sun/star/task/XInteractionHandler.hpp"
#include "com/sun/star/task/XInteractionRequest.hpp"
#include "com/sun/star/ucb/PostCommandArgument2.hpp"
#include "com/sun/star/ucb/XCommandEnvironment.hpp"
#include "com/sun/star/ucb/XProgressHandler.hpp"
#include "com/sun/star/ucb/XSimpleFileAccess.hpp"
#include "com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp"
#include "com/sun/star/ui/dialogs/TemplateDescription.hpp"
#include "com/sun/star/ui/dialogs/XExecutableDialog.hpp"
#include "com/sun/star/ui/dialogs/XFilePicker.hpp"
#include "com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp"
#include "com/sun/star/uno/Any.hxx"
#include "com/sun/star/uno/Exception.hpp"
#include "com/sun/star/uno/Reference.h"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/RuntimeException.hpp"
#include "com/sun/star/uno/Sequence.hxx"
#include "com/sun/star/uno/Type.hxx"
#include "com/sun/star/uno/XAggregation.hpp"
#include "com/sun/star/uno/XInterface.hpp"
#include "com/sun/star/util/Date.hpp"
#include "com/sun/star/util/DateTime.hpp"
#include "com/sun/star/util/NumberFormat.hpp"
#include "com/sun/star/util/SearchAlgorithms.hpp"
#include "com/sun/star/util/Time.hpp"
#include "com/sun/star/util/URL.hpp"
#include "com/sun/star/util/XCancellable.hpp"
#include "com/sun/star/util/XCloneable.hpp"
#include "com/sun/star/util/XModifyBroadcaster.hpp"
#include "com/sun/star/util/XModifyListener.hpp"
#include "com/sun/star/util/XNumberFormatTypes.hpp"
#include "com/sun/star/util/XNumberFormatsSupplier.hpp"
#include "com/sun/star/util/XNumberFormatter.hpp"
#include "com/sun/star/util/XRefreshable.hpp"
#include "com/sun/star/util/XURLTransformer.hpp"
#include "com/sun/star/util/XUpdatable.hpp"
#include "com/sun/star/view/XSelectionSupplier.hpp"
#include "com/sun/star/xforms/InvalidDataOnSubmitException.hpp"
#include "com/sun/star/xforms/XDataTypeRepository.hpp"
#include "com/sun/star/xforms/XFormsEvent.hpp"
#include "com/sun/star/xforms/XFormsSupplier.hpp"
#include "com/sun/star/xforms/XModel.hpp"
#include "com/sun/star/xforms/XSubmission.hpp"
#include "com/sun/star/xml/dom/NodeType.hpp"
#include "com/sun/star/xml/dom/XCharacterData.hpp"
#include "com/sun/star/xml/dom/XDocument.hpp"
#include "com/sun/star/xml/dom/XDocumentBuilder.hpp"
#include "com/sun/star/xml/dom/XDocumentFragment.hpp"
#include "com/sun/star/xml/dom/XElement.hpp"
#include "com/sun/star/xml/dom/XNamedNodeMap.hpp"
#include "com/sun/star/xml/dom/XNode.hpp"
#include "com/sun/star/xml/dom/XNodeList.hpp"
#include "com/sun/star/xml/dom/XText.hpp"
#include "com/sun/star/xml/dom/events/XDocumentEvent.hpp"
#include "com/sun/star/xml/dom/events/XEventListener.hpp"
#include "com/sun/star/xml/dom/events/XEventTarget.hpp"
#include "com/sun/star/xml/xpath/Libxml2ExtensionHandle.hpp"
#include "com/sun/star/xml/xpath/XPathObjectType.hpp"
#include "com/sun/star/xml/xpath/XXPathAPI.hpp"
#include "com/sun/star/xml/xpath/XXPathExtension.hpp"
#include "com/sun/star/xml/xpath/XXPathObject.hpp"
#include "com/sun/star/xsd/DataTypeClass.hpp"
#include "com/sun/star/xsd/WhiteSpaceTreatment.hpp"
#include "com/sun/star/xsd/XDataType.hpp"
#include "comphelper/basicio.hxx"
#include "comphelper/broadcasthelper.hxx"
#include "comphelper/container.hxx"
#include "comphelper/enumhelper.hxx"
#include "comphelper/eventattachermgr.hxx"
#include "comphelper/guarding.hxx"
#include "comphelper/implementationreference.hxx"
#include "comphelper/interaction.hxx"
#include "comphelper/listenernotification.hxx"
#include "comphelper/numbers.hxx"
#include "comphelper/processfactory.hxx"
#include "comphelper/propertycontainer.hxx"
#include "comphelper/propertycontainerhelper.hxx"
#include "comphelper/propertysetinfo.hxx"
#include "comphelper/seqstream.hxx"
#include "comphelper/sequence.hxx"
#include "comphelper/stl_types.hxx"
#include "comphelper/streamsection.hxx"
#include "comphelper/types.hxx"
#include "comphelper/uno3.hxx"
#include "connectivity/dbconversion.hxx"
#include "connectivity/predicateinput.hxx"
#include "connectivity/sqlparse.hxx"
#include "cppuhelper/compbase3.hxx"
#include "cppuhelper/component.hxx"
#include "cppuhelper/factory.hxx"
#include "cppuhelper/implbase1.hxx"
#include "cppuhelper/implbase11.hxx"
#include "cppuhelper/implbase2.hxx"
#include "cppuhelper/implbase3.hxx"
#include "cppuhelper/implbase4.hxx"
#include "cppuhelper/implbase5.hxx"
#include "cppuhelper/implbase6.hxx"
#include "cppuhelper/implbase7.hxx"
#include "cppuhelper/implbase8.hxx"
#include "cppuhelper/interfacecontainer.h"
#include "cppuhelper/interfacecontainer.hxx"
#include "cppuhelper/propshlp.hxx"
#include "cppuhelper/queryinterface.hxx"
#include "cppuhelper/typeprovider.hxx"
#include "cppuhelper/weak.hxx"
#include "cppuhelper/weakref.hxx"
#include "i18npool/mslangid.hxx"
#include "libxml/tree.h"
#include "libxml/xpath.h"
#include "libxml/xpathInternals.h"
#include "osl/conditn.hxx"
#include "osl/diagnose.h"
#include "osl/file.hxx"
#include "osl/mutex.hxx"
#include "rtl/alloc.h"
#include "rtl/logfile.hxx"
#include "rtl/math.hxx"
#include "rtl/memory.h"
#include "rtl/strbuf.hxx"
#include "rtl/string.hxx"
#include "rtl/tencinfo.h"
#include "rtl/textenc.h"
#include "rtl/ustrbuf.hxx"
#include "rtl/ustring.h"
#include "rtl/ustring.hxx"
#include "rtl/uuid.h"
#include "sfx2/imgmgr.hxx"
#include "sfx2/msgpool.hxx"
#include "sfx2/sfxuno.hxx"
#include "svtools/cliplistener.hxx"
#include "svtools/imageresourceaccess.hxx"
#include "svtools/inetstrm.hxx"
#include "svtools/inettype.hxx"
#include "svtools/itempool.hxx"
#include "svtools/itemset.hxx"
#include "svtools/languageoptions.hxx"
#include "svtools/lingucfg.hxx"
#include "svtools/numuno.hxx"
#include "svtools/poolitem.hxx"
#include "svtools/solar.hrc"
#include "svtools/transfer.hxx"
#include "svx/editdata.hxx"
#include "svx/editeng.hxx"
#include "svx/editobj.hxx"
#include "svx/editstat.hxx"
#include "svx/editview.hxx"
#include "svx/eeitem.hxx"
#include "svx/frmdir.hxx"
#include "svx/scripttypeitem.hxx"
#include "svx/svxenum.hxx"
#include "svx/svxids.hrc"
#include "svx/unoedsrc.hxx"
#include "svx/unofored.hxx"
#include "toolkit/helper/emptyfontdescriptor.hxx"
#include "tools/color.hxx"
#include "tools/date.hxx"
#include "tools/debug.hxx"
#include "tools/diagnose_ex.h"
#include "tools/inetmsg.hxx"
#include "tools/link.hxx"
#include "tools/list.hxx"
#include "tools/resid.hxx"
#include "tools/simplerm.hxx"
#include "tools/solar.h"
#include "tools/stream.hxx"
#include "tools/string.hxx"
#include "tools/urlobj.hxx"
#include "ucbhelper/activedatasink.hxx"
#include "ucbhelper/content.hxx"
#include "uno/lbnames.h"
#include "uno/mapping.hxx"
#include "unotools/desktopterminationobserver.hxx"
#include "unotools/idhelper.hxx"
#include "unotools/processfactory.hxx"
#include "unotools/streamhelper.hxx"
#include "unotools/textsearch.hxx"
#include "unotools/ucbstreamhelper.hxx"
#include "vcl/bmpacc.hxx"
#include "vcl/cvtgrf.hxx"
#include "vcl/mapmod.hxx"
#include "vcl/mapunit.hxx"
#include "vcl/stdtext.hxx"
#include "vcl/timer.hxx"
#include "vcl/wintypes.hxx"
#include "vos/mutex.hxx"
#include "vos/thread.hxx"
//---MARKER---
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: CheckBox.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2004-04-02 10:49:21 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _FORMS_CHECKBOX_HXX_
#define _FORMS_CHECKBOX_HXX_
#ifndef _FORMS_FORMCOMPONENT_HXX_
#include "FormComponent.hxx"
#endif
#ifndef _COMPHELPER_PROPERTY_MULTIPLEX_HXX_
#include <comphelper/propmultiplex.hxx>
#endif
//.........................................................................
namespace frm
{
enum { CB_NOCHECK, CB_CHECK, CB_DONTKNOW };
//==================================================================
//= OCheckBoxModel
//==================================================================
class OCheckBoxModel :public OBoundControlModel
,public ::comphelper::OAggregationArrayUsageHelper< OCheckBoxModel >
{
::rtl::OUString m_sReferenceValue; // Referenzwert zum Checken des Buttons
sal_Int16 m_nDefaultChecked; // Soll beim Reset gecheckt werden ?
protected:
sal_Int16 getState(const ::com::sun::star::uno::Any& rValue);
public:
DECLARE_DEFAULT_LEAF_XTOR( OCheckBoxModel );
// XServiceInfo
IMPLEMENTATION_NAME(OCheckBoxModel);
virtual StringSequence SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);
// OPropertySetHelper
virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle) const;
virtual void SAL_CALL setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue )
throw (::com::sun::star::uno::Exception);
virtual sal_Bool SAL_CALL convertFastPropertyValue(
::com::sun::star::uno::Any& _rConvertedValue, ::com::sun::star::uno::Any& _rOldValue, sal_Int32 _nHandle, const ::com::sun::star::uno::Any& _rValue )
throw (::com::sun::star::lang::IllegalArgumentException);
// XPropertySetRef
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo> SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException);
virtual cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();
// XPersistObject
virtual ::rtl::OUString SAL_CALL getServiceName() throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
// OAggregationArrayUsageHelper
virtual void fillProperties(
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps,
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rAggregateProps
) const;
IMPLEMENT_INFO_SERVICE()
protected:
DECLARE_XCLONEABLE();
// OBoundControlModel overridables
virtual ::com::sun::star::uno::Any
translateDbColumnToControlValue( );
virtual sal_Bool commitControlValueToDbColumn( bool _bPostReset );
virtual ::com::sun::star::uno::Any
translateExternalValueToControlValue( );
virtual ::com::sun::star::uno::Any
translateControlValueToExternalValue( );
virtual ::com::sun::star::uno::Any
getDefaultForReset() const;
virtual void onConnectedDbColumn( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxForm );
virtual sal_Bool approveValueBinding( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XValueBinding >& _rxBinding );
};
//==================================================================
//= OCheckBoxControl
//==================================================================
class OCheckBoxControl : public OBoundControl
{
public:
OCheckBoxControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory);
// XServiceInfo
IMPLEMENTATION_NAME(OCheckBoxControl);
virtual StringSequence SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);
};
//.........................................................................
}
//.........................................................................
#endif // _FORMS_CHECKBOX_HXX_
<commit_msg>INTEGRATION: CWS eforms2 (1.7.4); FILE MERGED 2004/05/12 08:15:06 fs 1.7.4.1: #116712# outsourced common refvalue-associated behavior to a base class<commit_after>/*************************************************************************
*
* $RCSfile: CheckBox.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2004-11-16 10:35:44 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _FORMS_CHECKBOX_HXX_
#define _FORMS_CHECKBOX_HXX_
#ifndef EFORMS2_FORMS_SOURCE_COMPONENT_REFVALUECOMPONENT_HXX
#include "refvaluecomponent.hxx"
#endif
//.........................................................................
namespace frm
{
//==================================================================
//= OCheckBoxModel
//==================================================================
class OCheckBoxModel :public OReferenceValueComponent
,public ::comphelper::OAggregationArrayUsageHelper< OCheckBoxModel >
{
protected:
sal_Int16 getState(const ::com::sun::star::uno::Any& rValue);
public:
DECLARE_DEFAULT_LEAF_XTOR( OCheckBoxModel );
// XServiceInfo
IMPLEMENTATION_NAME(OCheckBoxModel);
virtual StringSequence SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);
// XPropertySetRef
virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo> SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException);
virtual cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();
// XPersistObject
virtual ::rtl::OUString SAL_CALL getServiceName() throw(::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL
read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw(::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
// OAggregationArrayUsageHelper
virtual void fillProperties(
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps,
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rAggregateProps
) const;
IMPLEMENT_INFO_SERVICE()
protected:
DECLARE_XCLONEABLE();
// OBoundControlModel overridables
virtual ::com::sun::star::uno::Any
translateDbColumnToControlValue( );
virtual sal_Bool commitControlValueToDbColumn( bool _bPostReset );
};
//==================================================================
//= OCheckBoxControl
//==================================================================
class OCheckBoxControl : public OBoundControl
{
public:
OCheckBoxControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory);
// XServiceInfo
IMPLEMENTATION_NAME(OCheckBoxControl);
virtual StringSequence SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);
};
//.........................................................................
}
//.........................................................................
#endif // _FORMS_CHECKBOX_HXX_
<|endoftext|>
|
<commit_before>//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#include "NeonPadWorkload.hpp"
#include <neon/NeonTensorHandle.hpp>
#include <aclCommon/ArmComputeTensorUtils.hpp>
#include <arm_compute/core/Types.h>
#include <arm_compute/runtime/NEON/functions/NEPadLayer.h>
#include "NeonWorkloadUtils.hpp"
namespace armnn
{
using namespace armcomputetensorutils;
NeonPadWorkload::NeonPadWorkload(const PadQueueDescriptor& descriptor, const WorkloadInfo& info)
: BaseWorkload<PadQueueDescriptor>(descriptor, info)
{
m_Data.ValidateInputsOutputs("NeonPadWorkload", 1, 1);
arm_compute::ITensor& input = static_cast<INeonTensorHandle*>(m_Data.m_Inputs[0])->GetTensor();
arm_compute::ITensor& output = static_cast<INeonTensorHandle*>(m_Data.m_Outputs[0])->GetTensor();
std::vector<std::pair<unsigned int, unsigned int>> reversed_PadList(descriptor.m_Parameters.m_PadList.size());
std::reverse_copy(std::begin(descriptor.m_Parameters.m_PadList),
std::end(descriptor.m_Parameters.m_PadList),
std::begin(reversed_PadList));
arm_compute::PaddingList padList = static_cast<arm_compute::PaddingList>(reversed_PadList);
auto layer = std::make_unique<arm_compute::NEPadLayer>();
layer->configure(&input, &output, padList);
m_Layer.reset(layer.release());
}
void NeonPadWorkload::Execute() const
{
ARMNN_SCOPED_PROFILING_EVENT_NEON("NeonPadWorkload_Execute");
m_Layer->run();
}
arm_compute::Status NeonPadWorkloadValidate(const TensorInfo& input,
const TensorInfo& output,
const PadDescriptor& descriptor)
{
const arm_compute::TensorInfo aclInputInfo = BuildArmComputeTensorInfo(input);
const arm_compute::TensorInfo aclOutputInfo = BuildArmComputeTensorInfo(output);
arm_compute::PaddingList padList = static_cast<arm_compute::PaddingList>(descriptor.m_PadList);
return arm_compute::NEPadLayer::validate(&aclInputInfo, &aclOutputInfo, padList);
}
} // namespace armnn
<commit_msg>MLCE-90 Fixing issues with NEON pad tests<commit_after>//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#include "NeonPadWorkload.hpp"
#include <neon/NeonTensorHandle.hpp>
#include <aclCommon/ArmComputeTensorUtils.hpp>
#include <arm_compute/core/Types.h>
#include <arm_compute/runtime/NEON/functions/NEPadLayer.h>
#include "NeonWorkloadUtils.hpp"
namespace armnn
{
using namespace armcomputetensorutils;
NeonPadWorkload::NeonPadWorkload(const PadQueueDescriptor& descriptor, const WorkloadInfo& info)
: BaseWorkload<PadQueueDescriptor>(descriptor, info)
{
m_Data.ValidateInputsOutputs("NeonPadWorkload", 1, 1);
arm_compute::ITensor& input = static_cast<INeonTensorHandle*>(m_Data.m_Inputs[0])->GetTensor();
arm_compute::ITensor& output = static_cast<INeonTensorHandle*>(m_Data.m_Outputs[0])->GetTensor();
std::vector<std::pair<unsigned int, unsigned int>> reversed_PadList(descriptor.m_Parameters.m_PadList.size());
std::reverse_copy(std::begin(descriptor.m_Parameters.m_PadList),
std::end(descriptor.m_Parameters.m_PadList),
std::begin(reversed_PadList));
arm_compute::PaddingList padList = static_cast<arm_compute::PaddingList>(reversed_PadList);
auto layer = std::make_unique<arm_compute::NEPadLayer>();
layer->configure(&input, &output, padList);
m_Layer.reset(layer.release());
}
void NeonPadWorkload::Execute() const
{
ARMNN_SCOPED_PROFILING_EVENT_NEON("NeonPadWorkload_Execute");
m_Layer->run();
}
arm_compute::Status NeonPadWorkloadValidate(const TensorInfo& input,
const TensorInfo& output,
const PadDescriptor& descriptor)
{
const arm_compute::TensorInfo aclInputInfo = BuildArmComputeTensorInfo(input);
const arm_compute::TensorInfo aclOutputInfo = BuildArmComputeTensorInfo(output);
std::vector<std::pair<unsigned int, unsigned int>> reversed_PadList(descriptor.m_PadList.size());
std::reverse_copy(std::begin(descriptor.m_PadList),
std::end(descriptor.m_PadList),
std::begin(reversed_PadList));
arm_compute::PaddingList padList = static_cast<arm_compute::PaddingList>(reversed_PadList);
return arm_compute::NEPadLayer::validate(&aclInputInfo, &aclOutputInfo, padList);
}
} // namespace armnn
<|endoftext|>
|
<commit_before>/*
* JPetWriter.cpp
*
*
* Created by Karol Stola on 13-09-02.
* Copyright 2013 __MyCompanyName__. All rights reserved.
*
*/
#include "JPetWriter.h"
//TFile* JPetWriter::fFile = NULL;
JPetWriter::JPetWriter(const char* file_name)
: fFileName(file_name, "UPDATE") // string z nazwą pliku
, fFile(fFileName.c_str()) // plik
{
if ( fFile.IsZombie() ){
ERROR("Could not open file to write.");
this->~JPetWriter();
}
}
bool JPetWriter::Write(const TNamed& obj){
vector<TNamed> wrapper;
wrapper.push_back(obj);
Write(wrapper);
}
void JPetWriter::CloseFile(){
if (fFile.IsOpen() ) fFile.Close();
}
bool JPetWriter::Write( vector<TNamed>& obj) {
if (obj.size() == 0) {
WARNING("Vector passed is empty");
return false;
}
if ( !fFile.IsOpen() ) {
ERROR("Could not write to file. Have you closed it already?");
return false;
}
fFile.cd(fFileName.c_str()); // -> http://root.cern.ch/drupal/content/current-directory
TTree tree;
TNamed& filler = obj[0];
tree.Branch(filler.GetName(), filler.GetName(), &filler);
for (int i = 0; i < obj.size(); i++){
filler = obj[i];
tree.Fill();
}
tree.Write();
return true;
}
JPetWriter::~JPetWriter(){
CloseFile();
}
<commit_msg>usunięcie wywołania destruktora we writerze.<commit_after>/*
* JPetWriter.cpp
*
*
* Created by Karol Stola on 13-09-02.
* Copyright 2013 __MyCompanyName__. All rights reserved.
*
*/
#include "JPetWriter.h"
//TFile* JPetWriter::fFile = NULL;
JPetWriter::JPetWriter(const char* file_name)
: fFileName(file_name, "UPDATE") // string z nazwą pliku
, fFile(fFileName.c_str()) // plik
{
if ( fFile.IsZombie() ){
ERROR("Could not open file to write.");
}
}
bool JPetWriter::Write(const TNamed& obj){
vector<TNamed> wrapper;
wrapper.push_back(obj);
Write(wrapper);
}
void JPetWriter::CloseFile(){
if (fFile.IsOpen() ) fFile.Close();
}
bool JPetWriter::Write( vector<TNamed>& obj) {
if (obj.size() == 0) {
WARNING("Vector passed is empty");
return false;
}
if ( !fFile.IsOpen() ) {
ERROR("Could not write to file. Have you closed it already?");
return false;
}
fFile.cd(fFileName.c_str()); // -> http://root.cern.ch/drupal/content/current-directory
TTree tree;
TNamed& filler = obj[0];
tree.Branch(filler.GetName(), filler.GetName(), &filler);
for (int i = 0; i < obj.size(); i++){
filler = obj[i];
tree.Fill();
}
tree.Write();
return true;
}
JPetWriter::~JPetWriter(){
CloseFile();
}
<|endoftext|>
|
<commit_before>#include <sstream>
#include <string>
#include <libHierGA/HierGA.hpp>
#include "1maxFitness.hpp"
using namespace std;
OneMaxFitness::OneMaxFitness() : ObjectiveFunction() {}
float OneMaxFitness::checkFitness(Genome * genome) {
unsigned total = 0;
Genome flattened = genome->flattenGenome();
for (unsigned int i = 0; i < 32; i++)
total += flattened.getIndex<int>(i);
return total;
}
string OneMaxToString::toString(Genome * genome) {
stringstream ss;
Genome flattened = genome->flattenGenome();
for (unsigned int i = 0; i < 32; i++)
ss << flattened.getIndex<int>(i);
return ss.str();
}
<commit_msg>[1max Fitness]: Fixed segfault<commit_after>#include <sstream>
#include <string>
#include <libHierGA/HierGA.hpp>
#include "1maxFitness.hpp"
using namespace std;
OneMaxFitness::OneMaxFitness() : ObjectiveFunction() {}
float OneMaxFitness::checkFitness(Genome * genome) {
unsigned total = 0;
Genome flattened = genome->flattenGenome();
for (unsigned int i = 0; i < 32 && i < genome->genomeLength(); i++)
total += flattened.getIndex<int>(i);
return total;
}
string OneMaxToString::toString(Genome * genome) {
stringstream ss;
Genome flattened = genome->flattenGenome();
for (unsigned int i = 0; i < 32 && i < genome->genomeLength(); i++)
ss << flattened.getIndex<int>(i);
return ss.str();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 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 "base/basictypes.h"
#include "base/file_path.h"
#include "base/path_service.h"
#include "base/utf_string_conversions.h"
#include "base/string_util.h"
#include "chrome/browser/view_ids.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "chrome/test/ui/ui_layout_test.h"
#include "net/base/net_util.h"
namespace {
const wchar_t kPlaying[] = L"PLAYING";
const wchar_t kReady[] = L"READY";
const wchar_t kFullScreen[] = L"FULLSCREEN";
} // namespace
class MediaBrowserTest : public InProcessBrowserTest {
protected:
MediaBrowserTest() {
set_show_window(true);
}
virtual void SetUpCommandLine(CommandLine* command_line) {
command_line->AppendSwitch(switches::kEnableVideoFullscreen);
}
void PlayMedia(const char* tag, const char* media_file) {
FilePath test_file;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_file));
test_file = test_file.AppendASCII("media/player.html");
GURL player_gurl = net::FilePathToFileURL(test_file);
std::string url = StringPrintf("%s?%s=%s",
player_gurl.spec().c_str(),
tag,
media_file);
ui_test_utils::NavigateToURL(browser(), GURL(url));
// Allow the media file to be loaded.
ui_test_utils::WaitForNotification(
NotificationType::TAB_CONTENTS_TITLE_UPDATED);
string16 title;
ui_test_utils::GetCurrentTabTitle(browser(), &title);
EXPECT_EQ(WideToUTF16(kPlaying), title);
}
void PlayAudio(const char* url) {
PlayMedia("audio", url);
}
void PlayVideo(const char* url) {
PlayMedia("video", url);
}
void PlayVideoFullScreen(const char* media_file) {
FilePath test_file;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_file));
test_file = test_file.AppendASCII("media/player_fullscreen.html");
GURL player_gurl = net::FilePathToFileURL(test_file);
std::string url = StringPrintf("%s?%s",
player_gurl.spec().c_str(),
media_file);
ui_test_utils::NavigateToURL(browser(), GURL(url));
ui_test_utils::WaitForNotification(
NotificationType::TAB_CONTENTS_TITLE_UPDATED);
string16 title;
ui_test_utils::GetCurrentTabTitle(browser(), &title);
EXPECT_EQ(WideToUTF16(kReady), title);
ui_test_utils::ClickOnView(browser(), VIEW_ID_TAB_CONTAINER);
ui_test_utils::WaitForNotification(
NotificationType::TAB_CONTENTS_TITLE_UPDATED);
ui_test_utils::GetCurrentTabTitle(browser(), &title);
EXPECT_EQ(WideToUTF16(kFullScreen), title);
}
};
IN_PROC_BROWSER_TEST_F(MediaBrowserTest, VideoBearTheora) {
PlayVideo("bear.ogv");
}
IN_PROC_BROWSER_TEST_F(MediaBrowserTest, VideoBearSilentTheora) {
PlayVideo("bear_silent.ogv");
}
IN_PROC_BROWSER_TEST_F(MediaBrowserTest, VideoBearWebm) {
PlayVideo("bear.webm");
}
IN_PROC_BROWSER_TEST_F(MediaBrowserTest, VideoBearSilentWebm) {
PlayVideo("bear_silent.webm");
}
#if defined(GOOGLE_CHROME_BUILD) || defined(USE_PROPRIETARY_CODECS)
TEST_F(MediaBrowserTest, VideoBearMp4) {
PlayVideo("bear.mp4");
}
TEST_F(MediaBrowserTest, VideoBearSilentMp4) {
PlayVideo("bear_silent.mp4");
}
#endif
// TODO(imcheng): Disabled until fullscreen Webkit patch is here - See
// http://crbug.com/54838.
// (Does Mac have fullscreen?)
#if defined(OS_WIN) || defined(OS_LINUX)
IN_PROC_BROWSER_TEST_F(MediaBrowserTest, DISABLED_VideoBearFullScreen) {
PlayVideoFullScreen("bear.ogv");
}
#endif // defined(OS_WIN) || defined(OS_LINUX)
TEST_F(UILayoutTest, MediaUILayoutTest) {
static const char* kResources[] = {
"content",
"media-file.js",
"media-fullscreen.js",
"video-paint-test.js",
"video-played.js",
"video-test.js",
};
static const char* kMediaTests[] = {
"video-autoplay.html",
// "video-loop.html", disabled due to 52887.
"video-no-autoplay.html",
// TODO(sergeyu): Add more tests here.
};
FilePath test_dir;
FilePath media_test_dir;
media_test_dir = media_test_dir.AppendASCII("media");
InitializeForLayoutTest(test_dir, media_test_dir, kNoHttpPort);
// Copy resources first.
for (size_t i = 0; i < arraysize(kResources); ++i)
AddResourceForLayoutTest(
test_dir, media_test_dir.AppendASCII(kResources[i]));
for (size_t i = 0; i < arraysize(kMediaTests); ++i)
RunLayoutTest(kMediaTests[i], kNoHttpPort);
}
<commit_msg>Mark MediaBrowserTest.VideoBearTheora as FLAKY on Mac OS.<commit_after>// Copyright (c) 2009 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 "base/basictypes.h"
#include "base/file_path.h"
#include "base/path_service.h"
#include "base/utf_string_conversions.h"
#include "base/string_util.h"
#include "chrome/browser/view_ids.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "chrome/test/ui/ui_layout_test.h"
#include "net/base/net_util.h"
namespace {
const wchar_t kPlaying[] = L"PLAYING";
const wchar_t kReady[] = L"READY";
const wchar_t kFullScreen[] = L"FULLSCREEN";
} // namespace
class MediaBrowserTest : public InProcessBrowserTest {
protected:
MediaBrowserTest() {
set_show_window(true);
}
virtual void SetUpCommandLine(CommandLine* command_line) {
command_line->AppendSwitch(switches::kEnableVideoFullscreen);
}
void PlayMedia(const char* tag, const char* media_file) {
FilePath test_file;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_file));
test_file = test_file.AppendASCII("media/player.html");
GURL player_gurl = net::FilePathToFileURL(test_file);
std::string url = StringPrintf("%s?%s=%s",
player_gurl.spec().c_str(),
tag,
media_file);
ui_test_utils::NavigateToURL(browser(), GURL(url));
// Allow the media file to be loaded.
ui_test_utils::WaitForNotification(
NotificationType::TAB_CONTENTS_TITLE_UPDATED);
string16 title;
ui_test_utils::GetCurrentTabTitle(browser(), &title);
EXPECT_EQ(WideToUTF16(kPlaying), title);
}
void PlayAudio(const char* url) {
PlayMedia("audio", url);
}
void PlayVideo(const char* url) {
PlayMedia("video", url);
}
void PlayVideoFullScreen(const char* media_file) {
FilePath test_file;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_file));
test_file = test_file.AppendASCII("media/player_fullscreen.html");
GURL player_gurl = net::FilePathToFileURL(test_file);
std::string url = StringPrintf("%s?%s",
player_gurl.spec().c_str(),
media_file);
ui_test_utils::NavigateToURL(browser(), GURL(url));
ui_test_utils::WaitForNotification(
NotificationType::TAB_CONTENTS_TITLE_UPDATED);
string16 title;
ui_test_utils::GetCurrentTabTitle(browser(), &title);
EXPECT_EQ(WideToUTF16(kReady), title);
ui_test_utils::ClickOnView(browser(), VIEW_ID_TAB_CONTAINER);
ui_test_utils::WaitForNotification(
NotificationType::TAB_CONTENTS_TITLE_UPDATED);
ui_test_utils::GetCurrentTabTitle(browser(), &title);
EXPECT_EQ(WideToUTF16(kFullScreen), title);
}
};
// Crashes on Mac OS (http://crbug.com/54939)
#if defined(OS_MACOSX)
#define MAYBE_VideoBearTheora FLAKY_VideoBearTheora
#else
#define MAYBE_VideoBearTheora VideoBearTheora
#endif
IN_PROC_BROWSER_TEST_F(MediaBrowserTest, MAYBE_VideoBearTheora) {
PlayVideo("bear.ogv");
}
IN_PROC_BROWSER_TEST_F(MediaBrowserTest, VideoBearSilentTheora) {
PlayVideo("bear_silent.ogv");
}
IN_PROC_BROWSER_TEST_F(MediaBrowserTest, VideoBearWebm) {
PlayVideo("bear.webm");
}
IN_PROC_BROWSER_TEST_F(MediaBrowserTest, VideoBearSilentWebm) {
PlayVideo("bear_silent.webm");
}
#if defined(GOOGLE_CHROME_BUILD) || defined(USE_PROPRIETARY_CODECS)
TEST_F(MediaBrowserTest, VideoBearMp4) {
PlayVideo("bear.mp4");
}
TEST_F(MediaBrowserTest, VideoBearSilentMp4) {
PlayVideo("bear_silent.mp4");
}
#endif
// TODO(imcheng): Disabled until fullscreen Webkit patch is here - See
// http://crbug.com/54838.
// (Does Mac have fullscreen?)
#if defined(OS_WIN) || defined(OS_LINUX)
IN_PROC_BROWSER_TEST_F(MediaBrowserTest, DISABLED_VideoBearFullScreen) {
PlayVideoFullScreen("bear.ogv");
}
#endif // defined(OS_WIN) || defined(OS_LINUX)
TEST_F(UILayoutTest, MediaUILayoutTest) {
static const char* kResources[] = {
"content",
"media-file.js",
"media-fullscreen.js",
"video-paint-test.js",
"video-played.js",
"video-test.js",
};
static const char* kMediaTests[] = {
"video-autoplay.html",
// "video-loop.html", disabled due to 52887.
"video-no-autoplay.html",
// TODO(sergeyu): Add more tests here.
};
FilePath test_dir;
FilePath media_test_dir;
media_test_dir = media_test_dir.AppendASCII("media");
InitializeForLayoutTest(test_dir, media_test_dir, kNoHttpPort);
// Copy resources first.
for (size_t i = 0; i < arraysize(kResources); ++i)
AddResourceForLayoutTest(
test_dir, media_test_dir.AppendASCII(kResources[i]));
for (size_t i = 0; i < arraysize(kMediaTests); ++i)
RunLayoutTest(kMediaTests[i], kNoHttpPort);
}
<|endoftext|>
|
<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File Points1D.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: C functions to provide access to managers.
//
///////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <Loki/Singleton.h>
#include <LibUtilities/Foundations/GaussPoints.h>
#include <LibUtilities/Foundations/FourierPoints.h>
#include <LibUtilities/Foundations/PolyEPoints.h>
#include <LibUtilities/Foundations/Basis.h>
#include <LibUtilities/Foundations/Foundations.hpp>
#include <LibUtilities/BasicUtils/ErrorUtil.hpp>
#include <LibUtilities/Foundations/ManagerAccess.h>
namespace Nektar
{
namespace LibUtilities
{
// Register all points and basis creators.
namespace
{
const bool gaussInited1 = PointsManager().RegisterCreator(PointsKey(0, eGaussGaussLegendre), GaussPoints::Create);
const bool gaussInited2 = PointsManager().RegisterCreator(PointsKey(0, eGaussRadauMLegendre), GaussPoints::Create);
const bool gaussInited3 = PointsManager().RegisterCreator(PointsKey(0, eGaussRadauPLegendre), GaussPoints::Create);
const bool gaussInited4 = PointsManager().RegisterCreator(PointsKey(0, eGaussLobattoLegendre), GaussPoints::Create);
const bool gaussInited5 = PointsManager().RegisterCreator(PointsKey(0, eGaussGaussChebyshev), GaussPoints::Create);
const bool gaussInited6 = PointsManager().RegisterCreator(PointsKey(0, eGaussRadauMChebyshev), GaussPoints::Create);
const bool gaussInited7 = PointsManager().RegisterCreator(PointsKey(0, eGaussRadauPChebyshev), GaussPoints::Create);
const bool gaussInited8 = PointsManager().RegisterCreator(PointsKey(0, eGaussLobattoChebyshev), GaussPoints::Create);
const bool gaussInited9 = PointsManager().RegisterCreator(PointsKey(0, eGaussRadauMAlpha0Beta1), GaussPoints::Create);
const bool gaussInited10 = PointsManager().RegisterCreator(PointsKey(0, eGaussRadauMAlpha0Beta2), GaussPoints::Create);
const bool fourierInited0 = PointsManager().RegisterCreator(PointsKey(0, eFourierEvenlySpaced), FourierPoints::Create);
const bool polyeInited10 = PointsManager().RegisterCreator(PointsKey(0, ePolyEvenlySpaced), PolyEPoints::Create);
const bool Ortho_A_Inited = BasisManager().RegisterCreator(BasisKey(eOrtho_A, 0, NullPointsKey), Basis::Create);
const bool Ortho_B_Inited = BasisManager().RegisterCreator(BasisKey(eOrtho_B, 0, NullPointsKey), Basis::Create);
const bool Ortho_C_Inited = BasisManager().RegisterCreator(BasisKey(eOrtho_C, 0, NullPointsKey), Basis::Create);
const bool Modified_A_Inited = BasisManager().RegisterCreator(BasisKey(eModified_A, 0, NullPointsKey), Basis::Create);
const bool Modified_B_Inited = BasisManager().RegisterCreator(BasisKey(eModified_B, 0, NullPointsKey), Basis::Create);
const bool Modified_C_Inited = BasisManager().RegisterCreator(BasisKey(eModified_C, 0, NullPointsKey), Basis::Create);
const bool Fourier_Inited = BasisManager().RegisterCreator(BasisKey(eFourier, 0, NullPointsKey), Basis::Create);
const bool GLL_Lagrange_Inited = BasisManager().RegisterCreator(BasisKey(eGLL_Lagrange, 0, NullPointsKey), Basis::Create);
const bool Legendre_Inited = BasisManager().RegisterCreator(BasisKey(eLegendre, 0, NullPointsKey), Basis::Create);
const bool Chebyshev_Inited = BasisManager().RegisterCreator(BasisKey(eChebyshev, 0, NullPointsKey), Basis::Create);
};
PointsManagerT &PointsManager(void)
{
return Loki::SingletonHolder<PointsManagerT>::Instance();
}
BasisManagerT &BasisManager(void)
{
return Loki::SingletonHolder<BasisManagerT>::Instance();
}
} // end of namespace LibUtilities
} // end of namespace Nektar
/**
$Log: ManagerAccess.cpp,v $
Revision 1.6 2007/03/13 16:59:04 kirby
added GaussLobattoChebyshev -- we had forgotten it
Revision 1.5 2007/02/26 15:52:31 sherwin
Working version for Fourier points calling from StdRegions. Fourier interpolations not working yet
Revision 1.4 2007/02/06 17:12:31 jfrazier
Fixed a problem with global initialization in libraries.
Revision 1.3 2007/02/01 23:28:42 jfrazier
Basis is not working, but not fully tested.
Revision 1.2 2007/01/20 21:45:59 kirby
*** empty log message ***
Revision 1.1 2007/01/19 18:02:26 jfrazier
Initial checkin.
**/
<commit_msg>*** empty log message ***<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// File Points1D.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// Description: C functions to provide access to managers.
//
///////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <Loki/Singleton.h>
#include <LibUtilities/Foundations/GaussPoints.h>
#include <LibUtilities/Foundations/FourierPoints.h>
#include <LibUtilities/Foundations/PolyEPoints.h>
#include <LibUtilities/Foundations/Basis.h>
#include <LibUtilities/Foundations/Foundations.hpp>
#include <LibUtilities/BasicUtils/ErrorUtil.hpp>
#include <LibUtilities/Foundations/ManagerAccess.h>
namespace Nektar
{
namespace LibUtilities
{
// Register all points and basis creators.
namespace
{
const bool gaussInited1 = PointsManager().RegisterCreator(PointsKey(0, eGaussGaussLegendre), GaussPoints::Create);
const bool gaussInited2 = PointsManager().RegisterCreator(PointsKey(0, eGaussRadauMLegendre), GaussPoints::Create);
const bool gaussInited3 = PointsManager().RegisterCreator(PointsKey(0, eGaussRadauPLegendre), GaussPoints::Create);
const bool gaussInited4 = PointsManager().RegisterCreator(PointsKey(0, eGaussLobattoLegendre), GaussPoints::Create);
const bool gaussInited5 = PointsManager().RegisterCreator(PointsKey(0, eGaussGaussChebyshev), GaussPoints::Create);
const bool gaussInited6 = PointsManager().RegisterCreator(PointsKey(0, eGaussRadauMChebyshev), GaussPoints::Create);
const bool gaussInited7 = PointsManager().RegisterCreator(PointsKey(0, eGaussRadauPChebyshev), GaussPoints::Create);
const bool gaussInited8 = PointsManager().RegisterCreator(PointsKey(0, eGaussLobattoChebyshev), GaussPoints::Create);
const bool gaussInited9 = PointsManager().RegisterCreator(PointsKey(0, eGaussRadauMAlpha0Beta1), GaussPoints::Create);
const bool gaussInited10 = PointsManager().RegisterCreator(PointsKey(0, eGaussRadauMAlpha0Beta2), GaussPoints::Create);
const bool fourierInited0 = PointsManager().RegisterCreator(PointsKey(0, eFourierEvenlySpaced), FourierPoints::Create);
const bool polyeInited10 = PointsManager().RegisterCreator(PointsKey(0, ePolyEvenlySpaced), PolyEPoints::Create);
const bool Ortho_A_Inited = BasisManager().RegisterCreator(BasisKey(eOrtho_A, 0, NullPointsKey), Basis::Create);
const bool Ortho_B_Inited = BasisManager().RegisterCreator(BasisKey(eOrtho_B, 0, NullPointsKey), Basis::Create);
const bool Ortho_C_Inited = BasisManager().RegisterCreator(BasisKey(eOrtho_C, 0, NullPointsKey), Basis::Create);
const bool Modified_A_Inited = BasisManager().RegisterCreator(BasisKey(eModified_A, 0, NullPointsKey), Basis::Create);
const bool Modified_B_Inited = BasisManager().RegisterCreator(BasisKey(eModified_B, 0, NullPointsKey), Basis::Create);
const bool Modified_C_Inited = BasisManager().RegisterCreator(BasisKey(eModified_C, 0, NullPointsKey), Basis::Create);
const bool Fourier_Inited = BasisManager().RegisterCreator(BasisKey(eFourier, 0, NullPointsKey), Basis::Create);
const bool GLL_Lagrange_Inited = BasisManager().RegisterCreator(BasisKey(eGLL_Lagrange, 0, NullPointsKey), Basis::Create);
const bool Legendre_Inited = BasisManager().RegisterCreator(BasisKey(eLegendre, 0, NullPointsKey), Basis::Create);
const bool Chebyshev_Inited = BasisManager().RegisterCreator(BasisKey(eChebyshev, 0, NullPointsKey), Basis::Create);
};
PointsManagerT &PointsManager(void)
{
return Loki::SingletonHolder<PointsManagerT>::Instance();
}
BasisManagerT &BasisManager(void)
{
return Loki::SingletonHolder<BasisManagerT>::Instance();
}
} // end of namespace LibUtilities
} // end of namespace Nektar
/**
$Log: ManagerAccess.cpp,v $
Revision 1.7 2007/03/13 21:31:32 kirby
small update to the numbering.
Revision 1.6 2007/03/13 16:59:04 kirby
added GaussLobattoChebyshev -- we had forgotten it
Revision 1.5 2007/02/26 15:52:31 sherwin
Working version for Fourier points calling from StdRegions. Fourier interpolations not working yet
Revision 1.4 2007/02/06 17:12:31 jfrazier
Fixed a problem with global initialization in libraries.
Revision 1.3 2007/02/01 23:28:42 jfrazier
Basis is not working, but not fully tested.
Revision 1.2 2007/01/20 21:45:59 kirby
*** empty log message ***
Revision 1.1 2007/01/19 18:02:26 jfrazier
Initial checkin.
**/
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: IBM Corporation
*
* Copyright: 2008 by IBM Corporation
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
/*************************************************************************
* @file
* ruby style.
************************************************************************/
#ifndef _XFRUBYSTYLE_HXX
#define _XFRUBYSTYLE_HXX
#include "xfglobal.hxx"
#include "xfstyle.hxx"
#include "xfdefs.hxx"
class XFRubyStyle : public XFStyle
{
public:
XFRubyStyle(){}
virtual ~XFRubyStyle(){}
virtual void ToXml(IXFStream *strm);
void SetPosition(enumXFRubyPosition ePosition);
void SetAlignment(enumXFRubyPosition eAlignment);
enumXFStyle GetStyleFamily();
private:
enumXFRubyPosition m_ePos;
enumXFRubyPosition m_eAlign;
};
void XFRubyStyle::SetPosition(enumXFRubyPosition ePosition)
{
m_ePos = ePosition;
}
void XFRubyStyle::SetAlignment(enumXFRubyPosition eAlignment)
{
m_eAlign = eAlignment;
}
enumXFStyle XFRubyStyle::GetStyleFamily()
{
return enumXFStyleRuby;
}
void XFRubyStyle::ToXml(IXFStream *pStrm)
{
IXFAttrList *pAttrList = pStrm->GetAttrList();
OUString style = GetStyleName();
pAttrList->Clear();
if( !style.isEmpty() )
pAttrList->AddAttribute(A2OUSTR("style:name"),GetStyleName());
pAttrList->AddAttribute(A2OUSTR("style:family"), A2OUSTR("ruby"));
pStrm->StartElement(A2OUSTR("style:style"));
pAttrList->Clear();
OUString sPos;
if (m_eAlign == enumXFRubyLeft)
{
sPos = A2OUSTR("left");
}
else if(m_eAlign == enumXFRubyRight)
{
sPos = A2OUSTR("right");
}
else if(m_eAlign == enumXFRubyCenter)
{
sPos = A2OUSTR("center");
}
if (!sPos.isEmpty())
pAttrList->AddAttribute(A2OUSTR("style:ruby-align"),sPos);
OUString sAlign;
if (m_ePos == enumXFRubyTop)
{
sAlign = A2OUSTR("above");
}
else if(m_ePos == enumXFRubyBottom)
{
sAlign = A2OUSTR("below");
}
if (!sAlign.isEmpty())
pAttrList->AddAttribute(A2OUSTR("style:ruby-position"),sAlign);
pStrm->StartElement(A2OUSTR("style:properties"));
pStrm->EndElement(A2OUSTR("style:properties"));
pStrm->EndElement(A2OUSTR("style:style"));
}
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#738773 Uninitialized scalar field<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 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
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: IBM Corporation
*
* Copyright: 2008 by IBM Corporation
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
/*************************************************************************
* @file
* ruby style.
************************************************************************/
#ifndef _XFRUBYSTYLE_HXX
#define _XFRUBYSTYLE_HXX
#include "xfglobal.hxx"
#include "xfstyle.hxx"
#include "xfdefs.hxx"
class XFRubyStyle : public XFStyle
{
public:
XFRubyStyle()
: m_ePos(enumXFRubyLeft)
, m_eAlign(enumXFRubyLeft)
{
}
virtual ~XFRubyStyle(){}
virtual void ToXml(IXFStream *strm);
void SetPosition(enumXFRubyPosition ePosition);
void SetAlignment(enumXFRubyPosition eAlignment);
enumXFStyle GetStyleFamily();
private:
enumXFRubyPosition m_ePos;
enumXFRubyPosition m_eAlign;
};
void XFRubyStyle::SetPosition(enumXFRubyPosition ePosition)
{
m_ePos = ePosition;
}
void XFRubyStyle::SetAlignment(enumXFRubyPosition eAlignment)
{
m_eAlign = eAlignment;
}
enumXFStyle XFRubyStyle::GetStyleFamily()
{
return enumXFStyleRuby;
}
void XFRubyStyle::ToXml(IXFStream *pStrm)
{
IXFAttrList *pAttrList = pStrm->GetAttrList();
OUString style = GetStyleName();
pAttrList->Clear();
if( !style.isEmpty() )
pAttrList->AddAttribute(A2OUSTR("style:name"),GetStyleName());
pAttrList->AddAttribute(A2OUSTR("style:family"), A2OUSTR("ruby"));
pStrm->StartElement(A2OUSTR("style:style"));
pAttrList->Clear();
OUString sPos;
if (m_eAlign == enumXFRubyLeft)
{
sPos = A2OUSTR("left");
}
else if(m_eAlign == enumXFRubyRight)
{
sPos = A2OUSTR("right");
}
else if(m_eAlign == enumXFRubyCenter)
{
sPos = A2OUSTR("center");
}
if (!sPos.isEmpty())
pAttrList->AddAttribute(A2OUSTR("style:ruby-align"),sPos);
OUString sAlign;
if (m_ePos == enumXFRubyTop)
{
sAlign = A2OUSTR("above");
}
else if(m_ePos == enumXFRubyBottom)
{
sAlign = A2OUSTR("below");
}
if (!sAlign.isEmpty())
pAttrList->AddAttribute(A2OUSTR("style:ruby-position"),sAlign);
pStrm->StartElement(A2OUSTR("style:properties"));
pStrm->EndElement(A2OUSTR("style:properties"));
pStrm->EndElement(A2OUSTR("style:style"));
}
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>//---------------------------------------------------------------------------------------
// This file is part of the Lomse library.
// Lomse is copyrighted work (c) 2010-2016. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice, this
// list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// For any comment, suggestion or feature request, please contact the manager of
// the project at cecilios@users.sourceforge.net
//---------------------------------------------------------------------------------------
#include "lomse_image_reader.h"
#include "lomse_logger.h"
#include <png.h>
#include <pngconf.h>
#include <iostream>
#include <sstream>
#include <stdexcept>
using namespace std;
#include <cstdlib>
using ::malloc;
using ::free;
namespace lomse
{
//declaration of some internal functions, to avoid compiler warnings
void read_callback(png_structp png, png_bytep data, png_size_t length);
void error_callback (png_structp, png_const_charp);
//=======================================================================================
// ImageReader implementation
//=======================================================================================
SpImage ImageReader::load_image(const string& locator)
{
InputStream* pFile = nullptr;
try
{
pFile = FileSystem::open_input_stream(locator);
//find a reader that can decode the file
{
//PNG Format
PngImageDecoder decoder;
if (decoder.can_decode(pFile))
{
SpImage img = decoder.decode_file(pFile);
delete pFile;
return img;
}
}
{
//JPG Format
JpgImageDecoder decoder;
if (decoder.can_decode(pFile))
{
SpImage img = decoder.decode_file(pFile);
delete pFile;
return img;
}
}
//other formats not supported. throw error
delete pFile;
stringstream s;
s << "[ImageReader::load_image] Image format not supported. Locator: "
<< locator;
LOMSE_LOG_ERROR(s.str());
throw runtime_error(s.str());
}
catch(exception& e)
{
SpImage img( LOMSE_NEW Image() );
img->set_error_msg(e.what());
cerr << e.what() << " (catch in ImageReader::load_image)" << endl;
return img;
}
catch(...)
{
SpImage img( LOMSE_NEW Image() );
img->set_error_msg("Non-standard unknown exception");
cerr << "Non-standard unknown exception (catch in ImageReader::load_image)" << endl;
return img;
}
return SpImage( LOMSE_NEW Image() ); //compiler happy
}
//=======================================================================================
// PngImageDecoder implementation
//
// See: http://www.libpng.org/pub/png/book/chapter13.html
// http://www.piko3d.com/tutorials/libpng-tutorial-loading-png-files-from-streams
//=======================================================================================
//=======================================================================================
//some helper internal functions, not declared as protected members to avoid
//having to contaminate the lomse header files with PNG types
//=======================================================================================
void read_callback(png_structp png, png_bytep data, png_size_t length)
{
static_cast<InputStream*>( png_get_io_ptr(png) )->read(data, long(length));
}
//---------------------------------------------------------------------------------------
void error_callback (png_structp, png_const_charp)
{
LOMSE_LOG_ERROR("error reading png image");
throw "error reading png image";
}
//=======================================================================================
// PngImageDecoder members implementation
//=======================================================================================
bool PngImageDecoder::can_decode(InputStream* file)
{
//A PNG file starts with an 8-byte signature. The hexadecimal byte values are:
// 89 50 4E 47 0D 0A 1A 0A; the decimal values are 137 80 78 71 13 10 26 10.
//From http://en.wikipedia.org/wiki/Portable_Network_Graphics
unsigned char header[8];
if (file->read(header, 8) == 8 && png_check_sig(header, 8))
return true;
else
{
//TODO: rewind file
return false;
}
}
//---------------------------------------------------------------------------------------
SpImage PngImageDecoder::decode_file(InputStream* file)
{
//TODO: error checking and handling
//create an empty image to be returned when errors
Image* pImage = LOMSE_NEW Image();
//create read struct
png_structp pReadStruct = png_create_read_struct(PNG_LIBPNG_VER_STRING,
nullptr, nullptr, nullptr);
if (!pReadStruct)
{
pImage->set_error_msg("[PngImageDecoder::decode_file] out of memory creating read struct");
return SpImage(pImage);
}
//create info struct
png_infop pInfoStruct = png_create_info_struct(pReadStruct);
if (!pInfoStruct)
{
pImage->set_error_msg("[PngImageDecoder::decode_file] out of memory creating info struct");
png_destroy_read_struct(&pReadStruct, 0, 0);
return SpImage(pImage );
}
png_set_error_fn(pReadStruct, 0, error_callback, error_callback );
png_uint_32 width, height;
int bitDepth, colorType, interlaceType;
//we will take care of reading the file in our callback method
png_set_read_fn(pReadStruct, file, read_callback);
//inform about file position (we already read the 8 signature bytes)
png_set_sig_bytes(pReadStruct, 8);
//read all PNG info up to image data
png_read_info(pReadStruct, pInfoStruct);
//read image info. Don't care about compression_type and filter_type => NULLs
png_get_IHDR(pReadStruct, pInfoStruct, &width, &height, &bitDepth, &colorType,
&interlaceType, nullptr, nullptr);
//set some transformations
//expand palette images to 24-bit RGB
if (colorType == PNG_COLOR_TYPE_PALETTE)
png_set_expand(pReadStruct);
//expand low-bit-depth images to 8 bits
if (bitDepth < 8)
png_set_expand(pReadStruct);
//expand transparency chunks to full alpha channel
if (png_get_valid(pReadStruct, pInfoStruct, PNG_INFO_tRNS))
png_set_expand(pReadStruct);
//if more than 8 bits per colors, reduce to 8 bits
if (bitDepth == 16)
png_set_strip_16(pReadStruct);
//convert grayscale to RGB[A]
if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
png_set_gray_to_rgb(pReadStruct);
//TODO: gamma correction
// //if the image doesn't have gamma info, don't do any gamma correction
// if (png_get_gAMA(pReadStruct, pInfoStruct, &gamma))
// png_set_gamma(pReadStruct, display_exponent, gamma);
//set default alpha channel value to 255 (opaque)
png_set_add_alpha(pReadStruct, 0xff, PNG_FILLER_AFTER);
//all transformations have been defined.
//Now allocate a buffer for the full bitmap
unsigned char* imgbuf = nullptr;
int stride = int(width) * 4;
if ((imgbuf = (unsigned char*)malloc(height * stride)) == nullptr)
{
pImage->set_error_msg("[PngImageDecoder::decode_file] error allocating memory for image");
png_destroy_read_struct(&pReadStruct, &pInfoStruct, nullptr);
return SpImage(pImage);
}
//allocate pointers to rows
png_bytepp pRows = nullptr;
if ((pRows = (png_bytepp)malloc(height*sizeof(png_bytep))) == nullptr)
{
pImage->set_error_msg("[PngImageDecoder::decode_file] error allocating memory for line ptrs.");
png_destroy_read_struct(&pReadStruct, &pInfoStruct, nullptr);
free(imgbuf);
imgbuf = nullptr;
return SpImage(pImage);
}
//point row pointers to image buffer
png_bytep pDest = (png_bytep)imgbuf;
for (int y=0; y < int(height); ++y)
{
pRows[y] = pDest;
pDest += stride;
}
//go ahead and read the whole image
png_read_image(pReadStruct, pRows);
png_read_end(pReadStruct, pInfoStruct);
//image bitmap in RGBA format is now ready. Free memory used for row pointers
free(pRows);
pRows = nullptr;
//create the Image object
VSize bmpSize(width, height);
EPixelFormat format = k_pix_format_rgba32;
//TODO: get display reolution from lomse initialization. Here it is assumed 96 ppi
USize imgSize(float(width) * 2540.0f / 96.0f, float(height) * 2540.0f / 96.0f);
delete pImage;
pImage = LOMSE_NEW Image(imgbuf, bmpSize, format, imgSize);
//delete helper structs
png_destroy_read_struct(&pReadStruct, &pInfoStruct, 0);
//done!
return SpImage(pImage);
}
//=======================================================================================
// JpgImageDecoder implementation
//=======================================================================================
bool JpgImageDecoder::can_decode(InputStream* UNUSED(file))
{
// unsigned char hdr[2];
//
// if ( !stream.Read(hdr, WXSIZEOF(hdr)) )
// return false;
//
// return hdr[0] == 0xFF && hdr[1] == 0xD8;
////----------------------------
// const int bytesNeeded = 10;
// uint8 header [bytesNeeded];
//
// if (in.read (header, bytesNeeded) == bytesNeeded)
// {
// return header[0] == 0xff
// && header[1] == 0xd8
// && header[2] == 0xff
// && (header[3] == 0xe0 || header[3] == 0xe1);
// }
//
// return false;
return false;
}
//---------------------------------------------------------------------------------------
SpImage JpgImageDecoder::decode_file(InputStream* UNUSED(file))
{
//TODO: JpgImageDecoder::decode_file
return SpImage( LOMSE_NEW Image() );
}
} //namespace lomse
<commit_msg>Do not fail on png warnings<commit_after>//---------------------------------------------------------------------------------------
// This file is part of the Lomse library.
// Lomse is copyrighted work (c) 2010-2016. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice, this
// list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// For any comment, suggestion or feature request, please contact the manager of
// the project at cecilios@users.sourceforge.net
//---------------------------------------------------------------------------------------
#include "lomse_image_reader.h"
#include "lomse_logger.h"
#include <png.h>
#include <pngconf.h>
#include <iostream>
#include <sstream>
#include <stdexcept>
using namespace std;
#include <cstdlib>
using ::malloc;
using ::free;
namespace lomse
{
//declaration of some internal functions, to avoid compiler warnings
void read_callback(png_structp png, png_bytep data, png_size_t length);
void error_callback (png_structp, png_const_charp);
void warning_callback (png_structp, png_const_charp);
//=======================================================================================
// ImageReader implementation
//=======================================================================================
SpImage ImageReader::load_image(const string& locator)
{
InputStream* pFile = nullptr;
try
{
pFile = FileSystem::open_input_stream(locator);
//find a reader that can decode the file
{
//PNG Format
PngImageDecoder decoder;
if (decoder.can_decode(pFile))
{
SpImage img = decoder.decode_file(pFile);
delete pFile;
return img;
}
}
{
//JPG Format
JpgImageDecoder decoder;
if (decoder.can_decode(pFile))
{
SpImage img = decoder.decode_file(pFile);
delete pFile;
return img;
}
}
//other formats not supported. throw error
delete pFile;
stringstream s;
s << "[ImageReader::load_image] Image format not supported. Locator: "
<< locator;
LOMSE_LOG_ERROR(s.str());
throw runtime_error(s.str());
}
catch(exception& e)
{
SpImage img( LOMSE_NEW Image() );
img->set_error_msg(e.what());
cerr << e.what() << " (catch in ImageReader::load_image)" << endl;
return img;
}
catch(...)
{
SpImage img( LOMSE_NEW Image() );
img->set_error_msg("Non-standard unknown exception");
cerr << "Non-standard unknown exception (catch in ImageReader::load_image)" << endl;
return img;
}
return SpImage( LOMSE_NEW Image() ); //compiler happy
}
//=======================================================================================
// PngImageDecoder implementation
//
// See: http://www.libpng.org/pub/png/book/chapter13.html
// http://www.piko3d.com/tutorials/libpng-tutorial-loading-png-files-from-streams
//=======================================================================================
//=======================================================================================
//some helper internal functions, not declared as protected members to avoid
//having to contaminate the lomse header files with PNG types
//=======================================================================================
void read_callback(png_structp png, png_bytep data, png_size_t length)
{
static_cast<InputStream*>( png_get_io_ptr(png) )->read(data, long(length));
}
//---------------------------------------------------------------------------------------
void error_callback (png_structp, png_const_charp)
{
LOMSE_LOG_ERROR("error reading png image");
throw "error reading png image";
}
//---------------------------------------------------------------------------------------
void warning_callback (png_structp, png_const_charp msg)
{
LOMSE_LOG_WARN("warning reading png image: %s", msg);
}
//=======================================================================================
// PngImageDecoder members implementation
//=======================================================================================
bool PngImageDecoder::can_decode(InputStream* file)
{
//A PNG file starts with an 8-byte signature. The hexadecimal byte values are:
// 89 50 4E 47 0D 0A 1A 0A; the decimal values are 137 80 78 71 13 10 26 10.
//From http://en.wikipedia.org/wiki/Portable_Network_Graphics
unsigned char header[8];
if (file->read(header, 8) == 8 && png_check_sig(header, 8))
return true;
else
{
//TODO: rewind file
return false;
}
}
//---------------------------------------------------------------------------------------
SpImage PngImageDecoder::decode_file(InputStream* file)
{
//TODO: error checking and handling
//create an empty image to be returned when errors
Image* pImage = LOMSE_NEW Image();
//create read struct
png_structp pReadStruct = png_create_read_struct(PNG_LIBPNG_VER_STRING,
nullptr, nullptr, nullptr);
if (!pReadStruct)
{
pImage->set_error_msg("[PngImageDecoder::decode_file] out of memory creating read struct");
return SpImage(pImage);
}
//create info struct
png_infop pInfoStruct = png_create_info_struct(pReadStruct);
if (!pInfoStruct)
{
pImage->set_error_msg("[PngImageDecoder::decode_file] out of memory creating info struct");
png_destroy_read_struct(&pReadStruct, 0, 0);
return SpImage(pImage );
}
png_set_error_fn(pReadStruct, 0, error_callback, warning_callback);
png_uint_32 width, height;
int bitDepth, colorType, interlaceType;
//we will take care of reading the file in our callback method
png_set_read_fn(pReadStruct, file, read_callback);
//inform about file position (we already read the 8 signature bytes)
png_set_sig_bytes(pReadStruct, 8);
//read all PNG info up to image data
png_read_info(pReadStruct, pInfoStruct);
//read image info. Don't care about compression_type and filter_type => NULLs
png_get_IHDR(pReadStruct, pInfoStruct, &width, &height, &bitDepth, &colorType,
&interlaceType, nullptr, nullptr);
//set some transformations
//expand palette images to 24-bit RGB
if (colorType == PNG_COLOR_TYPE_PALETTE)
png_set_expand(pReadStruct);
//expand low-bit-depth images to 8 bits
if (bitDepth < 8)
png_set_expand(pReadStruct);
//expand transparency chunks to full alpha channel
if (png_get_valid(pReadStruct, pInfoStruct, PNG_INFO_tRNS))
png_set_expand(pReadStruct);
//if more than 8 bits per colors, reduce to 8 bits
if (bitDepth == 16)
png_set_strip_16(pReadStruct);
//convert grayscale to RGB[A]
if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
png_set_gray_to_rgb(pReadStruct);
//TODO: gamma correction
// //if the image doesn't have gamma info, don't do any gamma correction
// if (png_get_gAMA(pReadStruct, pInfoStruct, &gamma))
// png_set_gamma(pReadStruct, display_exponent, gamma);
//set default alpha channel value to 255 (opaque)
png_set_add_alpha(pReadStruct, 0xff, PNG_FILLER_AFTER);
//all transformations have been defined.
//Now allocate a buffer for the full bitmap
unsigned char* imgbuf = nullptr;
int stride = int(width) * 4;
if ((imgbuf = (unsigned char*)malloc(height * stride)) == nullptr)
{
pImage->set_error_msg("[PngImageDecoder::decode_file] error allocating memory for image");
png_destroy_read_struct(&pReadStruct, &pInfoStruct, nullptr);
return SpImage(pImage);
}
//allocate pointers to rows
png_bytepp pRows = nullptr;
if ((pRows = (png_bytepp)malloc(height*sizeof(png_bytep))) == nullptr)
{
pImage->set_error_msg("[PngImageDecoder::decode_file] error allocating memory for line ptrs.");
png_destroy_read_struct(&pReadStruct, &pInfoStruct, nullptr);
free(imgbuf);
imgbuf = nullptr;
return SpImage(pImage);
}
//point row pointers to image buffer
png_bytep pDest = (png_bytep)imgbuf;
for (int y=0; y < int(height); ++y)
{
pRows[y] = pDest;
pDest += stride;
}
//go ahead and read the whole image
png_read_image(pReadStruct, pRows);
png_read_end(pReadStruct, pInfoStruct);
//image bitmap in RGBA format is now ready. Free memory used for row pointers
free(pRows);
pRows = nullptr;
//create the Image object
VSize bmpSize(width, height);
EPixelFormat format = k_pix_format_rgba32;
//TODO: get display reolution from lomse initialization. Here it is assumed 96 ppi
USize imgSize(float(width) * 2540.0f / 96.0f, float(height) * 2540.0f / 96.0f);
delete pImage;
pImage = LOMSE_NEW Image(imgbuf, bmpSize, format, imgSize);
//delete helper structs
png_destroy_read_struct(&pReadStruct, &pInfoStruct, 0);
//done!
return SpImage(pImage);
}
//=======================================================================================
// JpgImageDecoder implementation
//=======================================================================================
bool JpgImageDecoder::can_decode(InputStream* UNUSED(file))
{
// unsigned char hdr[2];
//
// if ( !stream.Read(hdr, WXSIZEOF(hdr)) )
// return false;
//
// return hdr[0] == 0xFF && hdr[1] == 0xD8;
////----------------------------
// const int bytesNeeded = 10;
// uint8 header [bytesNeeded];
//
// if (in.read (header, bytesNeeded) == bytesNeeded)
// {
// return header[0] == 0xff
// && header[1] == 0xd8
// && header[2] == 0xff
// && (header[3] == 0xe0 || header[3] == 0xe1);
// }
//
// return false;
return false;
}
//---------------------------------------------------------------------------------------
SpImage JpgImageDecoder::decode_file(InputStream* UNUSED(file))
{
//TODO: JpgImageDecoder::decode_file
return SpImage( LOMSE_NEW Image() );
}
} //namespace lomse
<|endoftext|>
|
<commit_before>#include "llvm/Pass.h"
#include "llvm/Function.h"
#include "llvm/Module.h"
#include "llvm/Instructions.h"
#include "llvm/Constants.h"
#include "llvm/GlobalVariable.h"
#include "llvm/Support/IRBuilder.h"
#include "llvm/Analysis/LoopInfo.h"
#include <string>
using namespace llvm;
using std::string;
using std::pair;
namespace
{
class ClassLookupCachePass : public FunctionPass
{
Module *M;
typedef std::pair<CallInst*,std::string> ClassLookup;
public:
static char ID;
ClassLookupCachePass() : FunctionPass((intptr_t)&ID) {}
virtual bool doInitialization(Module &Mod) {
M = &Mod;
return false;
}
virtual bool runOnFunction(Function &F) {
bool modified = false;
SmallVector<ClassLookup, 16> Lookups;
BasicBlock *entry = &F.getEntryBlock();
for (Function::iterator i=F.begin(), end=F.end() ;
i != end ; ++i) {
for (BasicBlock::iterator b=i->begin(), last=i->end() ;
b != last ; ++b) {
if (CallInst *call = dyn_cast<CallInst>(b)) {
Value *callee = call->getCalledValue()->stripPointerCasts();
if (Function *func = dyn_cast<Function>(callee)) {
if (func->getName() == "objc_lookup_class") {
ClassLookup lookup;
GlobalVariable *classNameVar = dyn_cast<GlobalVariable>(
call->getOperand(1)->stripPointerCasts());
if (0 == classNameVar) { continue; }
ConstantArray *init = dyn_cast<ConstantArray>(
classNameVar->getInitializer());
if (0 == init || !init->isCString()) { continue; }
lookup.first = call;
lookup.second = init->getAsString();
modified = true;
Lookups.push_back(lookup);
}
}
}
}
}
IRBuilder<> B = IRBuilder<>(entry);
for (SmallVectorImpl<ClassLookup>::iterator i=Lookups.begin(),
e=Lookups.end() ; e!=i ; i++) {
Value *global = M->getGlobalVariable(("_OBJC_CLASS_" + i->second).c_str(), true);
fprintf(stderr, "%s\n", ("_OBJC_CLASS_" + i->second).c_str());
if (global) {
Value *cls = new BitCastInst(global, i->first->getType(), "class", i->first);
i->first->replaceAllUsesWith(cls);
i->first->removeFromParent();
}
}
return modified;
}
};
char ClassLookupCachePass::ID = 0;
RegisterPass<ClassLookupCachePass> X("gnu-class-lookup-cache",
"Cache class lookups");
}
FunctionPass *createClassLookupCachePass(void)
{
return new ClassLookupCachePass();
}
<commit_msg>Removed debugging code that shouldn't have been in last commit.<commit_after>#include "llvm/Pass.h"
#include "llvm/Function.h"
#include "llvm/Module.h"
#include "llvm/Instructions.h"
#include "llvm/Constants.h"
#include "llvm/GlobalVariable.h"
#include "llvm/Support/IRBuilder.h"
#include "llvm/Analysis/LoopInfo.h"
#include <string>
using namespace llvm;
using std::string;
using std::pair;
namespace
{
class ClassLookupCachePass : public FunctionPass
{
Module *M;
typedef std::pair<CallInst*,std::string> ClassLookup;
public:
static char ID;
ClassLookupCachePass() : FunctionPass((intptr_t)&ID) {}
virtual bool doInitialization(Module &Mod) {
M = &Mod;
return false;
}
virtual bool runOnFunction(Function &F) {
bool modified = false;
SmallVector<ClassLookup, 16> Lookups;
BasicBlock *entry = &F.getEntryBlock();
for (Function::iterator i=F.begin(), end=F.end() ;
i != end ; ++i) {
for (BasicBlock::iterator b=i->begin(), last=i->end() ;
b != last ; ++b) {
if (CallInst *call = dyn_cast<CallInst>(b)) {
Value *callee = call->getCalledValue()->stripPointerCasts();
if (Function *func = dyn_cast<Function>(callee)) {
if (func->getName() == "objc_lookup_class") {
ClassLookup lookup;
GlobalVariable *classNameVar = dyn_cast<GlobalVariable>(
call->getOperand(1)->stripPointerCasts());
if (0 == classNameVar) { continue; }
ConstantArray *init = dyn_cast<ConstantArray>(
classNameVar->getInitializer());
if (0 == init || !init->isCString()) { continue; }
lookup.first = call;
lookup.second = init->getAsString();
modified = true;
Lookups.push_back(lookup);
}
}
}
}
}
IRBuilder<> B = IRBuilder<>(entry);
for (SmallVectorImpl<ClassLookup>::iterator i=Lookups.begin(),
e=Lookups.end() ; e!=i ; i++) {
Value *global = M->getGlobalVariable(("_OBJC_CLASS_" + i->second).c_str(), true);
if (global) {
Value *cls = new BitCastInst(global, i->first->getType(), "class", i->first);
i->first->replaceAllUsesWith(cls);
i->first->removeFromParent();
}
}
return modified;
}
};
char ClassLookupCachePass::ID = 0;
RegisterPass<ClassLookupCachePass> X("gnu-class-lookup-cache",
"Cache class lookups");
}
FunctionPass *createClassLookupCachePass(void)
{
return new ClassLookupCachePass();
}
<|endoftext|>
|
<commit_before>// Licensed under the Apache License, Version 2.0.
// Author: Jin Qing (http://blog.csdn.net/jq0123)
#include "client_async_reader_helper.h"
#include <cassert> // for assert()
#include <grpc_cb/impl/client/client_async_read_handler.h> // for ClientAsyncReadHandler
#include <grpc_cb/impl/client/client_reader_async_recv_status_cqtag.h> // for ClientReaderAsyncRecvStatusCqTag
#include <grpc_cb/status.h> // for Status
#include "client_reader_async_read_cqtag.h" // for ClientReaderAsyncReadCqTag
namespace grpc_cb {
using Sptr = ClientAsyncReaderHelperSptr;
ClientAsyncReaderHelper::ClientAsyncReaderHelper(
CompletionQueueSptr cq_sptr, CallSptr call_sptr, const StatusSptr& status_sptr,
const ClientAsyncReadHandlerSptr& read_handler_sptr,
const StatusCallback& on_status)
: cq_sptr_(cq_sptr),
call_sptr_(call_sptr),
status_sptr_(status_sptr),
read_handler_sptr_(read_handler_sptr),
on_status_(on_status) {
assert(cq_sptr);
assert(call_sptr);
assert(status_sptr);
}
ClientAsyncReaderHelper::~ClientAsyncReaderHelper() {}
// Setup next async read.
void ClientAsyncReaderHelper::AsyncReadNext() {
if (!status_sptr_->ok()) return;
Sptr sptr = shared_from_this();
auto* tag = new ClientReaderAsyncReadCqTag(sptr);
if (tag->Start()) return;
delete tag;
status_sptr_->SetInternalError("Failed to async read server stream.");
if (on_status_) on_status_(*status_sptr_);
}
void ClientAsyncReaderHelper::OnRead(ClientReaderAsyncReadCqTag& tag) {
if (!status_sptr_->ok())
return;
if (!tag.HasGotMsg()) {
// End of read.
AsyncRecvStatus();
return;
}
Status& status = *status_sptr_;
status = tag.GetResultMsg(read_handler_sptr_->GetMsg());
if (status.ok()) {
read_handler_sptr_->HandleMsg();
return;
}
// XXX CallOnEnd(status);
}
void ClientAsyncReaderHelper::AsyncRecvStatus() {
assert(status_sptr_->ok());
// XXX input status_sptr_ to CqTag? To abort writing?
auto* tag = new ClientReaderAsyncRecvStatusCqTag(call_sptr_, on_status_);
if (tag->Start()) return;
delete tag;
status_sptr_->SetInternalError("Failed to receive status.");
if (on_status_) on_status_(*status_sptr_);
}
#if 0
template <class Response>
inline void OnReadEach(const Response& msg,
const ClientReaderDataSptr<Response>& data_sptr) {
Status& status = data_sptr->status;
assert(status.ok());
std::function<void(const Response&)>& on_msg = data_sptr->on_msg;
if (on_msg) on_msg(msg);
AsyncReadNext(data_sptr);
// Old tag will be deleted after return in BlockingRun().
}
template <class Response>
inline void OnEnd(const Status& status,
const ClientReaderDataSptr<Response>& data_sptr) {
StatusCallback& on_status = data_sptr->on_status;
if (status.ok()) {
AsyncRecvStatus(data_sptr->call_sptr,
data_sptr->status, on_status);
return;
}
if (on_status) on_status(status);
}
#endif
} // namespace grpc_cb
<commit_msg>Add todo.<commit_after>// Licensed under the Apache License, Version 2.0.
// Author: Jin Qing (http://blog.csdn.net/jq0123)
#include "client_async_reader_helper.h"
#include <cassert> // for assert()
#include <grpc_cb/impl/client/client_async_read_handler.h> // for ClientAsyncReadHandler
#include <grpc_cb/impl/client/client_reader_async_recv_status_cqtag.h> // for ClientReaderAsyncRecvStatusCqTag
#include <grpc_cb/status.h> // for Status
#include "client_reader_async_read_cqtag.h" // for ClientReaderAsyncReadCqTag
namespace grpc_cb {
using Sptr = ClientAsyncReaderHelperSptr;
ClientAsyncReaderHelper::ClientAsyncReaderHelper(
CompletionQueueSptr cq_sptr, CallSptr call_sptr, const StatusSptr& status_sptr,
const ClientAsyncReadHandlerSptr& read_handler_sptr,
const StatusCallback& on_status)
: cq_sptr_(cq_sptr),
call_sptr_(call_sptr),
status_sptr_(status_sptr),
read_handler_sptr_(read_handler_sptr),
on_status_(on_status) {
assert(cq_sptr);
assert(call_sptr);
assert(status_sptr);
}
ClientAsyncReaderHelper::~ClientAsyncReaderHelper() {}
// Setup next async read.
void ClientAsyncReaderHelper::AsyncReadNext() {
if (!status_sptr_->ok()) return;
Sptr sptr = shared_from_this();
auto* tag = new ClientReaderAsyncReadCqTag(sptr);
if (tag->Start()) return;
delete tag;
status_sptr_->SetInternalError("Failed to async read server stream.");
if (on_status_) on_status_(*status_sptr_);
}
void ClientAsyncReaderHelper::OnRead(ClientReaderAsyncReadCqTag& tag) {
if (!status_sptr_->ok())
return;
if (!tag.HasGotMsg()) {
// End of read.
AsyncRecvStatus();
// XXXX Do not recv status in Reader. Do it after all reading and writing.
return;
}
Status& status = *status_sptr_;
status = tag.GetResultMsg(read_handler_sptr_->GetMsg());
if (status.ok()) {
read_handler_sptr_->HandleMsg();
return;
}
// XXX CallOnEnd(status);
}
void ClientAsyncReaderHelper::AsyncRecvStatus() {
assert(status_sptr_->ok());
// XXX input status_sptr_ to CqTag? To abort writing?
auto* tag = new ClientReaderAsyncRecvStatusCqTag(call_sptr_, on_status_);
if (tag->Start()) return;
delete tag;
status_sptr_->SetInternalError("Failed to receive status.");
if (on_status_) on_status_(*status_sptr_);
}
#if 0
template <class Response>
inline void OnReadEach(const Response& msg,
const ClientReaderDataSptr<Response>& data_sptr) {
Status& status = data_sptr->status;
assert(status.ok());
std::function<void(const Response&)>& on_msg = data_sptr->on_msg;
if (on_msg) on_msg(msg);
AsyncReadNext(data_sptr);
// Old tag will be deleted after return in BlockingRun().
}
template <class Response>
inline void OnEnd(const Status& status,
const ClientReaderDataSptr<Response>& data_sptr) {
StatusCallback& on_status = data_sptr->on_status;
if (status.ok()) {
AsyncRecvStatus(data_sptr->call_sptr,
data_sptr->status, on_status);
return;
}
if (on_status) on_status(status);
}
#endif
} // namespace grpc_cb
<|endoftext|>
|
<commit_before>/**
* This file is part of TelepathyQt4
*
* @copyright Copyright (C) 2008-2009 Collabora Ltd. <http://www.collabora.co.uk/>
* @copyright Copyright (C) 2008-2009 Nokia Corporation
* @license LGPL 2.1
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#define IN_TELEPATHY_QT4_HEADER
#include "debug.h"
#include "debug-internal.h"
#include "config-version.h"
/**
* \defgroup debug Common debug support
*
* TelepathyQt4 has an internal mechanism for displaying debugging output. It
* uses the Qt4 debugging subsystem, so if you want to redirect the messages,
* use qInstallMsgHandler() from <QtGlobal>.
*
* Debugging output is divided into two categories: normal debug output and
* warning messages. Normal debug output results in the normal operation of the
* library, warning messages are output only when something goes wrong. Each
* category can be invidually enabled.
*/
namespace Tp
{
/**
* \fn void enableDebug(bool enable)
* \ingroup debug
*
* Enable or disable normal debug output from the library. If the library is not
* compiled with debug support enabled, this has no effect; no output is
* produced in any case.
*
* The default is <code>false</code> ie. no debug output.
*
* \param enable Whether debug output should be enabled or not.
*/
/**
* \fn void enableWarnings(bool enable)
* \ingroup debug
*
* Enable or disable warning output from the library. If the library is not
* compiled with debug support enabled, this has no effect; no output is
* produced in any case.
*
* The default is <code>true</code> ie. warning output enabled.
*
* \param enable Whether warnings should be enabled or not.
*/
/**
* \typedef DebugCallback
* \ingroup debug
*
* \code
* typedef QDebug (*DebugCallback)(const QString &libraryName,
* const QString &libraryVersion,
* QtMsgType type,
* const QString &msg)
* \endcode
*/
/**
* \fn void setDebugCallback(DebugCallback cb)
* \ingroup debug
*
* Set the callback method that will handle the debug output.
*
* If \p cb is NULL this method will set the defaultDebugCallback instead.
* The default callback function will print the output using default Qt debug
* system.
*
* \param cb A function pointer to the callback method or NULL.
* \sa DebugCallback
*/
#ifdef ENABLE_DEBUG
namespace
{
bool debugEnabled = false;
bool warningsEnabled = true;
void (*debugCallback)(const QString &, const QString &, QtMsgType, const QString &) = NULL;
}
void enableDebug(bool enable)
{
debugEnabled = enable;
}
void enableWarnings(bool enable)
{
warningsEnabled = enable;
}
void setDebugCallback(DebugCallback cb)
{
debugCallback = cb;
}
Debug enabledDebug()
{
if (debugEnabled) {
return Debug(QtDebugMsg);
} else {
return Debug();
}
}
Debug enabledWarning()
{
if (warningsEnabled) {
return Debug(QtWarningMsg);
} else {
return Debug();
}
}
void Debug::invokeDebugCallback()
{
if (debugCallback) {
debugCallback(QLatin1String("tp-qt4"), QLatin1String(PACKAGE_VERSION), type, msg);
} else {
switch (type) {
case QtDebugMsg:
qDebug() << "tp-qt4 " PACKAGE_VERSION " DEBUG:" << qPrintable(msg);
break;
case QtWarningMsg:
qWarning() << "tp-qt4 " PACKAGE_VERSION " WARN:" << qPrintable(msg);
break;
default:
break;
}
}
}
#else /* !defined(ENABLE_DEBUG) */
void enableDebug(bool enable)
{
}
void enableWarnings(bool enable)
{
}
void setDebugCallback(DebugCallback cb)
{
}
Debug enabledDebug()
{
return Debug();
}
Debug enabledWarning()
{
return Debug();
}
void Debug::invokeDebugCallback()
{
}
#endif /* !defined(ENABLE_DEBUG) */
} // Tp
<commit_msg>Use the typedef for declaring the debug callback global variable<commit_after>/**
* This file is part of TelepathyQt4
*
* @copyright Copyright (C) 2008-2009 Collabora Ltd. <http://www.collabora.co.uk/>
* @copyright Copyright (C) 2008-2009 Nokia Corporation
* @license LGPL 2.1
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#define IN_TELEPATHY_QT4_HEADER
#include "debug.h"
#include "debug-internal.h"
#include "config-version.h"
/**
* \defgroup debug Common debug support
*
* TelepathyQt4 has an internal mechanism for displaying debugging output. It
* uses the Qt4 debugging subsystem, so if you want to redirect the messages,
* use qInstallMsgHandler() from <QtGlobal>.
*
* Debugging output is divided into two categories: normal debug output and
* warning messages. Normal debug output results in the normal operation of the
* library, warning messages are output only when something goes wrong. Each
* category can be invidually enabled.
*/
namespace Tp
{
/**
* \fn void enableDebug(bool enable)
* \ingroup debug
*
* Enable or disable normal debug output from the library. If the library is not
* compiled with debug support enabled, this has no effect; no output is
* produced in any case.
*
* The default is <code>false</code> ie. no debug output.
*
* \param enable Whether debug output should be enabled or not.
*/
/**
* \fn void enableWarnings(bool enable)
* \ingroup debug
*
* Enable or disable warning output from the library. If the library is not
* compiled with debug support enabled, this has no effect; no output is
* produced in any case.
*
* The default is <code>true</code> ie. warning output enabled.
*
* \param enable Whether warnings should be enabled or not.
*/
/**
* \typedef DebugCallback
* \ingroup debug
*
* \code
* typedef QDebug (*DebugCallback)(const QString &libraryName,
* const QString &libraryVersion,
* QtMsgType type,
* const QString &msg)
* \endcode
*/
/**
* \fn void setDebugCallback(DebugCallback cb)
* \ingroup debug
*
* Set the callback method that will handle the debug output.
*
* If \p cb is NULL this method will set the defaultDebugCallback instead.
* The default callback function will print the output using default Qt debug
* system.
*
* \param cb A function pointer to the callback method or NULL.
* \sa DebugCallback
*/
#ifdef ENABLE_DEBUG
namespace
{
bool debugEnabled = false;
bool warningsEnabled = true;
DebugCallback debugCallback = NULL;
}
void enableDebug(bool enable)
{
debugEnabled = enable;
}
void enableWarnings(bool enable)
{
warningsEnabled = enable;
}
void setDebugCallback(DebugCallback cb)
{
debugCallback = cb;
}
Debug enabledDebug()
{
if (debugEnabled) {
return Debug(QtDebugMsg);
} else {
return Debug();
}
}
Debug enabledWarning()
{
if (warningsEnabled) {
return Debug(QtWarningMsg);
} else {
return Debug();
}
}
void Debug::invokeDebugCallback()
{
if (debugCallback) {
debugCallback(QLatin1String("tp-qt4"), QLatin1String(PACKAGE_VERSION), type, msg);
} else {
switch (type) {
case QtDebugMsg:
qDebug() << "tp-qt4 " PACKAGE_VERSION " DEBUG:" << qPrintable(msg);
break;
case QtWarningMsg:
qWarning() << "tp-qt4 " PACKAGE_VERSION " WARN:" << qPrintable(msg);
break;
default:
break;
}
}
}
#else /* !defined(ENABLE_DEBUG) */
void enableDebug(bool enable)
{
}
void enableWarnings(bool enable)
{
}
void setDebugCallback(DebugCallback cb)
{
}
Debug enabledDebug()
{
return Debug();
}
Debug enabledWarning()
{
return Debug();
}
void Debug::invokeDebugCallback()
{
}
#endif /* !defined(ENABLE_DEBUG) */
} // Tp
<|endoftext|>
|
<commit_before>#include <stan/agrad/rev/functions/fmax.hpp>
#include <test/unit/agrad/util.hpp>
#include <gtest/gtest.h>
TEST(AgradRev,fmax_vv) {
AVAR a = 1.3;
AVAR b = 2.0;
AVAR f = fmax(a,b);
EXPECT_FLOAT_EQ(2.0,f.val());
AVEC x = createAVEC(a,b);
VEC grad_f;
f.grad(x,grad_f);
EXPECT_FLOAT_EQ(0.0,grad_f[0]);
EXPECT_FLOAT_EQ(1.0,grad_f[1]);
}
TEST(AgradRev,fmax_vv_2) {
AVAR a = 2.3;
AVAR b = 2.0;
AVAR f = fmax(a,b);
EXPECT_FLOAT_EQ(2.3,f.val());
AVEC x = createAVEC(a,b);
VEC grad_f;
f.grad(x,grad_f);
EXPECT_FLOAT_EQ(1.0,grad_f[0]);
EXPECT_FLOAT_EQ(0.0,grad_f[1]);
}
TEST(AgradRev,fmax_vv_3) {
AVAR a = 2.0;
AVAR b = 2.0;
AVAR f = fmax(a,b);
EXPECT_FLOAT_EQ(2.0,f.val());
AVEC x = createAVEC(a,b);
VEC grad_f;
f.grad(x,grad_f);
// arbitrary, but documented this way
EXPECT_FLOAT_EQ(0.0,grad_f[0]);
EXPECT_FLOAT_EQ(1.0,grad_f[1]);
}
TEST(AgradRev,fmax_vd) {
AVAR a = 1.3;
double b = 2.0;
AVAR f = fmax(a,b);
EXPECT_FLOAT_EQ(2.0,f.val());
AVEC x = createAVEC(a);
VEC grad_f;
f.grad(x,grad_f);
EXPECT_FLOAT_EQ(0.0,grad_f[0]);
}
TEST(AgradRev,fmax_vd_2) {
AVAR a = 2.3;
double b = 2.0;
AVAR f = fmax(a,b);
EXPECT_FLOAT_EQ(2.3,f.val());
AVEC x = createAVEC(a);
VEC grad_f;
f.grad(x,grad_f);
EXPECT_FLOAT_EQ(1.0,grad_f[0]);
}
TEST(AgradRev,fmax_vd_3) {
AVAR a = 2.0;
double b = 2.0;
AVAR f = fmax(a,b);
EXPECT_FLOAT_EQ(2.0,f.val());
AVEC x = createAVEC(a);
VEC grad_f;
f.grad(x,grad_f);
EXPECT_FLOAT_EQ(1.0,grad_f[0]);
}
TEST(AgradRev,fmax_dv) {
double a = 1.3;
AVAR b = 2.0;
AVAR f = fmax(a,b);
EXPECT_FLOAT_EQ(2.0,f.val());
AVEC x = createAVEC(b);
VEC grad_f;
f.grad(x,grad_f);
EXPECT_FLOAT_EQ(1.0,grad_f[0]);
}
TEST(AgradRev,fmax_dv_2) {
double a = 2.3;
AVAR b = 2.0;
AVAR f = fmax(a,b);
EXPECT_FLOAT_EQ(2.3,f.val());
AVEC x = createAVEC(b);
VEC grad_f;
f.grad(x,grad_f);
EXPECT_FLOAT_EQ(0.0,grad_f[0]);
}
TEST(AgradRev,fmax_dv_3) {
double a = 2.0;
AVAR b = 2.0;
AVAR f = fmax(a,b);
EXPECT_FLOAT_EQ(2.0,f.val());
AVEC x = createAVEC(b);
VEC grad_f;
f.grad(x,grad_f);
// arbitrary, but doc this way
EXPECT_FLOAT_EQ(1.0,grad_f[0]);
}
<commit_msg>added failing NaN test for agrad/rev/fmax<commit_after>#include <stan/agrad/rev/functions/fmax.hpp>
#include <test/unit/agrad/util.hpp>
#include <gtest/gtest.h>
#include <stan/meta/traits.hpp>
#include <test/unit-agrad-rev/nan_util.hpp>
TEST(AgradRev,fmax_vv) {
AVAR a = 1.3;
AVAR b = 2.0;
AVAR f = fmax(a,b);
EXPECT_FLOAT_EQ(2.0,f.val());
AVEC x = createAVEC(a,b);
VEC grad_f;
f.grad(x,grad_f);
EXPECT_FLOAT_EQ(0.0,grad_f[0]);
EXPECT_FLOAT_EQ(1.0,grad_f[1]);
}
TEST(AgradRev,fmax_vv_2) {
AVAR a = 2.3;
AVAR b = 2.0;
AVAR f = fmax(a,b);
EXPECT_FLOAT_EQ(2.3,f.val());
AVEC x = createAVEC(a,b);
VEC grad_f;
f.grad(x,grad_f);
EXPECT_FLOAT_EQ(1.0,grad_f[0]);
EXPECT_FLOAT_EQ(0.0,grad_f[1]);
}
TEST(AgradRev,fmax_vv_3) {
AVAR a = 2.0;
AVAR b = 2.0;
AVAR f = fmax(a,b);
EXPECT_FLOAT_EQ(2.0,f.val());
AVEC x = createAVEC(a,b);
VEC grad_f;
f.grad(x,grad_f);
// arbitrary, but documented this way
EXPECT_FLOAT_EQ(0.0,grad_f[0]);
EXPECT_FLOAT_EQ(1.0,grad_f[1]);
}
TEST(AgradRev,fmax_vd) {
AVAR a = 1.3;
double b = 2.0;
AVAR f = fmax(a,b);
EXPECT_FLOAT_EQ(2.0,f.val());
AVEC x = createAVEC(a);
VEC grad_f;
f.grad(x,grad_f);
EXPECT_FLOAT_EQ(0.0,grad_f[0]);
}
TEST(AgradRev,fmax_vd_2) {
AVAR a = 2.3;
double b = 2.0;
AVAR f = fmax(a,b);
EXPECT_FLOAT_EQ(2.3,f.val());
AVEC x = createAVEC(a);
VEC grad_f;
f.grad(x,grad_f);
EXPECT_FLOAT_EQ(1.0,grad_f[0]);
}
TEST(AgradRev,fmax_vd_3) {
AVAR a = 2.0;
double b = 2.0;
AVAR f = fmax(a,b);
EXPECT_FLOAT_EQ(2.0,f.val());
AVEC x = createAVEC(a);
VEC grad_f;
f.grad(x,grad_f);
EXPECT_FLOAT_EQ(1.0,grad_f[0]);
}
TEST(AgradRev,fmax_dv) {
double a = 1.3;
AVAR b = 2.0;
AVAR f = fmax(a,b);
EXPECT_FLOAT_EQ(2.0,f.val());
AVEC x = createAVEC(b);
VEC grad_f;
f.grad(x,grad_f);
EXPECT_FLOAT_EQ(1.0,grad_f[0]);
}
TEST(AgradRev,fmax_dv_2) {
double a = 2.3;
AVAR b = 2.0;
AVAR f = fmax(a,b);
EXPECT_FLOAT_EQ(2.3,f.val());
AVEC x = createAVEC(b);
VEC grad_f;
f.grad(x,grad_f);
EXPECT_FLOAT_EQ(0.0,grad_f[0]);
}
TEST(AgradRev,fmax_dv_3) {
double a = 2.0;
AVAR b = 2.0;
AVAR f = fmax(a,b);
EXPECT_FLOAT_EQ(2.0,f.val());
AVEC x = createAVEC(b);
VEC grad_f;
f.grad(x,grad_f);
// arbitrary, but doc this way
EXPECT_FLOAT_EQ(1.0,grad_f[0]);
}
struct fmax_fun {
template <typename T0, typename T1>
inline
typename stan::return_type<T0,T1>::type
operator()(const T0& arg1,
const T1& arg2) const {
return fmax(arg1,arg2);
}
};
TEST(AgradRev, fmax_nan) {
fmax_fun fmax_;
double nan = std::numeric_limits<double>::quiet_NaN();
test_nan_vv(fmax_,nan,nan,false, true);
test_nan_dv(fmax_,nan,nan,false, true);
test_nan_vd(fmax_,nan,nan,false, true);
}
<|endoftext|>
|
<commit_before>
#pragma once
#include <Geometry2d/Point.hpp>
#include <Geometry2d/Segment.hpp>
#include "Obstacle.hpp"
namespace Planning
{
/**
* Represents a path as a series of 2d points
*/
class Path
{
public:
/** default path is empty */
Path() {}
/** constructor with a single point */
Path(const Geometry2d::Point& p0);
/** constructor from two points */
Path(const Geometry2d::Point& p0, const Geometry2d::Point& p1);
bool empty() const
{
return points.empty();
}
void clear()
{
points.clear();
}
// Returns the length of the path starting at point (start).
float length(unsigned int start = 0) const;
/** returns the length of the path from the closet point found to @a pt */
float length(const Geometry2d::Point &pt) const;
// number of waypoints
size_t size() const { return points.size(); }
/** returns true if the path has non-zero size */
bool valid() const { return !points.empty(); }
// Returns the index of the point in this path nearest to pt.
int nearestIndex(const Geometry2d::Point &pt) const;
/** returns the nearest segement of @a pt to the path */
Geometry2d::Segment nearestSegment(const Geometry2d::Point &pt) const;
// Returns the shortest distance from this path to the given point
float distanceTo(const Geometry2d::Point &pt) const;
// Returns the start of the path
Geometry2d::Point::Optional start() const;
// Returns a new path starting from a given point
void startFrom(const Geometry2d::Point& pt, Planning::Path& result) const;
//Returns the destination of this path (the last point in the points array)
Geometry2d::Point::Optional destination() const;
// Returns true if the path never touches an obstacle or additionally, when exitObstacles is true, if the path
// starts out in an obstacle but leaves and never re-enters any obstacle.
bool hit(const ObstacleGroup &obstacles, unsigned int start = 0) const;
// Set of points in the path - used as waypoints
std::vector<Geometry2d::Point> points;
};
}
<commit_msg>added Path.evaluate()<commit_after>
#pragma once
#include <Geometry2d/Point.hpp>
#include <Geometry2d/Segment.hpp>
#include "Obstacle.hpp"
namespace Planning
{
/**
* Represents a path as a series of 2d points
*/
class Path
{
public:
/** default path is empty */
Path() {}
/** constructor with a single point */
Path(const Geometry2d::Point& p0);
/** constructor from two points */
Path(const Geometry2d::Point& p0, const Geometry2d::Point& p1);
bool empty() const
{
return points.empty();
}
void clear()
{
points.clear();
}
// Returns the length of the path starting at point (start).
float length(unsigned int start = 0) const;
/** returns the length of the path from the closet point found to @a pt */
float length(const Geometry2d::Point &pt) const;
// number of waypoints
size_t size() const { return points.size(); }
/** returns true if the path has non-zero size */
bool valid() const { return !points.empty(); }
// Returns the index of the point in this path nearest to pt.
int nearestIndex(const Geometry2d::Point &pt) const;
/** returns the nearest segement of @a pt to the path */
Geometry2d::Segment nearestSegment(const Geometry2d::Point &pt) const;
// Returns the shortest distance from this path to the given point
float distanceTo(const Geometry2d::Point &pt) const;
// Returns the start of the path
Geometry2d::Point::Optional start() const;
// Returns a new path starting from a given point
void startFrom(const Geometry2d::Point& pt, Planning::Path& result) const;
//Returns the destination of this path (the last point in the points array)
Geometry2d::Point::Optional destination() const;
// Returns true if the path never touches an obstacle or additionally, when exitObstacles is true, if the path
// starts out in an obstacle but leaves and never re-enters any obstacle.
bool hit(const ObstacleGroup &obstacles, unsigned int start = 0) const;
// Set of points in the path - used as waypoints
std::vector<Geometry2d::Point> points;
/**
* A path describes the position and velocity a robot should be at for a
* particular time interval. This methd evalates the path at a given time and
* returns the target position and velocity of the robot.
*
* @param t Time (in seconds) since the robot started the path
* @param targetPosOut The position the robot would ideally be at at the given time
* @param targetVelOut The target velocity of the robot at the given time
* @return true if the path is valid at time @t, false if you've gone past the end
*/
bool evaluate(float t, Geometry2d::Point &targetPosOut, Geometry2d::Point &targetVelOut);
};
}
<|endoftext|>
|
<commit_before>/**
mcu.cpp
Main source file.
Part of Magnetic stripe Card Utility.
Copyright (c) 2010 Wincent Balin
Based heavily upon dab.c and dmsb.c by Joseph Battaglia.
Uses RtAudio by Gary P. Scavone for audio input. Input routines
are based on RtAudio examples.
As both of the mentioned above inspirations the program is licensed
under the MIT License. See LICENSE file for further information.
*/
#include "mcu.hpp"
#include "RtAudio.h"
#include <iostream>
#include <map>
#include <cstdlib>
#include <getopt.h>
// Version of the program
#define VERSION 0.1
// Initial silence threshold
#define SILENCE_THRES 5000
// Percent of highest value to set silence_thres to
#define AUTO_THRES 30
// Frequency threshold (in percent)
#define FREQ_THRES 60
using namespace std;
// List of devices
vector<RtAudio::DeviceInfo> devices;
// List of original device indexes
vector<int> device_indexes;
// Input data buffer
struct input_data
{
int16_t* buffer;
uint32_t buffer_bytes;
uint32_t total_frames;
uint32_t frame_counter;
uint32_t channels;
};
void
print_version(void)
{
cerr << "mcu - Magnetic stripe Card Utility" << endl
<< "Version " << VERSION << endl
<< "Copyright (c) 2010 Wincent Balin" << endl
<< endl;
}
void
print_help(void)
{
print_version();
cerr << "Usage: mcu [OPTIONS]" << endl
<< endl
<< " -a, --auto-thres Set auto-thres percentage" << endl
<< " (default: " << AUTO_THRES << ")" << endl
<< " -d, --device Device (number) to read audio data from" << endl
<< " (default: 0)" << endl
<< " -l, --list-devices List compatible devices (enumerated)" << endl
<< " -h, --help Print help information" << endl
<< " -m, --max-level Shows the maximum level" << endl
<< " (use to determine threshold)" << endl
<< " -s, --silent No verbose messages" << endl
<< " -t, --threshold Set silence threshold" << endl
<< " (default: automatic detect)" << endl
<< " -v, --version Print version information" << endl
<< endl;
}
void
list_devices(vector<RtAudio::DeviceInfo>& dev, vector<int>& index)
{
// Audio interface
RtAudio audio;
// Get devices
for(unsigned int i = 0; i < audio.getDeviceCount(); i++)
{
RtAudio::DeviceInfo info = audio.getDeviceInfo(i);
// If device unprobed, go to the next one
if(!info.probed)
continue;
// If no input channels, skip this device
if(info.inputChannels < 1)
continue;
// If no natively supported formats, skip this device
if(info.nativeFormats == 0)
continue;
// We need S16 format. If unavailable, skip this device
if(!(info.nativeFormats & RTAUDIO_SINT16))
continue;
// If no sample rates supported, skip this device
if(info.sampleRates.size() < 1)
continue;
// Add new audio input device
dev.push_back(info);
index.push_back(i);
}
}
void
print_devices(vector<RtAudio::DeviceInfo>& dev)
{
// API map
map<int, string> api_map;
// Initialize API map
api_map[RtAudio::MACOSX_CORE] = "OS-X Core Audio";
api_map[RtAudio::WINDOWS_ASIO] = "Windows ASIO";
api_map[RtAudio::WINDOWS_DS] = "Windows Direct Sound";
api_map[RtAudio::UNIX_JACK] = "Jack Client";
api_map[RtAudio::LINUX_ALSA] = "Linux ALSA";
api_map[RtAudio::LINUX_OSS] = "Linux OSS";
api_map[RtAudio::RTAUDIO_DUMMY] = "RtAudio Dummy";
// Audio interface
RtAudio audio;
// Print current API
cerr << "Current API: " << api_map[audio.getCurrentApi()] << endl;
// Print every device
for(unsigned int i = 0; i < dev.size(); i++)
{
RtAudio::DeviceInfo info = dev[i];
// Print number of the device
cerr.width(3);
cerr << i << " "
<< info.name
<< (info.isDefaultInput ? " (Default input device)" : "") << endl;
}
}
int
input(void* out_buffer, void* in_buffer, unsigned int n_buffer_frames,
double stream_time, RtAudioStreamStatus status, void *data)
{
(void) out_buffer;
(void) stream_time;
(void) status;
struct input_data* in_data = (struct input_data*) data;
// Copy data to the allocated buffer
unsigned int frames = n_buffer_frames;
if(in_data->frame_counter + n_buffer_frames > in_data->total_frames)
{
frames = in_data->total_frames - in_data->frame_counter;
in_data->buffer_bytes = frames * in_data->channels * sizeof(int16_t);
}
uint32_t offset = in_data->frame_counter * in_data->channels;
memcpy(in_data->buffer + offset, in_buffer, in_data->buffer_bytes);
in_data->frame_counter += frames;
// If buffer overflown, return with unnormal value
if(in_data->frame_counter >= in_data->total_frames)
return 2;
return 0;
}
int
main(int argc, char** argv)
{
// Sound input
RtAudio adc;
// Configuration variables
int auto_thres = AUTO_THRES;
bool max_level = false;
bool verbose = true;
int silence_thres = SILENCE_THRES;
bool list_input_devices = false;
int device_number = 0;
// Getopt variables
int ch, option_index;
static struct option long_options[] =
{
{"auto-thres", 0, 0, 'a'},
{"device", 1, 0, 'd'},
{"list-devices", 0, 0, 'l'},
{"help", 0, 0, 'h'},
{"max-level", 0, 0, 'm'},
{"silent", 0, 0, 's'},
{"threshold", 1, 0, 't'},
{"version", 0, 0, 'v'},
{ 0, 0, 0, 0 }
};
// Process command line arguments
while(true)
{
ch = getopt_long(argc, argv, "a:d:lhmst:v", long_options, &option_index);
if(ch == -1)
break;
switch(ch)
{
// Auto threshold
case 'a':
auto_thres = atoi(optarg);
break;
// Device (number)
case 'd':
device_number = atoi(optarg);
break;
// List devices
case 'l':
list_input_devices = true;
break;
// Help
case 'h':
print_help();
exit(EXIT_SUCCESS);
break;
// Maximal level
case 'm':
max_level = true;
break;
// Silent
case 's':
verbose = false;
break;
// Threshold
case 't':
auto_thres = 0;
silence_thres = atoi(optarg);
break;
// Version
case 'v':
print_version();
exit(EXIT_SUCCESS);
break;
// Unknown options
default:
print_help();
exit(EXIT_FAILURE);
break;
}
}
// Print version
if(verbose)
{
print_version();
cerr << endl;
}
// Make RtAudio part verbose too
if(verbose)
adc.showWarnings(true);
// If no sound devices found, exit
if(adc.getDeviceCount() < 1)
{
cerr << "No audio devices found!" << endl;
exit(EXIT_FAILURE);
}
// Get list of device
list_devices(devices, device_indexes);
// If requested, print list of devices and exit
if(list_input_devices)
{
print_devices(devices);
exit(EXIT_SUCCESS);
}
// Specify parameters of the audio stream
unsigned int buffer_frames = 512;
unsigned int fs = 192000;
RtAudio::StreamParameters input_params;
input_params.deviceId = device_indexes[device_number];
input_params.nChannels = 1;
input_params.firstChannel = 0;
// Define data buffer
struct input_data data;
data.buffer = 0;
// Open audio stream
try
{
adc.openStream(NULL, &input_params, RTAUDIO_SINT16, fs,
&buffer_frames, &input, (void *) &data);
}
catch(RtError& e)
{
cerr << endl << e.getMessage() << endl;
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
}
<commit_msg>Reworked data buffer; added printing max level<commit_after>/**
mcu.cpp
Main source file.
Part of Magnetic stripe Card Utility.
Copyright (c) 2010 Wincent Balin
Based heavily upon dab.c and dmsb.c by Joseph Battaglia.
Uses RtAudio by Gary P. Scavone for audio input. Input routines
are based on RtAudio examples.
As both of the mentioned above inspirations the program is licensed
under the MIT License. See LICENSE file for further information.
*/
#include "mcu.hpp"
#include "RtAudio.h"
#include <iostream>
#include <map>
#include <queue>
#include <cstdlib>
#include <getopt.h>
// Platform-dependent sleep routines; taken from RtAudio example
#if defined( __WINDOWS_ASIO__ ) || defined( __WINDOWS_DS__ )
#include <windows.h>
#define SLEEP( milliseconds ) Sleep( (DWORD) milliseconds )
#else // Unix variants
#include <unistd.h>
#define SLEEP( milliseconds ) usleep( (unsigned long) (milliseconds * 1000.0) )
#endif
// Version of the program
#define VERSION 0.1
// Initial silence threshold
#define SILENCE_THRES 5000
// Percent of highest value to set silence_thres to
#define AUTO_THRES 30
// Frequency threshold (in percent)
#define FREQ_THRES 60
// Seconds before termination of print_max_level()
#define MAX_TERM 60
using namespace std;
// List of devices
vector<RtAudio::DeviceInfo> devices;
// List of original device indexes
vector<int> device_indexes;
// We use signed 16 bit value as a sample
typedef int16_t sample_t;
// Input data buffer
queue<sample_t> buffer;
void
print_version(void)
{
cerr << "mcu - Magnetic stripe Card Utility" << endl
<< "Version " << VERSION << endl
<< "Copyright (c) 2010 Wincent Balin" << endl
<< endl;
}
void
print_help(void)
{
print_version();
cerr << "Usage: mcu [OPTIONS]" << endl
<< endl
<< " -a, --auto-thres Set auto-thres percentage" << endl
<< " (default: " << AUTO_THRES << ")" << endl
<< " -d, --device Device (number) to read audio data from" << endl
<< " (default: 0)" << endl
<< " -l, --list-devices List compatible devices (enumerated)" << endl
<< " -h, --help Print help information" << endl
<< " -m, --max-level Shows the maximum level" << endl
<< " (use to determine threshold)" << endl
<< " -s, --silent No verbose messages" << endl
<< " -t, --threshold Set silence threshold" << endl
<< " (default: automatic detect)" << endl
<< " -v, --version Print version information" << endl
<< endl;
}
void
list_devices(vector<RtAudio::DeviceInfo>& dev, vector<int>& index)
{
// Audio interface
RtAudio audio;
// Get devices
for(unsigned int i = 0; i < audio.getDeviceCount(); i++)
{
RtAudio::DeviceInfo info = audio.getDeviceInfo(i);
// If device unprobed, go to the next one
if(!info.probed)
continue;
// If no input channels, skip this device
if(info.inputChannels < 1)
continue;
// If no natively supported formats, skip this device
if(info.nativeFormats == 0)
continue;
// We need S16 format. If unavailable, skip this device
if(!(info.nativeFormats & RTAUDIO_SINT16))
continue;
// If no sample rates supported, skip this device
if(info.sampleRates.size() < 1)
continue;
// Add new audio input device
dev.push_back(info);
index.push_back(i);
}
}
void
print_devices(vector<RtAudio::DeviceInfo>& dev)
{
// API map
map<int, string> api_map;
// Initialize API map
api_map[RtAudio::MACOSX_CORE] = "OS-X Core Audio";
api_map[RtAudio::WINDOWS_ASIO] = "Windows ASIO";
api_map[RtAudio::WINDOWS_DS] = "Windows Direct Sound";
api_map[RtAudio::UNIX_JACK] = "Jack Client";
api_map[RtAudio::LINUX_ALSA] = "Linux ALSA";
api_map[RtAudio::LINUX_OSS] = "Linux OSS";
api_map[RtAudio::RTAUDIO_DUMMY] = "RtAudio Dummy";
// Audio interface
RtAudio audio;
// Print current API
cerr << "Current API: " << api_map[audio.getCurrentApi()] << endl;
// Print every device
for(unsigned int i = 0; i < dev.size(); i++)
{
RtAudio::DeviceInfo info = dev[i];
// Print number of the device
cerr.width(3);
cerr << i << " "
<< info.name
<< (info.isDefaultInput ? " (Default input device)" : "") << endl;
}
}
int
input(void* out_buffer, void* in_buffer, unsigned int n_buffer_frames,
double stream_time, RtAudioStreamStatus status, void* data)
{
(void) out_buffer;
(void) stream_time;
(void) data;
// Check for audio input overflow
if(status == RTAUDIO_INPUT_OVERFLOW)
{
cerr << "Audio input overflow!"<< endl;
return 2;
}
// Copy audio input data to buffer
sample_t* src = (sample_t*) in_buffer;
for(unsigned int i = 0, ; i < n_buffer_frames; i++, src++)
{
buffer.push(*src);
}
return 0;
}
void
print_max_level(unsigned int sample_rate)
{
cout << "Terminating after " << MAX_TERM << " seconds..." << endl;
// Calculate maximal level
sample_t last_level = 0;
sample_t level;
for(unsigned int i = 0; i < MAX_TERM * sample_rate; i++)
{
// Wait if needed
if(buffer.size() == 0)
SLEEP(100);
level = buffer.front();
buffer.pop();
// Make level value absolute
if(level < 0)
{
level = -level;
}
// If current level is a (local) maximum, print it
if(level > last_level)
{
cout << "Maximum level: " << level << '\r';
last_level = level;
}
}
cout << endl;
}
void
cleanup(RtAudio& a)
{
// Stop audio stream
try
{
a.stopStream();
}
catch(RtError& e)
{
cerr << endl << e.getMessage() << endl;
exit(EXIT_FAILURE);
}
// Close audio stream
if(a.isStreamOpen())
a.closeStream();
}
int
main(int argc, char** argv)
{
// Sound input
RtAudio adc;
// Configuration variables
int auto_thres = AUTO_THRES;
bool max_level = false;
bool verbose = true;
int silence_thres = SILENCE_THRES;
bool list_input_devices = false;
int device_number = 0;
// Getopt variables
int ch, option_index;
static struct option long_options[] =
{
{"auto-thres", 0, 0, 'a'},
{"device", 1, 0, 'd'},
{"list-devices", 0, 0, 'l'},
{"help", 0, 0, 'h'},
{"max-level", 0, 0, 'm'},
{"silent", 0, 0, 's'},
{"threshold", 1, 0, 't'},
{"version", 0, 0, 'v'},
{ 0, 0, 0, 0 }
};
// Process command line arguments
while(true)
{
ch = getopt_long(argc, argv, "a:d:lhmst:v", long_options, &option_index);
if(ch == -1)
break;
switch(ch)
{
// Auto threshold
case 'a':
auto_thres = atoi(optarg);
break;
// Device (number)
case 'd':
device_number = atoi(optarg);
break;
// List devices
case 'l':
list_input_devices = true;
break;
// Help
case 'h':
print_help();
exit(EXIT_SUCCESS);
break;
// Maximal level
case 'm':
max_level = true;
break;
// Silent
case 's':
verbose = false;
break;
// Threshold
case 't':
auto_thres = 0;
silence_thres = atoi(optarg);
break;
// Version
case 'v':
print_version();
exit(EXIT_SUCCESS);
break;
// Unknown options
default:
print_help();
exit(EXIT_FAILURE);
break;
}
}
// Print version
if(verbose)
{
print_version();
cerr << endl;
}
// Make RtAudio part verbose too
if(verbose)
adc.showWarnings(true);
// If no sound devices found, exit
if(adc.getDeviceCount() < 1)
{
cerr << "No audio devices found!" << endl;
exit(EXIT_FAILURE);
}
// Get list of device
list_devices(devices, device_indexes);
// If requested, print list of devices and exit
if(list_input_devices)
{
print_devices(devices);
exit(EXIT_SUCCESS);
}
// Specify parameters of the audio stream
unsigned int buffer_frames = 512;
unsigned int sample_rate = 192000;
RtAudio::StreamParameters input_params;
input_params.deviceId = device_indexes[device_number];
input_params.nChannels = 1;
input_params.firstChannel = 0;
// Open and start audio stream
try
{
adc.openStream(NULL, &input_params, RTAUDIO_SINT16,
sample_rate, &buffer_frames, &input, NULL);
adc.startStream();
}
catch(RtError& e)
{
cerr << endl << e.getMessage() << endl;
cleanup(adc);
}
// If calculating maximal level is requested, do so and exit
if(max_level)
{
print_max_level(sample_rate);
cleanup(adc);
exit(EXIT_SUCCESS);
}
// Stop and close audio stream
cleanup(adc);
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include "SDL.h"
#include "core/log.h"
#include "core/str.h"
#include "core/interpolate.h"
#include "core/os.h"
#include "core/ecs-systems.h"
#include "core/vfs_imagegenerator.h"
#include "core/vfs_defaultshaders.h"
#include "core/proto.h"
#include "core/viewport.h"
#include "render/debuggl.h"
#include "render/fonts.h"
#include "render/init.h"
#include "render/fontcache.h"
#include "render/scalablesprite.h"
#include "render/shaderattribute2d.h"
#include "render/texturecache.h"
#include "render/viewport.h"
#include "render/shader.h"
#include "render/spriterender.h"
#include "render/viewporthandler.h"
#include "gui/root.h"
#include "gui/widget.h"
#include "window/key.h"
#include "window/imguilibrary.h"
#include "window/imgui_ext.h"
#include "window/filesystem.h"
#include "window/sdllibrary.h"
#include "window/sdlwindow.h"
#include "window/sdlglcontext.h"
#include "window/engine.h"
#include "engine/loadworld.h"
#include "engine/systems.h"
#include "engine/dukintegration.h"
#include "engine/dukmathbindings.h"
#include "engine/dukprint.h"
#include "engine/input.h"
#include "engine/objectemplate.h"
#include "engine/components.h"
#include "engine/cameradata.h"
#include "imgui/imgui.h"
#include "imgui/imgui_internal.h"
LOG_SPECIFY_DEFAULT_LOGGER("samples-gui")
using namespace euphoria::core;
using namespace euphoria::gui;
using namespace euphoria::render;
using namespace euphoria::window;
using namespace euphoria::engine;
// todo(Gustav): move to window/imgui_ext
bool
ImWidget(const char* title, Sizef* s)
{
return ImGui::DragFloat2(title, &s->width);
}
bool
ImWidget(const char* title, vec2f* v)
{
return ImGui::DragFloat2(title, &v->x);
}
bool
ImWidget(const char* title, bool b)
{
bool bb = b;
ImGui::Checkbox(title, &bb);
return false;
}
bool
ImWidget(const char* title, bool* b)
{
return ImGui::Checkbox(title, b);
}
bool
ImWidget(const char* title, euphoria::gui::Lrtb* p)
{
auto same_line = []()
{
ImGui::SameLine(0, ImGui::GetStyle().ItemInnerSpacing.x);
};
ImGui::PushID(title);
ImGui::BeginGroup();
ImGui::PushMultiItemsWidths(4, ImGui::CalcItemWidth());
bool changed = ImGui::InputFloat("L", &p->left);
ImGui::PopItemWidth();
same_line();
changed |= ImGui::InputFloat("R", &p->right);
ImGui::PopItemWidth();
same_line();
changed |= ImGui::InputFloat("T", &p->top);
ImGui::PopItemWidth();
same_line();
changed |= ImGui::InputFloat("B", &p->bottom);
ImGui::PopItemWidth();
same_line();
ImGui::Text("%s", title);
ImGui::EndGroup();
ImGui::PopID();
return changed;
}
bool
ImWidget(const char* title, Rectf* r)
{
return ImGui::InputFloat4(title, &r->left);
}
bool
ImWidget(UiState* state)
{
ImWidget("mouse", &state->mouse);
ImWidget("down", &state->mouse_down);
ImWidget("hot", state->hot != nullptr);
ImWidget("active", state->active != nullptr);
ImWidget("has active", &state->has_active);
return false;
}
bool
ImWidget(Widget* w)
{
ImWidget("margin", &w->margin);
ImWidget("padding", &w->padding);
ImWidget("rect", &w->rect_);
return false;
}
bool
ImWidget(LayoutContainer* container)
{
for(int i=0; i<container->widgets_.size(); i+= 1)
{
auto widget = container->widgets_[i];
if(ImGui::TreeNode(widget->name.c_str()))
{
ImGui::PushID(i);
ImWidget(widget.get());
ImGui::PopID();
ImGui::TreePop();
}
}
return false;
}
void
DebugUi(Root* root)
{
ImWidget("size", &root->size);
ImWidget(&root->state);
ImWidget(&root->container);
}
int
main(int argc, char* argv[])
{
Engine engine;
if(const auto ret = engine.Setup(argparse::Arguments::Extract(argc, argv)) != 0; ret != 0)
{
return ret;
}
engine.file_system->SetWrite
(
std::make_shared<vfs::FileSystemWriteFolder>(GetCurrentDirectory())
);
TextureCache cache {engine.file_system.get()};
const auto clear_color = Color::Blue;
ViewportHandler viewport_handler;
int window_width = 800;
int window_height = 600;
if
(
engine.CreateWindow
(
"euphoria gui demo",
window_width,
window_height,
true
) == false
)
{
return -1;
}
viewport_handler.SetSize(window_width, window_height);
Shader shader;
attributes2d::PrebindShader(&shader);
shader.Load(engine.file_system.get(), vfs::FilePath{"~/shaders/sprite"});
SpriteRenderer renderer(&shader);
FontCache font_cache {engine.file_system.get(), &cache};
auto root = Root{Sizef::FromWidthHeight(window_width, window_height)};
const auto gui_loaded = root.Load
(
engine.file_system.get(),
&font_cache,
vfs::FilePath{"~/gui.json"},
&cache
);
if(gui_loaded == false)
{
return -1;
}
Use(&shader);
shader.SetUniform(shader.GetUniform("image"), 0);
Uint64 now = SDL_GetPerformanceCounter();
Uint64 last = 0;
// SDL_StartTextInput();
bool running = true;
constexpr bool show_imgui = true;
int window_mouse_x = 0;
int window_mouse_y = 0;
SDL_GetMouseState(&window_mouse_x, &window_mouse_y);
bool mouse_lmb_down = false;
engine.init->Use2d();
while(running)
{
last = now;
now = SDL_GetPerformanceCounter();
const float dt = (now - last) * 1.0f / SDL_GetPerformanceFrequency();
SDL_Event e;
// imgui
if(show_imgui)
{
engine.imgui->StartNewFrame();
ImGui::Begin("Gui");
DebugUi(&root);
ImGui::End();
}
while(SDL_PollEvent(&e) != 0)
{
if(e.type == SDL_QUIT)
{
running = false;
}
if(show_imgui)
{
engine.imgui->ProcessEvents(&e);
}
if(engine.HandleResize(e, &window_width, &window_height))
{
viewport_handler.SetSize(window_width, window_height);
root.Resize(Sizef::FromWidthHeight(window_width, window_height));
}
if(e.type == SDL_MOUSEMOTION)
{
window_mouse_x = e.motion.x;
window_mouse_y = e.motion.y;
}
else if(e.type == SDL_KEYUP || e.type == SDL_KEYDOWN)
{
const bool down = e.type == SDL_KEYDOWN;
const auto key = ToKey(e.key.keysym);
if(down && key == Key::ESCAPE)
{
running = false;
}
}
else if(e.type == SDL_MOUSEBUTTONDOWN
|| e.type == SDL_MOUSEBUTTONUP)
{
const bool down = e.type == SDL_MOUSEBUTTONDOWN;
window_mouse_x = e.button.x;
window_mouse_y = e.button.y;
if(e.button.button == SDL_BUTTON_LEFT)
{
mouse_lmb_down = down;
}
}
else if(e.type == SDL_TEXTINPUT)
{
// const std::string& input = e.text.text;
}
}
root.SetInputMouse
(
vec2f{window_mouse_x, window_mouse_y},
mouse_lmb_down
);
root.Step(dt);
engine.init->ClearScreen(clear_color);
root.Render(&renderer);
if(show_imgui)
{
engine.imgui->Render();
}
SDL_GL_SwapWindow(engine.window->window);
}
return 0;
}
<commit_msg>using drag inputs, proper widget for rectf now, gui events are now blocked by imgui<commit_after>#include "SDL.h"
#include "core/log.h"
#include "core/str.h"
#include "core/interpolate.h"
#include "core/os.h"
#include "core/ecs-systems.h"
#include "core/vfs_imagegenerator.h"
#include "core/vfs_defaultshaders.h"
#include "core/proto.h"
#include "core/viewport.h"
#include "render/debuggl.h"
#include "render/fonts.h"
#include "render/init.h"
#include "render/fontcache.h"
#include "render/scalablesprite.h"
#include "render/shaderattribute2d.h"
#include "render/texturecache.h"
#include "render/viewport.h"
#include "render/shader.h"
#include "render/spriterender.h"
#include "render/viewporthandler.h"
#include "gui/root.h"
#include "gui/widget.h"
#include "window/key.h"
#include "window/imguilibrary.h"
#include "window/imgui_ext.h"
#include "window/filesystem.h"
#include "window/sdllibrary.h"
#include "window/sdlwindow.h"
#include "window/sdlglcontext.h"
#include "window/engine.h"
#include "engine/loadworld.h"
#include "engine/systems.h"
#include "engine/dukintegration.h"
#include "engine/dukmathbindings.h"
#include "engine/dukprint.h"
#include "engine/input.h"
#include "engine/objectemplate.h"
#include "engine/components.h"
#include "engine/cameradata.h"
#include "imgui/imgui.h"
#include "imgui/imgui_internal.h"
LOG_SPECIFY_DEFAULT_LOGGER("samples-gui")
using namespace euphoria::core;
using namespace euphoria::gui;
using namespace euphoria::render;
using namespace euphoria::window;
using namespace euphoria::engine;
// todo(Gustav): move to window/imgui_ext
bool
ImWidget(const char* title, Sizef* s)
{
return ImGui::DragFloat2(title, &s->width);
}
bool
ImWidget(const char* title, vec2f* v)
{
return ImGui::DragFloat2(title, &v->x);
}
bool
ImWidget(const char* title, bool b)
{
bool bb = b;
ImGui::Checkbox(title, &bb);
return false;
}
bool
ImWidget(const char* title, bool* b)
{
return ImGui::Checkbox(title, b);
}
bool
ImWidget(const char* title, euphoria::gui::Lrtb* p)
{
const auto spacing = ImGui::GetStyle().ItemInnerSpacing.x;
ImGui::PushID(title);
ImGui::BeginGroup();
ImGui::PushMultiItemsWidths(4, ImGui::CalcItemWidth());
bool changed = ImGui::DragFloat("L", &p->left);
ImGui::PopItemWidth();
ImGui::SameLine(0, spacing);
changed |= ImGui::DragFloat("R", &p->right);
ImGui::PopItemWidth();
ImGui::SameLine(0, spacing);
changed |= ImGui::DragFloat("T", &p->top);
ImGui::PopItemWidth();
ImGui::SameLine(0, spacing);
changed |= ImGui::DragFloat("B", &p->bottom);
ImGui::PopItemWidth();
ImGui::SameLine(0, spacing);
ImGui::Text("%s", title);
ImGui::EndGroup();
ImGui::PopID();
return changed;
}
bool
ImWidget(const char* title, Rectf* r)
{
const auto spacing = ImGui::GetStyle().ItemInnerSpacing.x;
ImGui::PushID(title);
ImGui::BeginGroup();
ImGui::PushMultiItemsWidths(4, ImGui::CalcItemWidth());
bool changed = ImGui::DragFloat("L", &r->left);
ImGui::PopItemWidth();
ImGui::SameLine(0, spacing);
changed |= ImGui::DragFloat("R", &r->right);
ImGui::PopItemWidth();
ImGui::SameLine(0, spacing);
changed |= ImGui::DragFloat("T", &r->top);
ImGui::PopItemWidth();
ImGui::SameLine(0, spacing);
changed |= ImGui::DragFloat("B", &r->bottom);
ImGui::PopItemWidth();
ImGui::SameLine(0, spacing);
ImGui::Text("%s", title);
ImGui::EndGroup();
ImGui::PopID();
return changed;
}
bool
ImWidget(UiState* state)
{
ImWidget("mouse", &state->mouse);
ImWidget("down", &state->mouse_down);
ImWidget("hot", state->hot != nullptr);
ImWidget("active", state->active != nullptr);
ImWidget("has active", &state->has_active);
return false;
}
bool
ImWidget(Widget* w)
{
ImWidget("margin", &w->margin);
ImWidget("padding", &w->padding);
ImWidget("rect", &w->rect_);
return false;
}
bool
ImWidget(LayoutContainer* container)
{
for(int i=0; i<container->widgets_.size(); i+= 1)
{
auto widget = container->widgets_[i];
if(ImGui::TreeNode(widget->name.c_str()))
{
ImGui::PushID(i);
ImWidget(widget.get());
ImGui::PopID();
ImGui::TreePop();
}
}
return false;
}
void
DebugUi(Root* root)
{
ImWidget("size", &root->size);
ImWidget(&root->state);
ImWidget(&root->container);
}
int
main(int argc, char* argv[])
{
Engine engine;
if(const auto ret = engine.Setup(argparse::Arguments::Extract(argc, argv)) != 0; ret != 0)
{
return ret;
}
engine.file_system->SetWrite
(
std::make_shared<vfs::FileSystemWriteFolder>(GetCurrentDirectory())
);
TextureCache cache {engine.file_system.get()};
const auto clear_color = Color::Blue;
ViewportHandler viewport_handler;
int window_width = 800;
int window_height = 600;
if
(
engine.CreateWindow
(
"euphoria gui demo",
window_width,
window_height,
true
) == false
)
{
return -1;
}
viewport_handler.SetSize(window_width, window_height);
Shader shader;
attributes2d::PrebindShader(&shader);
shader.Load(engine.file_system.get(), vfs::FilePath{"~/shaders/sprite"});
SpriteRenderer renderer(&shader);
FontCache font_cache {engine.file_system.get(), &cache};
auto root = Root{Sizef::FromWidthHeight(window_width, window_height)};
const auto gui_loaded = root.Load
(
engine.file_system.get(),
&font_cache,
vfs::FilePath{"~/gui.json"},
&cache
);
if(gui_loaded == false)
{
return -1;
}
Use(&shader);
shader.SetUniform(shader.GetUniform("image"), 0);
Uint64 now = SDL_GetPerformanceCounter();
Uint64 last = 0;
// SDL_StartTextInput();
bool running = true;
constexpr bool show_imgui = true;
int window_mouse_x = 0;
int window_mouse_y = 0;
SDL_GetMouseState(&window_mouse_x, &window_mouse_y);
bool mouse_lmb_down = false;
engine.init->Use2d();
while(running)
{
last = now;
now = SDL_GetPerformanceCounter();
const float dt = (now - last) * 1.0f / SDL_GetPerformanceFrequency();
SDL_Event e;
// imgui
if(show_imgui)
{
engine.imgui->StartNewFrame();
ImGui::Begin("Gui");
DebugUi(&root);
ImGui::End();
}
while(SDL_PollEvent(&e) != 0)
{
if(e.type == SDL_QUIT)
{
running = false;
}
if(show_imgui)
{
engine.imgui->ProcessEvents(&e);
}
if(engine.HandleResize(e, &window_width, &window_height))
{
viewport_handler.SetSize(window_width, window_height);
root.Resize(Sizef::FromWidthHeight(window_width, window_height));
}
if(e.type == SDL_MOUSEMOTION)
{
window_mouse_x = e.motion.x;
window_mouse_y = e.motion.y;
}
else if(e.type == SDL_KEYUP || e.type == SDL_KEYDOWN)
{
const bool down = e.type == SDL_KEYDOWN;
const auto key = ToKey(e.key.keysym);
if(down && key == Key::ESCAPE)
{
running = false;
}
}
else if(e.type == SDL_MOUSEBUTTONDOWN
|| e.type == SDL_MOUSEBUTTONUP)
{
const bool down = e.type == SDL_MOUSEBUTTONDOWN;
window_mouse_x = e.button.x;
window_mouse_y = e.button.y;
if(e.button.button == SDL_BUTTON_LEFT)
{
mouse_lmb_down = down;
}
}
else if(e.type == SDL_TEXTINPUT)
{
// const std::string& input = e.text.text;
}
}
if(show_imgui && ImGui::GetIO().WantCaptureMouse)
{
}
else
{
root.SetInputMouse
(
vec2f{window_mouse_x, window_mouse_y},
mouse_lmb_down
);
}
root.Step(dt);
engine.init->ClearScreen(clear_color);
root.Render(&renderer);
if(show_imgui)
{
engine.imgui->Render();
}
SDL_GL_SwapWindow(engine.window->window);
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "id3.hpp"
inline size_t sum_counts(size_t* counters, size_t n_counters) {
size_t total = 0;
for (uint i = 0; i < n_counters; i++) {
total += counters[i];
}
return total;
}
Node* newNode(size_t n_classes) {
Node* node = static_cast<Node*>(malloc(sizeof(Node)));
node->feature_id = NO_FEATURE;
node->counters = static_cast<size_t*>(malloc(n_classes * sizeof(size_t)));
node->n_instances = NO_INSTANCE;
node->score = INFINITY;
node->split_value = NO_SPLIT_VALUE;
node->left_child = nullptr;
node->right_child = nullptr;
return node;
}
Density* computeDensities(data_t* data, size_t n_instances, size_t n_features,
size_t n_classes, data_t nan_value) {
size_t s = sizeof(data_t);
Density* densities = static_cast<Density*>(malloc(n_features * sizeof(Density)));
data_t* sorted_values = static_cast<data_t*>(malloc(n_instances * s));
for (uint f = 0; f < n_features; f++) {
densities[f].quartiles = static_cast<data_t*>(malloc(4 * s));
densities[f].deciles = static_cast<data_t*>(malloc(10 * s));
densities[f].percentiles = static_cast<data_t*>(malloc(100 * s));
densities[f].counters_left = static_cast<size_t*>(malloc(n_classes * sizeof(size_t)));
densities[f].counters_right = static_cast<size_t*>(malloc(n_classes * sizeof(size_t)));
densities[f].counters_nan = static_cast<size_t*>(malloc(n_classes * sizeof(size_t)));
// Putting nan values aside
bool is_categorical = true;
size_t n_acceptable = 0;
data_t data_point;
for (uint i = 0; i < n_instances; i++) {
data_point = data[i * n_features + f];
if (data_point != nan_value) {
sorted_values[n_acceptable] = data_point;
n_acceptable++;
if (is_categorical && !(round(data_point) == data_point)) {
is_categorical = false;
}
}
}
densities[f].is_categorical = is_categorical;
// Sorting acceptable values
size_t k;
data_t x;
for (uint i = 0; i < n_acceptable; i++) {
x = sorted_values[i];
k = i;
while (k > 0 && sorted_values[k - 1] > x) {
sorted_values[k] = sorted_values[k - 1];
k--;
}
sorted_values[k] = x;
}
// Computing quartiles, deciles, percentiles
float step_size = static_cast<float>(n_acceptable) / 100.0f;
float current_index = 0.0;
int rounded_index = 0;
for (uint i = 0; i < 10; i++) {
densities[f].deciles[i] = sorted_values[rounded_index];
for (uint k = 0; k < 10; k++) {
rounded_index = static_cast<int>(floor(current_index));
densities[f].percentiles[10 * i + k] = sorted_values[rounded_index];
current_index += step_size;
}
}
}
free(sorted_values);
return densities;
}
inline float ShannonEntropy(float probability) {
return -probability * log2(probability);
}
inline float GiniCoefficient(float probability) {
return 1.f - probability * probability;
}
inline double getFeatureCost(Density* density, size_t n_classes) {
size_t n_left = sum_counts(density->counters_left, n_classes);
size_t n_right = sum_counts(density->counters_right, n_classes);
size_t total = n_left + n_right;
float left_rate = static_cast<float>(n_left) / static_cast<float>(total);
float right_rate = static_cast<float>(n_right) / static_cast<float>(total);
if (n_left == 0 || n_right == 0) {
return COST_OF_EMPTINESS;
}
double left_cost = 0.0, right_cost = 0.0;
size_t* counters_left = density->counters_left;
size_t* counters_right = density->counters_right;
if (n_left > 0) {
size_t n_p;
for (uint i = 0; i < n_classes; i++) {
n_p = counters_left[i];
if (n_p > 0) {
left_cost += ShannonEntropy(static_cast<float>(n_p) / static_cast<float>(n_left));
}
}
left_cost *= left_rate;
}
if (n_right > 0) {
size_t n_n;
for (uint i = 0; i < n_classes; i++) {
n_n = counters_right[i];
if (n_n > 0) {
right_cost += ShannonEntropy(static_cast<float>(n_n) / static_cast<float>(n_right));
}
}
right_cost *= right_rate;
}
return left_cost + right_cost;
}
void initRoot(Node* root, target_t* const targets, size_t n_instances, size_t n_classes) {
memset(root->counters, 0x00, n_classes * sizeof(size_t));
for (uint i = 0; i < n_instances; i++) {
root->counters[targets[i]]++;
}
}
Tree* ID3(data_t* const data, target_t* const targets, size_t n_instances,
size_t n_features, TreeConfig* config) {
Node* current_node = newNode(config->n_classes);
current_node->id = 0;
current_node->n_instances = n_instances;
current_node->score = 0.0;
initRoot(current_node, targets, n_instances, config->n_classes);
Node* child_node;
Tree* tree = static_cast<Tree*>(malloc(sizeof(Tree)));
tree->root = current_node;
tree->config = config;
tree->n_nodes = 1;
tree->n_classes = config->n_classes;
tree->n_features = n_features;
bool still_going = 1;
size_t* belongs_to = static_cast<size_t*>(calloc(n_instances, sizeof(size_t)));
size_t** split_sides = static_cast<size_t**>(malloc(2 * sizeof(size_t*)));
Splitter<target_t> splitter = {
config->task,
current_node,
n_instances,
nullptr,
config->n_classes,
belongs_to,
static_cast<size_t>(NO_FEATURE),
n_features,
targets,
config->nan_value
};
Density* densities = computeDensities(data, n_instances, n_features,
config->n_classes, config->nan_value);
Density* next_density;
size_t best_feature = 0;
std::queue<Node*> queue;
queue.push(current_node);
while ((tree->n_nodes < config->max_nodes) && !queue.empty() && still_going) {
current_node = queue.front(); queue.pop();
double e_cost = INFINITY;
double lowest_e_cost = INFINITY;
splitter.node = current_node;
for (uint f = 0; f < n_features; f++) {
splitter.feature_id = f;
e_cost = evaluateByThreshold(&splitter, &densities[f], data, config->partitioning);
if (e_cost < lowest_e_cost) {
lowest_e_cost = e_cost;
best_feature = f;
}
}
next_density = &densities[best_feature];
if ((best_feature != static_cast<size_t>(current_node->feature_id))
|| (next_density->split_value != current_node->split_value)) { // TO REMOVE ?
next_density = &densities[best_feature];
size_t split_totals[2] = {
sum_counts(next_density->counters_left, config->n_classes),
sum_counts(next_density->counters_right, config->n_classes)
};
if (split_totals[0] && split_totals[1]) {
Node* new_children = static_cast<Node*>(malloc(2 * sizeof(Node)));
data_t split_value = next_density->split_value;
current_node->score = lowest_e_cost;
current_node->feature_id = static_cast<int>(best_feature);
current_node->split_value = split_value;
current_node->left_child = &new_children[0];
current_node->right_child = &new_children[1];
split_sides[0] = next_density->counters_left;
split_sides[1] = next_density->counters_right;
for (uint i = 0; i < 2; i++) {
for (uint j = 0; j < n_instances; j++) {
bool is_on_the_left = (data[j * n_features + best_feature] < split_value) ? 1 : 0;
if (belongs_to[j] == static_cast<size_t>(current_node->id)) {
if (is_on_the_left * (1 - i) + (1 - is_on_the_left) * i) {
belongs_to[j] = tree->n_nodes;
}
}
}
child_node = &new_children[i];
child_node->id = static_cast<int>(tree->n_nodes);
child_node->split_value = split_value;
child_node->n_instances = split_totals[i];
child_node->score = COST_OF_EMPTINESS;
child_node->feature_id = static_cast<int>(best_feature);
child_node->left_child = nullptr;
child_node->right_child = nullptr;
child_node->counters = static_cast<size_t*>(malloc(config->n_classes * sizeof(size_t)));
memcpy(child_node->counters, split_sides[i], config->n_classes * sizeof(size_t));
if (lowest_e_cost > config->min_threshold) {
queue.push(child_node);
}
++tree->n_nodes;
}
}
}
}
free(belongs_to);
free(split_sides);
return tree;
}
float* classify(data_t* const data, size_t n_instances, size_t n_features,
Tree* const tree, TreeConfig* config) {
assert(config->task == gbdf_task::CLASSIFICATION_TASK);
Node *current_node;
size_t feature;
size_t n_classes = config->n_classes;
float* predictions = static_cast<float*>(malloc(n_instances * n_classes * sizeof(float)));
for (uint k = 0; k < n_instances; k++) {
bool improving = true;
current_node = tree->root;
while (improving) {
feature = current_node->feature_id;
if (current_node->left_child != NULL) {
if (data[k * n_features + feature] >= current_node->split_value) {
current_node = current_node->right_child;
}
else {
current_node = current_node->left_child;
}
}
else {
improving = false;
}
}
size_t node_instances = current_node->n_instances;
for (uint c = 0; c < n_classes; c++) {
predictions[k * n_classes + c] = static_cast<float>(current_node->counters[c]) / static_cast<float>(node_instances);
}
}
return predictions;
}
data_t* regress(data_t* const data, size_t n_instances, size_t n_features,
Tree* const tree, TreeConfig* config) {
assert(config->task == gbdf_task::REGRESSION_TASK);
Node *current_node;
size_t feature;
data_t* predictions = static_cast<data_t*>(malloc(n_instances * sizeof(data_t)));
for (uint k = 0; k < n_instances; k++) {
bool improving = true;
current_node = tree->root;
while (improving) {
feature = current_node->feature_id;
if (current_node->left_child != NULL) {
if (data[k * n_features + feature] >= current_node->split_value) {
current_node = current_node->right_child;
}
else {
current_node = current_node->left_child;
}
}
else {
improving = false;
}
}
// predictions[k] = stuff... -> TODO
// TODO : define a new type of struct
}
return predictions;
}
<commit_msg>Use new operator rather than that black magic<commit_after>#include "id3.hpp"
inline size_t sum_counts(size_t* counters, size_t n_counters) {
size_t total = 0;
for (uint i = 0; i < n_counters; i++) {
total += counters[i];
}
return total;
}
Node* newNode(size_t n_classes) {
Node* node = new Node;
node->feature_id = NO_FEATURE;
node->counters = new size_t[n_classes];
node->n_instances = NO_INSTANCE;
node->score = INFINITY;
node->split_value = NO_SPLIT_VALUE;
node->left_child = nullptr;
node->right_child = nullptr;
return node;
}
Density* computeDensities(data_t* data, size_t n_instances, size_t n_features,
size_t n_classes, data_t nan_value) {
Density* densities = new Density[n_features];
data_t* sorted_values = new data_t[n_instances];
for (uint f = 0; f < n_features; f++) {
densities[f].quartiles = new data_t[4];
densities[f].deciles = new data_t[10];
densities[f].percentiles = new data_t[100];
densities[f].counters_left = new size_t[n_classes];
densities[f].counters_right = new size_t[n_classes];
densities[f].counters_nan = new size_t[n_classes];
// Putting nan values aside
bool is_categorical = true;
size_t n_acceptable = 0;
data_t data_point;
for (uint i = 0; i < n_instances; i++) {
data_point = data[i * n_features + f];
if (data_point != nan_value) {
sorted_values[n_acceptable] = data_point;
n_acceptable++;
if (is_categorical && !(round(data_point) == data_point)) {
is_categorical = false;
}
}
}
densities[f].is_categorical = is_categorical;
// Sorting acceptable values
size_t k;
data_t x;
for (uint i = 0; i < n_acceptable; i++) {
x = sorted_values[i];
k = i;
while (k > 0 && sorted_values[k - 1] > x) {
sorted_values[k] = sorted_values[k - 1];
k--;
}
sorted_values[k] = x;
}
// Computing quartiles, deciles, percentiles
float step_size = static_cast<float>(n_acceptable) / 100.0f;
float current_index = 0.0;
int rounded_index = 0;
for (uint i = 0; i < 10; i++) {
densities[f].deciles[i] = sorted_values[rounded_index];
for (uint k = 0; k < 10; k++) {
rounded_index = static_cast<int>(floor(current_index));
densities[f].percentiles[10 * i + k] = sorted_values[rounded_index];
current_index += step_size;
}
}
}
free(sorted_values);
return densities;
}
inline float ShannonEntropy(float probability) {
return -probability * log2(probability);
}
inline float GiniCoefficient(float probability) {
return 1.f - probability * probability;
}
inline double getFeatureCost(Density* density, size_t n_classes) {
size_t n_left = sum_counts(density->counters_left, n_classes);
size_t n_right = sum_counts(density->counters_right, n_classes);
size_t total = n_left + n_right;
float left_rate = static_cast<float>(n_left) / static_cast<float>(total);
float right_rate = static_cast<float>(n_right) / static_cast<float>(total);
if (n_left == 0 || n_right == 0) {
return COST_OF_EMPTINESS;
}
double left_cost = 0.0, right_cost = 0.0;
size_t* counters_left = density->counters_left;
size_t* counters_right = density->counters_right;
if (n_left > 0) {
size_t n_p;
for (uint i = 0; i < n_classes; i++) {
n_p = counters_left[i];
if (n_p > 0) {
left_cost += ShannonEntropy(static_cast<float>(n_p) / static_cast<float>(n_left));
}
}
left_cost *= left_rate;
}
if (n_right > 0) {
size_t n_n;
for (uint i = 0; i < n_classes; i++) {
n_n = counters_right[i];
if (n_n > 0) {
right_cost += ShannonEntropy(static_cast<float>(n_n) / static_cast<float>(n_right));
}
}
right_cost *= right_rate;
}
return left_cost + right_cost;
}
void initRoot(Node* root, target_t* const targets, size_t n_instances, size_t n_classes) {
memset(root->counters, 0x00, n_classes * sizeof(size_t));
for (uint i = 0; i < n_instances; i++) {
root->counters[targets[i]]++;
}
}
Tree* ID3(data_t* const data, target_t* const targets, size_t n_instances,
size_t n_features, TreeConfig* config) {
Node* current_node = newNode(config->n_classes);
current_node->id = 0;
current_node->n_instances = n_instances;
current_node->score = 0.0;
initRoot(current_node, targets, n_instances, config->n_classes);
Node* child_node;
Tree* tree = new Tree;
tree->root = current_node;
tree->config = config;
tree->n_nodes = 1;
tree->n_classes = config->n_classes;
tree->n_features = n_features;
bool still_going = 1;
size_t* belongs_to = new size_t[n_instances];
size_t** split_sides = new size_t*[2];
Splitter<target_t> splitter = {
config->task,
current_node,
n_instances,
nullptr,
config->n_classes,
belongs_to,
static_cast<size_t>(NO_FEATURE),
n_features,
targets,
config->nan_value
};
Density* densities = computeDensities(data, n_instances, n_features,
config->n_classes, config->nan_value);
Density* next_density;
size_t best_feature = 0;
std::queue<Node*> queue;
queue.push(current_node);
while ((tree->n_nodes < config->max_nodes) && !queue.empty() && still_going) {
current_node = queue.front(); queue.pop();
double e_cost = INFINITY;
double lowest_e_cost = INFINITY;
splitter.node = current_node;
for (uint f = 0; f < n_features; f++) {
splitter.feature_id = f;
e_cost = evaluateByThreshold(&splitter, &densities[f], data, config->partitioning);
if (e_cost < lowest_e_cost) {
lowest_e_cost = e_cost;
best_feature = f;
}
}
next_density = &densities[best_feature];
if ((best_feature != static_cast<size_t>(current_node->feature_id))
|| (next_density->split_value != current_node->split_value)) { // TO REMOVE ?
next_density = &densities[best_feature];
size_t split_totals[2] = {
sum_counts(next_density->counters_left, config->n_classes),
sum_counts(next_density->counters_right, config->n_classes)
};
if (split_totals[0] && split_totals[1]) {
Node* new_children = new Node[2];
data_t split_value = next_density->split_value;
current_node->score = lowest_e_cost;
current_node->feature_id = static_cast<int>(best_feature);
current_node->split_value = split_value;
current_node->left_child = &new_children[0];
current_node->right_child = &new_children[1];
split_sides[0] = next_density->counters_left;
split_sides[1] = next_density->counters_right;
for (uint i = 0; i < 2; i++) {
for (uint j = 0; j < n_instances; j++) {
bool is_on_the_left = (data[j * n_features + best_feature] < split_value) ? 1 : 0;
if (belongs_to[j] == static_cast<size_t>(current_node->id)) {
if (is_on_the_left * (1 - i) + (1 - is_on_the_left) * i) {
belongs_to[j] = tree->n_nodes;
}
}
}
child_node = &new_children[i];
child_node->id = static_cast<int>(tree->n_nodes);
child_node->split_value = split_value;
child_node->n_instances = split_totals[i];
child_node->score = COST_OF_EMPTINESS;
child_node->feature_id = static_cast<int>(best_feature);
child_node->left_child = nullptr;
child_node->right_child = nullptr;
child_node->counters = static_cast<size_t*>(malloc(config->n_classes * sizeof(size_t)));
memcpy(child_node->counters, split_sides[i], config->n_classes * sizeof(size_t));
if (lowest_e_cost > config->min_threshold) {
queue.push(child_node);
}
++tree->n_nodes;
}
}
}
}
free(belongs_to);
free(split_sides);
return tree;
}
float* classify(data_t* const data, size_t n_instances, size_t n_features,
Tree* const tree, TreeConfig* config) {
assert(config->task == gbdf_task::CLASSIFICATION_TASK);
Node *current_node;
size_t feature;
size_t n_classes = config->n_classes;
float* predictions = new float[n_instances * n_classes];
for (uint k = 0; k < n_instances; k++) {
bool improving = true;
current_node = tree->root;
while (improving) {
feature = current_node->feature_id;
if (current_node->left_child != NULL) {
if (data[k * n_features + feature] >= current_node->split_value) {
current_node = current_node->right_child;
}
else {
current_node = current_node->left_child;
}
}
else {
improving = false;
}
}
size_t node_instances = current_node->n_instances;
for (uint c = 0; c < n_classes; c++) {
predictions[k * n_classes + c] = static_cast<float>(current_node->counters[c]) / static_cast<float>(node_instances);
}
}
return predictions;
}
data_t* regress(data_t* const data, size_t n_instances, size_t n_features,
Tree* const tree, TreeConfig* config) {
assert(config->task == gbdf_task::REGRESSION_TASK);
Node *current_node;
size_t feature;
data_t* predictions = new data_t[n_instances];
for (uint k = 0; k < n_instances; k++) {
bool improving = true;
current_node = tree->root;
while (improving) {
feature = current_node->feature_id;
if (current_node->left_child != NULL) {
if (data[k * n_features + feature] >= current_node->split_value) {
current_node = current_node->right_child;
}
else {
current_node = current_node->left_child;
}
}
else {
improving = false;
}
}
// predictions[k] = stuff... -> TODO
// TODO : define a new type of struct
}
return predictions;
}
<|endoftext|>
|
<commit_before>#ifndef _SDD_HOM_SUM_HH_
#define _SDD_HOM_SUM_HH_
#include <algorithm> // all_of, copy
#include <deque>
#include <initializer_list>
#include <iosfwd>
#include <stdexcept> //invalid_argument
#include <unordered_map>
#include <boost/container/flat_set.hpp>
#include "sdd/dd/definition.hh"
#include "sdd/dd/top.hh"
#include "sdd/hom/context_fwd.hh"
#include "sdd/hom/definition_fwd.hh"
#include "sdd/hom/evaluation_error.hh"
#include "sdd/hom/identity.hh"
#include "sdd/hom/local.hh"
#include "sdd/order/order.hh"
#include "sdd/util/packed.hh"
namespace sdd { namespace hom {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Sum homomorphism.
template <typename C>
class LIBSDD_ATTRIBUTE_PACKED sum
{
public:
/// @brief The type of the homomorphism operands' set.
typedef boost::container::flat_set<homomorphism<C>> operands_type;
private:
/// @brief The homomorphism operands' set.
const operands_type operands_;
public:
/// @brief Constructor.
sum(operands_type&& operands)
: operands_(std::move(operands))
{
}
/// @brief Evaluation.
SDD<C>
operator()(context<C>& cxt, const order<C>& o, const SDD<C>& x)
const
{
dd::sum_builder<C, SDD<C>> sum_operands(operands_.size());
for (const auto& op : operands_)
{
sum_operands.add(op(cxt, o, x));
}
try
{
return dd::sum(cxt.sdd_context(), std::move(sum_operands));
}
catch (top<C>& t)
{
evaluation_error<C> e(x);
e.add_top(t);
throw e;
}
}
/// @brief Skip variable predicate.
bool
skip(const order<C>& o)
const noexcept
{
return std::all_of( operands_.begin(), operands_.end()
, [&o](const homomorphism<C>& h){return h.skip(o);});
}
/// @brief Selector predicate
bool
selector()
const noexcept
{
return std::all_of( operands_.begin(), operands_.end()
, [](const homomorphism<C>& h){return h.selector();});
}
const operands_type&
operands()
const noexcept
{
return operands_;
}
};
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Equality of two sum.
/// @related sum
template <typename C>
inline
bool
operator==(const sum<C>& lhs, const sum<C>& rhs)
noexcept
{
return lhs.operands() == rhs.operands();
}
/// @internal
/// @related sum
template <typename C>
std::ostream&
operator<<(std::ostream& os, const sum<C>& s)
{
os << "(";
std::copy( s.operands().begin(), std::prev(s.operands().end())
, std::ostream_iterator<homomorphism<C>>(os, " + "));
return os << *std::prev(s.operands().end()) << ")";
}
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Help optimize an union's operands.
template <typename C>
struct sum_builder_helper
{
typedef void result_type;
typedef typename sum<C>::operands_type operands_type;
typedef std::deque<homomorphism<C>> hom_list_type;
typedef std::unordered_map<typename C::Identifier, hom_list_type> locals_type;
/// @brief Flatten nested sums.
void
operator()( const sum<C>& s
, const homomorphism<C>& h, operands_type& operands, locals_type& locals)
const
{
for (const auto& op : s.operands())
{
apply_visitor(*this, op->data(), op, operands, locals);
}
}
/// @brief Regroup locals.
void
operator()( const local<C>& l
, const homomorphism<C>& h, operands_type& operands, locals_type& locals)
const
{
auto insertion = locals.emplace(l.identifier(), hom_list_type());
insertion.first->second.emplace_back(l.hom());
}
/// @brief Insert normally all other operands.
template <typename T>
void
operator()(const T&, const homomorphism<C>& h, operands_type& operands, locals_type&)
const
{
operands.insert(h);
}
};
} // namespace hom
/*------------------------------------------------------------------------------------------------*/
/// @brief Create the Sum homomorphism.
/// @related homomorphism
template <typename C, typename InputIterator>
homomorphism<C>
Sum(const order<C>& o, InputIterator begin, InputIterator end)
{
const std::size_t size = std::distance(begin, end);
if (size == 0)
{
throw std::invalid_argument("Empty operands at Sum construction.");
}
typename hom::sum<C>::operands_type operands;
operands.reserve(size);
hom::sum_builder_helper<C> sbv;
typename hom::sum_builder_helper<C>::locals_type locals;
for (; begin != end; ++begin)
{
apply_visitor(sbv, (*begin)->data(), *begin, operands, locals);
}
// insert remaining locals
for (const auto& l : locals)
{
operands.insert(Local<C>(l.first, o, Sum<C>(o, l.second.begin(), l.second.end())));
}
if (operands.size() == 1)
{
return *operands.begin();
}
else
{
operands.shrink_to_fit();
return homomorphism<C>::create(mem::construct<hom::sum<C>>(), std::move(operands));
}
}
/*------------------------------------------------------------------------------------------------*/
/// @brief Create the Sum homomorphism.
/// @related homomorphism
template <typename C>
homomorphism<C>
Sum(const order<C>& o, std::initializer_list<homomorphism<C>> operands)
{
return Sum<C>(o, operands.begin(), operands.end());
}
/*------------------------------------------------------------------------------------------------*/
} // namespace sdd
namespace std {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Hash specialization for sdd::hom::sum.
template <typename C>
struct hash<sdd::hom::sum<C>>
{
std::size_t
operator()(const sdd::hom::sum<C>& s)
const noexcept
{
std::size_t seed = 0;
for (const auto& op : s.operands())
{
sdd::util::hash_combine(seed, op);
}
return seed;
}
};
/*------------------------------------------------------------------------------------------------*/
} // namespace std
#endif // _SDD_HOM_SUM_HH_
<commit_msg>Remove useless packed attribute.<commit_after>#ifndef _SDD_HOM_SUM_HH_
#define _SDD_HOM_SUM_HH_
#include <algorithm> // all_of, copy
#include <deque>
#include <initializer_list>
#include <iosfwd>
#include <stdexcept> //invalid_argument
#include <unordered_map>
#include <boost/container/flat_set.hpp>
#include "sdd/dd/definition.hh"
#include "sdd/dd/top.hh"
#include "sdd/hom/context_fwd.hh"
#include "sdd/hom/definition_fwd.hh"
#include "sdd/hom/evaluation_error.hh"
#include "sdd/hom/identity.hh"
#include "sdd/hom/local.hh"
#include "sdd/order/order.hh"
#include "sdd/util/packed.hh"
namespace sdd { namespace hom {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Sum homomorphism.
template <typename C>
class sum
{
public:
/// @brief The type of the homomorphism operands' set.
typedef boost::container::flat_set<homomorphism<C>> operands_type;
private:
/// @brief The homomorphism operands' set.
const operands_type operands_;
public:
/// @brief Constructor.
sum(operands_type&& operands)
: operands_(std::move(operands))
{
}
/// @brief Evaluation.
SDD<C>
operator()(context<C>& cxt, const order<C>& o, const SDD<C>& x)
const
{
dd::sum_builder<C, SDD<C>> sum_operands(operands_.size());
for (const auto& op : operands_)
{
sum_operands.add(op(cxt, o, x));
}
try
{
return dd::sum(cxt.sdd_context(), std::move(sum_operands));
}
catch (top<C>& t)
{
evaluation_error<C> e(x);
e.add_top(t);
throw e;
}
}
/// @brief Skip variable predicate.
bool
skip(const order<C>& o)
const noexcept
{
return std::all_of( operands_.begin(), operands_.end()
, [&o](const homomorphism<C>& h){return h.skip(o);});
}
/// @brief Selector predicate
bool
selector()
const noexcept
{
return std::all_of( operands_.begin(), operands_.end()
, [](const homomorphism<C>& h){return h.selector();});
}
const operands_type&
operands()
const noexcept
{
return operands_;
}
};
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Equality of two sum.
/// @related sum
template <typename C>
inline
bool
operator==(const sum<C>& lhs, const sum<C>& rhs)
noexcept
{
return lhs.operands() == rhs.operands();
}
/// @internal
/// @related sum
template <typename C>
std::ostream&
operator<<(std::ostream& os, const sum<C>& s)
{
os << "(";
std::copy( s.operands().begin(), std::prev(s.operands().end())
, std::ostream_iterator<homomorphism<C>>(os, " + "));
return os << *std::prev(s.operands().end()) << ")";
}
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Help optimize an union's operands.
template <typename C>
struct sum_builder_helper
{
typedef void result_type;
typedef typename sum<C>::operands_type operands_type;
typedef std::deque<homomorphism<C>> hom_list_type;
typedef std::unordered_map<typename C::Identifier, hom_list_type> locals_type;
/// @brief Flatten nested sums.
void
operator()( const sum<C>& s
, const homomorphism<C>& h, operands_type& operands, locals_type& locals)
const
{
for (const auto& op : s.operands())
{
apply_visitor(*this, op->data(), op, operands, locals);
}
}
/// @brief Regroup locals.
void
operator()( const local<C>& l
, const homomorphism<C>& h, operands_type& operands, locals_type& locals)
const
{
auto insertion = locals.emplace(l.identifier(), hom_list_type());
insertion.first->second.emplace_back(l.hom());
}
/// @brief Insert normally all other operands.
template <typename T>
void
operator()(const T&, const homomorphism<C>& h, operands_type& operands, locals_type&)
const
{
operands.insert(h);
}
};
} // namespace hom
/*------------------------------------------------------------------------------------------------*/
/// @brief Create the Sum homomorphism.
/// @related homomorphism
template <typename C, typename InputIterator>
homomorphism<C>
Sum(const order<C>& o, InputIterator begin, InputIterator end)
{
const std::size_t size = std::distance(begin, end);
if (size == 0)
{
throw std::invalid_argument("Empty operands at Sum construction.");
}
typename hom::sum<C>::operands_type operands;
operands.reserve(size);
hom::sum_builder_helper<C> sbv;
typename hom::sum_builder_helper<C>::locals_type locals;
for (; begin != end; ++begin)
{
apply_visitor(sbv, (*begin)->data(), *begin, operands, locals);
}
// insert remaining locals
for (const auto& l : locals)
{
operands.insert(Local<C>(l.first, o, Sum<C>(o, l.second.begin(), l.second.end())));
}
if (operands.size() == 1)
{
return *operands.begin();
}
else
{
operands.shrink_to_fit();
return homomorphism<C>::create(mem::construct<hom::sum<C>>(), std::move(operands));
}
}
/*------------------------------------------------------------------------------------------------*/
/// @brief Create the Sum homomorphism.
/// @related homomorphism
template <typename C>
homomorphism<C>
Sum(const order<C>& o, std::initializer_list<homomorphism<C>> operands)
{
return Sum<C>(o, operands.begin(), operands.end());
}
/*------------------------------------------------------------------------------------------------*/
} // namespace sdd
namespace std {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Hash specialization for sdd::hom::sum.
template <typename C>
struct hash<sdd::hom::sum<C>>
{
std::size_t
operator()(const sdd::hom::sum<C>& s)
const noexcept
{
std::size_t seed = 0;
for (const auto& op : s.operands())
{
sdd::util::hash_combine(seed, op);
}
return seed;
}
};
/*------------------------------------------------------------------------------------------------*/
} // namespace std
#endif // _SDD_HOM_SUM_HH_
<|endoftext|>
|
<commit_before>#pragma once
#include "../search/search.hpp"
#include "../structs/kdtree.hpp"
#include "../utils/pool.hpp"
#include <set>
template <class D> class RRT : public SearchAlgorithm<D> {
public:
typedef typename D::State State;
typedef typename D::PackedState PackedState;
typedef typename D::Cost Cost;
typedef typename D::Edge Edge;
typedef typename D::Oper Oper;
static const unsigned int K = D::State::K;
struct Node {
Node *parent;
PackedState state;
Oper op;
std::set<Oper> ops; // ops added to the tree
};
RRT(int argc, const char *argv[]) : SearchAlgorithm<D>(argc, argv), rng(0) {
seed = randgen.bits();
for (int i = 0; i < argc; i++) {
if (i < argc - 1 && strcmp(argv[i], "-s") == 0) {
char *end = NULL;
seed = strtoull(argv[i++], &end, 10);
if (end == NULL)
fatal("Invalid seed: %s", argv[i-1]);
}
}
rng = Rand(seed);
}
~RRT() {
}
void search(D &d, typename D::State &s0) {
this->start();
Node *root = pool.construct();
root->parent = NULL;
d.pack(root->state, s0);
double pt[K];
s0.vector(&d, pt);
tree.insert(pt, root);
for ( ; ; ) {
sample(pt);
auto near = tree.nearest(pt);
Node *node = near->data;
State buf, &state = d.unpack(buf, node->state);
SearchAlgorithm<D>::res.expd++;
Node *kid = pool.construct();
kid->parent = node;
double bestpt[K];
double dist = std::numeric_limits<double>::infinity();
typename D::Operators ops(d, state);
for (unsigned int i = 0; i < ops.size(); i++) {
SearchAlgorithm<D>::res.gend++;
if (node->ops.find(ops[i]) != node->ops.end())
continue;
Edge e(d, state, ops[i]);
if (d.isgoal(e.state)) {
d.pack(kid->state, e.state);
kid->op = ops[i];
solpath<D, Node>(d, kid, this->res);
goto done;
}
double kidpt[K];
e.state.vector(&d, kidpt);
double dst = sqdist(pt, kidpt);
if (dst < dist) {
dist = dst;
for (unsigned int j = 0; j < K; j++)
bestpt[j] = kidpt[j];
d.pack(kid->state, e.state);
kid->op = ops[i];
}
}
if (std::isinf(dist)) {
pool.destruct(kid);
continue;
}
node->ops.insert(kid->op);
tree.insert(bestpt, kid);
}
done:
this->finish();
}
virtual void reset() {
SearchAlgorithm<D>::reset();
pool.releaseall();
}
virtual void output(FILE *out) {
SearchAlgorithm<D>::output(out);
dfpair(stdout, "node size", "%u", sizeof(Node));
dfpair(stdout, "RRT seed", "%lu", (unsigned long) seed);
}
private:
double sqdist(double a[], double b[]) {
double s = 0;
for (unsigned int i = 0; i < K; i++) {
double d = a[i] - b[i];
s += d*d;
}
return s;
}
void sample(double s[]) {
for (unsigned int i = 0; i < K; i++)
s[i] = rng.real();
}
Rand rng;
uint64_t seed;
Kdtree<K, Node*> tree;
Pool<Node> pool;
};
<commit_msg>search: print the RRT tree size.<commit_after>#pragma once
#include "../search/search.hpp"
#include "../structs/kdtree.hpp"
#include "../utils/pool.hpp"
#include <set>
template <class D> class RRT : public SearchAlgorithm<D> {
public:
typedef typename D::State State;
typedef typename D::PackedState PackedState;
typedef typename D::Cost Cost;
typedef typename D::Edge Edge;
typedef typename D::Oper Oper;
static const unsigned int K = D::State::K;
struct Node {
Node *parent;
PackedState state;
Oper op;
std::set<Oper> ops; // ops added to the tree
};
RRT(int argc, const char *argv[]) : SearchAlgorithm<D>(argc, argv), rng(0) {
seed = randgen.bits();
for (int i = 0; i < argc; i++) {
if (i < argc - 1 && strcmp(argv[i], "-s") == 0) {
char *end = NULL;
seed = strtoull(argv[i++], &end, 10);
if (end == NULL)
fatal("Invalid seed: %s", argv[i-1]);
}
}
rng = Rand(seed);
}
~RRT() {
}
void search(D &d, typename D::State &s0) {
this->start();
Node *root = pool.construct();
root->parent = NULL;
d.pack(root->state, s0);
double pt[K];
s0.vector(&d, pt);
tree.insert(pt, root);
for ( ; ; ) {
sample(pt);
auto near = tree.nearest(pt);
Node *node = near->data;
State buf, &state = d.unpack(buf, node->state);
SearchAlgorithm<D>::res.expd++;
Node *kid = pool.construct();
kid->parent = node;
double bestpt[K];
double dist = std::numeric_limits<double>::infinity();
typename D::Operators ops(d, state);
for (unsigned int i = 0; i < ops.size(); i++) {
SearchAlgorithm<D>::res.gend++;
if (node->ops.find(ops[i]) != node->ops.end())
continue;
Edge e(d, state, ops[i]);
if (d.isgoal(e.state)) {
d.pack(kid->state, e.state);
kid->op = ops[i];
solpath<D, Node>(d, kid, this->res);
goto done;
}
double kidpt[K];
e.state.vector(&d, kidpt);
double dst = sqdist(pt, kidpt);
if (dst < dist) {
dist = dst;
for (unsigned int j = 0; j < K; j++)
bestpt[j] = kidpt[j];
d.pack(kid->state, e.state);
kid->op = ops[i];
}
}
if (std::isinf(dist)) {
pool.destruct(kid);
continue;
}
node->ops.insert(kid->op);
tree.insert(bestpt, kid);
}
done:
this->finish();
}
virtual void reset() {
SearchAlgorithm<D>::reset();
pool.releaseall();
}
virtual void output(FILE *out) {
SearchAlgorithm<D>::output(out);
dfpair(stdout, "node size", "%u", sizeof(Node));
dfpair(stdout, "RRT seed", "%lu", (unsigned long) seed);
dfpair(stdout, "RRT tree size", "%lu", (unsigned long) tree.size());
}
private:
double sqdist(double a[], double b[]) {
double s = 0;
for (unsigned int i = 0; i < K; i++) {
double d = a[i] - b[i];
s += d*d;
}
return s;
}
void sample(double s[]) {
for (unsigned int i = 0; i < K; i++)
s[i] = rng.real();
}
Rand rng;
uint64_t seed;
Kdtree<K, Node*> tree;
Pool<Node> pool;
};
<|endoftext|>
|
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Ioan Sucan, Sachin Chitta */
#include "ompl_interface_ros/ompl_interface_ros.h"
#include "planning_scene_monitor/planning_scene_monitor.h"
#include <tf/transform_listener.h>
#include <visualization_msgs/MarkerArray.h>
static const std::string PLANNER_NODE_NAME="ompl_planning"; // name of node
static const std::string PLANNER_SERVICE_NAME="plan_kinematic_path"; // name of the advertised service (within the ~ namespace)
static const std::string BENCHMARK_SERVICE_NAME="benchmark_planning_problem"; // name of the advertised service (within the ~ namespace)
static const std::string ROBOT_DESCRIPTION="robot_description"; // name of the robot description (a param name, so it can be changed externally)
class OMPLPlannerService
{
public:
OMPLPlannerService(planning_scene_monitor::PlanningSceneMonitor &psm) : nh_("~"), psm_(psm), ompl_interface_(psm.getPlanningScene()->getKinematicModel())
{
plan_service_ = nh_.advertiseService(PLANNER_SERVICE_NAME, &OMPLPlannerService::computePlan, this);
benchmark_service_ = nh_.advertiseService(BENCHMARK_SERVICE_NAME, &OMPLPlannerService::computeBenchmark, this);
pub_markers_ = nh_.advertise<visualization_msgs::MarkerArray>("visualization_marker_array", 5);
}
bool computePlan(moveit_msgs::GetMotionPlan::Request &req, moveit_msgs::GetMotionPlan::Response &res)
{
ROS_INFO("Received new planning request...");
bool result = ompl_interface_.solve(psm_.getPlanningScene(), req, res);
displayPlannerData("r_wrist_roll_link");
return result;
}
void displayPlannerData(const std::string &link_name)
{
const ompl_interface::PlanningConfigurationPtr &pc = ompl_interface_.getLastPlanningConfiguration();
if (pc)
{
const ompl::base::PlannerData &pd = pc->getOMPLSimpleSetup().getPlannerData();
planning_models::KinematicState kstate = psm_.getPlanningScene()->getCurrentState();
visualization_msgs::MarkerArray arr;
std_msgs::ColorRGBA color;
color.r = 1.0f;
color.g = 0.0f;
color.b = 0.0f;
color.a = 1.0f;
for (std::size_t i = 0 ; i < pd.states.size() ; ++i)
{
pc->getKMStateSpace().copyToKinematicState(kstate, pd.states[i]);
kstate.getJointStateGroup(pc->getJointModelGroupName())->updateLinkTransforms();
const Eigen::Vector3d &pos = kstate.getLinkState(link_name)->getGlobalLinkTransform().translation();
visualization_msgs::Marker mk;
mk.header.stamp = ros::Time::now();
mk.header.frame_id = psm_.getPlanningScene()->getPlanningFrame();
mk.ns = "planner_data";
mk.id = i;
mk.type = visualization_msgs::Marker::SPHERE;
mk.action = visualization_msgs::Marker::ADD;
mk.pose.position.x = pos.x();
mk.pose.position.y = pos.y();
mk.pose.position.z = pos.z();
mk.pose.orientation.w = 1.0;
mk.scale.x = mk.scale.y = mk.scale.z = 0.035;
mk.color = color;
mk.lifetime = ros::Duration(10.0);
arr.markers.push_back(mk);
}
pub_markers_.publish(arr);
}
}
bool computeBenchmark(moveit_msgs::ComputePlanningBenchmark::Request &req, moveit_msgs::ComputePlanningBenchmark::Response &res)
{
ROS_INFO("Received new benchmark request...");
return ompl_interface_.benchmark(psm_.getPlanningScene(), req, res);
}
void status(void)
{
ompl_interface_.printStatus();
ROS_INFO("Responding to planning and bechmark requests");
}
private:
ros::NodeHandle nh_;
planning_scene_monitor::PlanningSceneMonitor &psm_;
ompl_interface_ros::OMPLInterfaceROS ompl_interface_;
ros::ServiceServer plan_service_;
ros::ServiceServer benchmark_service_;
ros::ServiceServer display_states_service_;
ros::Publisher pub_markers_;
};
int main(int argc, char **argv)
{
ros::init(argc, argv, PLANNER_NODE_NAME);
ros::AsyncSpinner spinner(1);
spinner.start();
tf::TransformListener tf;
planning_scene_monitor::PlanningSceneMonitor psm(ROBOT_DESCRIPTION, &tf);
if (psm.getPlanningScene()->isConfigured())
{
psm.startWorldGeometryMonitor();
psm.startSceneMonitor();
psm.startStateMonitor();
OMPLPlannerService pservice(psm);
pservice.status();
ros::waitForShutdown();
}
else
ROS_ERROR("Planning scene not configured");
return 0;
}
<commit_msg>merging default<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Ioan Sucan, Sachin Chitta */
#include "ompl_interface_ros/ompl_interface_ros.h"
#include "planning_scene_monitor/planning_scene_monitor.h"
#include <tf/transform_listener.h>
#include <visualization_msgs/MarkerArray.h>
static const std::string PLANNER_NODE_NAME="ompl_planning"; // name of node
static const std::string PLANNER_SERVICE_NAME="plan_kinematic_path"; // name of the advertised service (within the ~ namespace)
static const std::string BENCHMARK_SERVICE_NAME="benchmark_planning_problem"; // name of the advertised service (within the ~ namespace)
static const std::string ROBOT_DESCRIPTION="robot_description"; // name of the robot description (a param name, so it can be changed externally)
class OMPLPlannerService
{
public:
OMPLPlannerService(planning_scene_monitor::PlanningSceneMonitor &psm) : nh_("~"), psm_(psm), ompl_interface_(psm.getPlanningScene()->getKinematicModel())
{
plan_service_ = nh_.advertiseService(PLANNER_SERVICE_NAME, &OMPLPlannerService::computePlan, this);
benchmark_service_ = nh_.advertiseService(BENCHMARK_SERVICE_NAME, &OMPLPlannerService::computeBenchmark, this);
pub_markers_ = nh_.advertise<visualization_msgs::MarkerArray>("visualization_marker_array", 5);
}
bool computePlan(moveit_msgs::GetMotionPlan::Request &req, moveit_msgs::GetMotionPlan::Response &res)
{
ROS_INFO("Received new planning request...");
bool result = ompl_interface_.solve(psm_.getPlanningScene(), req, res);
displayPlannerData("r_wrist_roll_link");
std::stringstream ss;
ompl::Profiler::Status(ss);
ROS_INFO("%s", ss.str().c_str());
return result;
}
void displayPlannerData(const std::string &link_name)
{
const ompl_interface::PlanningConfigurationPtr &pc = ompl_interface_.getLastPlanningConfiguration();
if (pc)
{
const ompl::base::PlannerData &pd = pc->getOMPLSimpleSetup().getPlannerData();
planning_models::KinematicState kstate = psm_.getPlanningScene()->getCurrentState();
visualization_msgs::MarkerArray arr;
std_msgs::ColorRGBA color;
color.r = 1.0f;
color.g = 0.0f;
color.b = 0.0f;
color.a = 1.0f;
for (std::size_t i = 0 ; i < pd.states.size() ; ++i)
{
pc->getKMStateSpace().copyToKinematicState(kstate, pd.states[i]);
kstate.getJointStateGroup(pc->getJointModelGroupName())->updateLinkTransforms();
const Eigen::Vector3d &pos = kstate.getLinkState(link_name)->getGlobalLinkTransform().translation();
visualization_msgs::Marker mk;
mk.header.stamp = ros::Time::now();
mk.header.frame_id = psm_.getPlanningScene()->getPlanningFrame();
mk.ns = "planner_data";
mk.id = i;
mk.type = visualization_msgs::Marker::SPHERE;
mk.action = visualization_msgs::Marker::ADD;
mk.pose.position.x = pos.x();
mk.pose.position.y = pos.y();
mk.pose.position.z = pos.z();
mk.pose.orientation.w = 1.0;
mk.scale.x = mk.scale.y = mk.scale.z = 0.035;
mk.color = color;
mk.lifetime = ros::Duration(10.0);
arr.markers.push_back(mk);
}
pub_markers_.publish(arr);
}
}
bool computeBenchmark(moveit_msgs::ComputePlanningBenchmark::Request &req, moveit_msgs::ComputePlanningBenchmark::Response &res)
{
ROS_INFO("Received new benchmark request...");
return ompl_interface_.benchmark(psm_.getPlanningScene(), req, res);
}
void status(void)
{
ompl_interface_.printStatus();
ROS_INFO("Responding to planning and bechmark requests");
}
private:
ros::NodeHandle nh_;
planning_scene_monitor::PlanningSceneMonitor &psm_;
ompl_interface_ros::OMPLInterfaceROS ompl_interface_;
ros::ServiceServer plan_service_;
ros::ServiceServer benchmark_service_;
ros::ServiceServer display_states_service_;
ros::Publisher pub_markers_;
};
int main(int argc, char **argv)
{
ros::init(argc, argv, PLANNER_NODE_NAME);
ros::AsyncSpinner spinner(1);
spinner.start();
tf::TransformListener tf;
planning_scene_monitor::PlanningSceneMonitor psm(ROBOT_DESCRIPTION, &tf);
if (psm.getPlanningScene()->isConfigured())
{
psm.startWorldGeometryMonitor();
psm.startSceneMonitor();
psm.startStateMonitor();
OMPLPlannerService pservice(psm);
pservice.status();
ros::waitForShutdown();
}
else
ROS_ERROR("Planning scene not configured");
return 0;
}
<|endoftext|>
|
<commit_before>
#include <ionCore.h>
#include <catch.hpp>
class A
{};
class B : public A
{};
class C
{
public:
virtual ~C()
{}
};
TEST_CASE("InstanceOf", "[ionClass :: InstanceOf]")
{
A a;
B b;
C c;
A const * const aPtr = &a;
REQUIRE(InstanceOf<A>(a));
REQUIRE(InstanceOf<A>(aPtr));
REQUIRE(InstanceOf<A>(&a));
REQUIRE(InstanceOf<A>(b));
REQUIRE(InstanceOf<A>(&b));
REQUIRE(InstanceOf<C>(c));
REQUIRE(! InstanceOf<A>(c));
REQUIRE(! InstanceOf<A>(&c));
REQUIRE(nullptr != As<A>(&a));
REQUIRE(nullptr != As<A>(&b));
REQUIRE(nullptr == As<A>(&c));
}
class Base
{
public:
Base() {}
virtual ~Base() {}
};
class Derived : public Base
{};
TEST_CASE("ionClass::As", "As function converts between objects")
{
Base a;
Base const constA;
Derived b;
C c;
Base const * const aPtr = &a;
Derived const * const bPtr = &b;
C const * const cPtr = &c;
REQUIRE(As<Derived>((Base*)&b) == &b);
REQUIRE(As<Derived>((Base const * const)bPtr) == bPtr);
REQUIRE(As<Base>(& a) == & a);
REQUIRE(! As<Derived>(& a));
REQUIRE(! & As<Derived>(a));
REQUIRE(! & As<Derived>(constA));
}
TEST_CASE("Type", "[ionClass :: Type]")
{
Type TypeA(typeid(A));
Type TypeB(typeid(B));
Type TypeC(typeid(C));
REQUIRE((TypeA < TypeB) != (TypeB < TypeA));
REQUIRE((TypeA < TypeC) != (TypeC < TypeA));
REQUIRE((TypeB < TypeC) != (TypeC < TypeB));
}
class F;
class E : public Singleton<E>
{
public:
SingletonPointer<F> FPtr;
};
class F : public Singleton<F>
{
public:
SingletonPointer<E> EPtr;
};
TEST_CASE("Singleton lazy initialization", "[ionClass :: Singleton]")
{
SingletonPointer<E> e;
SingletonPointer<E> const constE = SingletonPointer<E>();
SingletonPointer<F> f;
REQUIRE(e->FPtr.Get() == f.Get());
REQUIRE(constE->FPtr.Get() == f.Get());
REQUIRE(f->EPtr.Get() == e.Get());
REQUIRE(f->EPtr.Get() == constE.Get());
REQUIRE(f->EPtr == e);
REQUIRE(f->EPtr == constE);
}
<commit_msg>Fix some name conflicts in ionClass tests<commit_after>
#include <ionCore.h>
#include <catch.hpp>
class A
{};
class B : public A
{};
class C
{
public:
virtual ~C()
{}
};
TEST_CASE("InstanceOf", "[ionClass :: InstanceOf]")
{
A a;
B b;
C c;
A const * const aPtr = &a;
REQUIRE(InstanceOf<A>(a));
REQUIRE(InstanceOf<A>(aPtr));
REQUIRE(InstanceOf<A>(&a));
REQUIRE(InstanceOf<A>(b));
REQUIRE(InstanceOf<A>(&b));
REQUIRE(InstanceOf<C>(c));
REQUIRE(! InstanceOf<A>(c));
REQUIRE(! InstanceOf<A>(&c));
REQUIRE(nullptr != As<A>(&a));
REQUIRE(nullptr != As<A>(&b));
REQUIRE(nullptr == As<A>(&c));
}
class TestBase
{
public:
TestBase() {}
virtual ~TestBase() {}
};
class TestDerived : public TestBase
{};
TEST_CASE("ionClass::As", "As function converts between objects")
{
TestBase a;
TestBase const constA;
TestDerived b;
C c;
TestBase const * const aPtr = &a;
TestDerived const * const bPtr = &b;
C const * const cPtr = &c;
REQUIRE(As<TestDerived>((TestBase*)&b) == &b);
REQUIRE(As<TestDerived>((TestBase const * const)bPtr) == bPtr);
REQUIRE(As<TestBase>(& a) == & a);
REQUIRE(! As<TestDerived>(& a));
REQUIRE(! & As<TestDerived>(a));
REQUIRE(! & As<TestDerived>(constA));
}
TEST_CASE("Type", "[ionClass :: Type]")
{
Type TypeA(typeid(A));
Type TypeB(typeid(B));
Type TypeC(typeid(C));
REQUIRE((TypeA < TypeB) != (TypeB < TypeA));
REQUIRE((TypeA < TypeC) != (TypeC < TypeA));
REQUIRE((TypeB < TypeC) != (TypeC < TypeB));
}
class F;
class E : public Singleton<E>
{
public:
SingletonPointer<F> FPtr;
};
class F : public Singleton<F>
{
public:
SingletonPointer<E> EPtr;
};
TEST_CASE("Singleton lazy initialization", "[ionClass :: Singleton]")
{
SingletonPointer<E> e;
SingletonPointer<E> const constE = SingletonPointer<E>();
SingletonPointer<F> f;
REQUIRE(e->FPtr.Get() == f.Get());
REQUIRE(constE->FPtr.Get() == f.Get());
REQUIRE(f->EPtr.Get() == e.Get());
REQUIRE(f->EPtr.Get() == constE.Get());
REQUIRE(f->EPtr == e);
REQUIRE(f->EPtr == constE);
}
<|endoftext|>
|
<commit_before>// Copyright 2012 Intel Corporation
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#if WAFFLE_ANDROID_MAJOR_VERSION >= 4 && \
WAFFLE_ANDROID_MINOR_VERSION >= 1
# include <gui/SurfaceComposerClient.h>
#elif WAFFLE_ANROID_MAJOR_VERSION >= 4 && \
WAFFLE_ANDROID_MINOR_VERSION == 0
# include <surfaceflinger/SurfaceComposerClient.h>
#else
# error "android >= 4.0 is required"
#endif
#include "droid_surfaceflingerlink.h"
extern "C" {
#include "wcore_util.h"
#include "wcore_error.h"
};
using namespace android;
namespace waffle {
struct droid_surfaceflinger_container {
sp<SurfaceComposerClient> composer_client;
};
struct droid_ANativeWindow_container {
// it is important ANativeWindow* is the first element in this structure
ANativeWindow* native_window;
sp<SurfaceControl> surface_control;
sp<ANativeWindow> window;
};
const uint32_t droid_magic_surface_width = 32;
const uint32_t droid_magic_surface_height = 32;
const int32_t droid_magic_surface_z = 0x7FFFFFFF;
void droid_tear_down_surfaceflinger_link(
droid_surfaceflinger_container* pSFContainer);
droid_surfaceflinger_container*
droid_setup_surfaceflinger_link()
{
bool bRVal;
EGLint iRVal;
droid_surfaceflinger_container* pSFContainer;
pSFContainer = new droid_surfaceflinger_container;
if (pSFContainer == NULL)
goto error;
pSFContainer->composer_client = new SurfaceComposerClient;
iRVal = pSFContainer->composer_client->initCheck();
if (iRVal != NO_ERROR) {
wcore_errorf(WAFFLE_ERROR_UNKNOWN,
"android::SurfaceComposerClient->initCheck != NO_ERROR");
goto error;
}
return pSFContainer;
error:
droid_tear_down_surfaceflinger_link(pSFContainer);
return NULL;
}
droid_ANativeWindow_container*
droid_setup_surface(
int width,
int height,
droid_surfaceflinger_container* pSFContainer)
{
bool bRVal;
EGLint iRVal;
droid_ANativeWindow_container* pANWContainer;
pANWContainer = new droid_ANativeWindow_container;
if (pANWContainer == NULL)
goto error;
pANWContainer->surface_control =
pSFContainer->composer_client->createSurface(
String8("Waffle Surface"),
droid_magic_surface_width, droid_magic_surface_height,
PIXEL_FORMAT_RGB_888, 0);
if (pANWContainer->surface_control == NULL) {
wcore_errorf(WAFFLE_ERROR_UNKNOWN,
"Unable to get android::SurfaceControl");
delete pANWContainer;
goto error;
}
bRVal = pANWContainer->surface_control->isValid();
if (bRVal != true) {
wcore_errorf(WAFFLE_ERROR_UNKNOWN,
"Acquired android::SurfaceControl is invalid");
delete pANWContainer;
goto error;
}
pSFContainer->composer_client->openGlobalTransaction();
iRVal = pANWContainer->surface_control->setLayer(droid_magic_surface_z);
if (iRVal != NO_ERROR) {
wcore_errorf(WAFFLE_ERROR_UNKNOWN,
"Error in android::SurfaceControl->setLayer");
delete pANWContainer;
goto error_closeTransaction;
}
pSFContainer->composer_client->closeGlobalTransaction();
pANWContainer->window = pANWContainer->surface_control->getSurface();
pSFContainer->composer_client->openGlobalTransaction();
iRVal = pANWContainer->surface_control->setSize(width, height);
pSFContainer->composer_client->closeGlobalTransaction();
if (iRVal != NO_ERROR) {
wcore_errorf(WAFFLE_ERROR_UNKNOWN,
"error in android::SurfaceControl->setSize");
delete pANWContainer;
goto error;
}
pANWContainer->native_window = pANWContainer->window.get();
return pANWContainer;
error_closeTransaction:
pSFContainer->composer_client->closeGlobalTransaction();
error:
droid_tear_down_surfaceflinger_link(pSFContainer);
return NULL;
}
bool
droid_show_surface(
droid_surfaceflinger_container* pSFContainer,
droid_ANativeWindow_container* pANWContainer)
{
int iRVal;
pSFContainer->composer_client->openGlobalTransaction();
iRVal = pANWContainer->surface_control->show();
pSFContainer->composer_client->closeGlobalTransaction();
if (iRVal != NO_ERROR) {
wcore_errorf(WAFFLE_ERROR_UNKNOWN,
"Error in android::SurfaceControl->show");
return false;
}
return true;
}
bool
droid_resize_surface(
droid_surfaceflinger_container* pSFContainer,
droid_ANativeWindow_container* pANWContainer,
int width,
int height)
{
int iRVal;
pSFContainer->composer_client->openGlobalTransaction();
iRVal = pANWContainer->surface_control->setSize(width, height);
pSFContainer->composer_client->closeGlobalTransaction();
if (iRVal != NO_ERROR) {
wcore_errorf(WAFFLE_ERROR_UNKNOWN,
"Error in android::SurfaceControl->setSize");
return false;
}
return true;
}
void
droid_destroy_surface(
droid_surfaceflinger_container* pSFContainer,
droid_ANativeWindow_container* pANWContainer)
{
pSFContainer->composer_client->openGlobalTransaction();
pANWContainer->surface_control->clear();
pSFContainer->composer_client->closeGlobalTransaction();
delete pANWContainer;
}
void
droid_tear_down_surfaceflinger_link(
waffle::droid_surfaceflinger_container* pSFContainer)
{
if( pSFContainer == NULL)
return;
if (pSFContainer->composer_client != NULL) {
pSFContainer->composer_client->dispose();
pSFContainer->composer_client = NULL;
}
delete pSFContainer;
}
}; // namespace waffle
extern "C" struct droid_surfaceflinger_container*
droid_init_gl()
{
return reinterpret_cast<droid_surfaceflinger_container*>(
waffle::droid_setup_surfaceflinger_link());
}
extern "C" bool
droid_deinit_gl(droid_surfaceflinger_container* pSFContainer)
{
waffle::droid_tear_down_surfaceflinger_link(
reinterpret_cast<waffle::droid_surfaceflinger_container*>
(pSFContainer));
return true;
}
extern "C" droid_ANativeWindow_container*
droid_create_surface(
int width,
int height,
droid_surfaceflinger_container* pSFContainer)
{
waffle::droid_ANativeWindow_container* container =
waffle::droid_setup_surface(
width, height,
reinterpret_cast<waffle::droid_surfaceflinger_container*> (pSFContainer));
return reinterpret_cast<droid_ANativeWindow_container*>(container);
}
extern "C" bool
droid_show_surface(
droid_surfaceflinger_container* pSFContainer,
droid_ANativeWindow_container* pANWContainer)
{
return waffle::droid_show_surface(
reinterpret_cast<waffle::droid_surfaceflinger_container*>
(pSFContainer),
reinterpret_cast<waffle::droid_ANativeWindow_container*>
(pANWContainer));
}
extern "C" bool
droid_resize_surface(
droid_surfaceflinger_container* pSFContainer,
droid_ANativeWindow_container* pANWContainer,
int height,
int width)
{
return waffle::droid_resize_surface(
reinterpret_cast<waffle::droid_surfaceflinger_container*>
(pSFContainer),
reinterpret_cast<waffle::droid_ANativeWindow_container*>
(pANWContainer), height, width);
}
extern "C" void
droid_destroy_surface(
droid_surfaceflinger_container* pSFContainer,
droid_ANativeWindow_container* pANWContainer)
{
return waffle::droid_destroy_surface(
reinterpret_cast<waffle::droid_surfaceflinger_container*>
(pSFContainer),
reinterpret_cast<waffle::droid_ANativeWindow_container*>
(pANWContainer));
}
<commit_msg>android: Fix Android Kitkat build issue<commit_after>// Copyright 2012 Intel Corporation
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#if WAFFLE_ANDROID_MAJOR_VERSION >= 4 && \
WAFFLE_ANDROID_MINOR_VERSION >= 1
# include <gui/Surface.h>
# include <gui/SurfaceComposerClient.h>
#elif WAFFLE_ANROID_MAJOR_VERSION >= 4 && \
WAFFLE_ANDROID_MINOR_VERSION == 0
# include <surfaceflinger/SurfaceComposerClient.h>
#else
# error "android >= 4.0 is required"
#endif
#include "droid_surfaceflingerlink.h"
extern "C" {
#include "wcore_util.h"
#include "wcore_error.h"
};
using namespace android;
namespace waffle {
struct droid_surfaceflinger_container {
sp<SurfaceComposerClient> composer_client;
};
struct droid_ANativeWindow_container {
// it is important ANativeWindow* is the first element in this structure
ANativeWindow* native_window;
sp<SurfaceControl> surface_control;
sp<ANativeWindow> window;
};
const uint32_t droid_magic_surface_width = 32;
const uint32_t droid_magic_surface_height = 32;
const int32_t droid_magic_surface_z = 0x7FFFFFFF;
void droid_tear_down_surfaceflinger_link(
droid_surfaceflinger_container* pSFContainer);
droid_surfaceflinger_container*
droid_setup_surfaceflinger_link()
{
bool bRVal;
EGLint iRVal;
droid_surfaceflinger_container* pSFContainer;
pSFContainer = new droid_surfaceflinger_container;
if (pSFContainer == NULL)
goto error;
pSFContainer->composer_client = new SurfaceComposerClient;
iRVal = pSFContainer->composer_client->initCheck();
if (iRVal != NO_ERROR) {
wcore_errorf(WAFFLE_ERROR_UNKNOWN,
"android::SurfaceComposerClient->initCheck != NO_ERROR");
goto error;
}
return pSFContainer;
error:
droid_tear_down_surfaceflinger_link(pSFContainer);
return NULL;
}
droid_ANativeWindow_container*
droid_setup_surface(
int width,
int height,
droid_surfaceflinger_container* pSFContainer)
{
bool bRVal;
EGLint iRVal;
droid_ANativeWindow_container* pANWContainer;
pANWContainer = new droid_ANativeWindow_container;
if (pANWContainer == NULL)
goto error;
pANWContainer->surface_control =
pSFContainer->composer_client->createSurface(
String8("Waffle Surface"),
droid_magic_surface_width, droid_magic_surface_height,
PIXEL_FORMAT_RGB_888, 0);
if (pANWContainer->surface_control == NULL) {
wcore_errorf(WAFFLE_ERROR_UNKNOWN,
"Unable to get android::SurfaceControl");
delete pANWContainer;
goto error;
}
bRVal = pANWContainer->surface_control->isValid();
if (bRVal != true) {
wcore_errorf(WAFFLE_ERROR_UNKNOWN,
"Acquired android::SurfaceControl is invalid");
delete pANWContainer;
goto error;
}
pSFContainer->composer_client->openGlobalTransaction();
iRVal = pANWContainer->surface_control->setLayer(droid_magic_surface_z);
if (iRVal != NO_ERROR) {
wcore_errorf(WAFFLE_ERROR_UNKNOWN,
"Error in android::SurfaceControl->setLayer");
delete pANWContainer;
goto error_closeTransaction;
}
pSFContainer->composer_client->closeGlobalTransaction();
pANWContainer->window = pANWContainer->surface_control->getSurface();
pSFContainer->composer_client->openGlobalTransaction();
iRVal = pANWContainer->surface_control->setSize(width, height);
pSFContainer->composer_client->closeGlobalTransaction();
if (iRVal != NO_ERROR) {
wcore_errorf(WAFFLE_ERROR_UNKNOWN,
"error in android::SurfaceControl->setSize");
delete pANWContainer;
goto error;
}
pANWContainer->native_window = pANWContainer->window.get();
return pANWContainer;
error_closeTransaction:
pSFContainer->composer_client->closeGlobalTransaction();
error:
droid_tear_down_surfaceflinger_link(pSFContainer);
return NULL;
}
bool
droid_show_surface(
droid_surfaceflinger_container* pSFContainer,
droid_ANativeWindow_container* pANWContainer)
{
int iRVal;
pSFContainer->composer_client->openGlobalTransaction();
iRVal = pANWContainer->surface_control->show();
pSFContainer->composer_client->closeGlobalTransaction();
if (iRVal != NO_ERROR) {
wcore_errorf(WAFFLE_ERROR_UNKNOWN,
"Error in android::SurfaceControl->show");
return false;
}
return true;
}
bool
droid_resize_surface(
droid_surfaceflinger_container* pSFContainer,
droid_ANativeWindow_container* pANWContainer,
int width,
int height)
{
int iRVal;
pSFContainer->composer_client->openGlobalTransaction();
iRVal = pANWContainer->surface_control->setSize(width, height);
pSFContainer->composer_client->closeGlobalTransaction();
if (iRVal != NO_ERROR) {
wcore_errorf(WAFFLE_ERROR_UNKNOWN,
"Error in android::SurfaceControl->setSize");
return false;
}
return true;
}
void
droid_destroy_surface(
droid_surfaceflinger_container* pSFContainer,
droid_ANativeWindow_container* pANWContainer)
{
pSFContainer->composer_client->openGlobalTransaction();
pANWContainer->surface_control->clear();
pSFContainer->composer_client->closeGlobalTransaction();
delete pANWContainer;
}
void
droid_tear_down_surfaceflinger_link(
waffle::droid_surfaceflinger_container* pSFContainer)
{
if( pSFContainer == NULL)
return;
if (pSFContainer->composer_client != NULL) {
pSFContainer->composer_client->dispose();
pSFContainer->composer_client = NULL;
}
delete pSFContainer;
}
}; // namespace waffle
extern "C" struct droid_surfaceflinger_container*
droid_init_gl()
{
return reinterpret_cast<droid_surfaceflinger_container*>(
waffle::droid_setup_surfaceflinger_link());
}
extern "C" bool
droid_deinit_gl(droid_surfaceflinger_container* pSFContainer)
{
waffle::droid_tear_down_surfaceflinger_link(
reinterpret_cast<waffle::droid_surfaceflinger_container*>
(pSFContainer));
return true;
}
extern "C" droid_ANativeWindow_container*
droid_create_surface(
int width,
int height,
droid_surfaceflinger_container* pSFContainer)
{
waffle::droid_ANativeWindow_container* container =
waffle::droid_setup_surface(
width, height,
reinterpret_cast<waffle::droid_surfaceflinger_container*> (pSFContainer));
return reinterpret_cast<droid_ANativeWindow_container*>(container);
}
extern "C" bool
droid_show_surface(
droid_surfaceflinger_container* pSFContainer,
droid_ANativeWindow_container* pANWContainer)
{
return waffle::droid_show_surface(
reinterpret_cast<waffle::droid_surfaceflinger_container*>
(pSFContainer),
reinterpret_cast<waffle::droid_ANativeWindow_container*>
(pANWContainer));
}
extern "C" bool
droid_resize_surface(
droid_surfaceflinger_container* pSFContainer,
droid_ANativeWindow_container* pANWContainer,
int height,
int width)
{
return waffle::droid_resize_surface(
reinterpret_cast<waffle::droid_surfaceflinger_container*>
(pSFContainer),
reinterpret_cast<waffle::droid_ANativeWindow_container*>
(pANWContainer), height, width);
}
extern "C" void
droid_destroy_surface(
droid_surfaceflinger_container* pSFContainer,
droid_ANativeWindow_container* pANWContainer)
{
return waffle::droid_destroy_surface(
reinterpret_cast<waffle::droid_surfaceflinger_container*>
(pSFContainer),
reinterpret_cast<waffle::droid_ANativeWindow_container*>
(pANWContainer));
}
<|endoftext|>
|
<commit_before>/*
* Copyright 1999-2004 The Apache Software 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.
*/
#include <algorithm>
#include "ICUFormatNumberFunctor.hpp"
#include <xalanc/ICUBridge/ICUBridge.hpp>
#include <xalanc/Include/XalanAutoPtr.hpp>
#include <xalanc/PlatformSupport/DOMStringHelper.hpp>
#include <xalanc/PlatformSupport/XalanDecimalFormatSymbols.hpp>
#include <xalanc/PlatformSupport/XalanMessageLoader.hpp>
#include <xalanc/XPath/XPathExecutionContext.hpp>
XALAN_CPP_NAMESPACE_BEGIN
ICUFormatNumberFunctor::ICUFormatNumberFunctor()
{
XalanDecimalFormatSymbols defaultXalanDFS;
m_defaultDecimalFormat = createDecimalFormat(defaultXalanDFS);
}
ICUFormatNumberFunctor::~ICUFormatNumberFunctor()
{
delete m_defaultDecimalFormat;
XALAN_USING_STD(for_each)
for_each(
m_decimalFormatCache.begin(),
m_decimalFormatCache.end(),
DecimalFormatCacheStruct::DecimalFormatDeleteFunctor());
}
void
ICUFormatNumberFunctor::operator() (
XPathExecutionContext& executionContext,
double theNumber,
const XalanDOMString& thePattern,
const XalanDecimalFormatSymbols* theDFS,
XalanDOMString& theResult,
const XalanNode* context,
const LocatorType* locator) const
{
if (!doFormat(theNumber, thePattern, theResult, theDFS))
{
executionContext.warn(
XalanMessageLoader::getMessage(XalanMessages::FormatNumberFailed_1Param),
context,
locator);
}
}
ICUFormatNumberFunctor::DecimalFormatType *
ICUFormatNumberFunctor::getCachedDecimalFormat(const XalanDecimalFormatSymbols &theDFS) const
{
XALAN_USING_STD(find_if)
DecimalFormatCacheListType& theNonConstCache =
#if defined(XALAN_NO_MUTABLE)
(DecimalFormatCacheListType&)m_decimalFormatCache;
#else
m_decimalFormatCache;
#endif
DecimalFormatCacheListType::iterator i =
find_if(
theNonConstCache.begin(),
theNonConstCache.end(),
DecimalFormatCacheStruct::DecimalFormatFindFunctor(&theDFS));
if (i == theNonConstCache.end())
{
return 0;
}
else
{
// Let's do a quick check to see if we found the first entry.
// If so, we don't have to update the cache, so just return the
// appropriate value...
const DecimalFormatCacheListType::iterator theBegin =
theNonConstCache.begin();
if (i == theBegin)
{
return (*i).m_formatter;
}
else
{
// Save the formatter, because splice() may invalidate
// i.
DecimalFormatType* const theFormatter = (*i).m_formatter;
// Move the entry to the beginning the cache
theNonConstCache.splice(theBegin, theNonConstCache, i);
return theFormatter;
}
}
}
bool
ICUFormatNumberFunctor::doFormat(
double theNumber,
const XalanDOMString& thePattern,
XalanDOMString& theResult,
const XalanDecimalFormatSymbols* theDFS) const
{
if (theDFS == 0)
{
return doICUFormat(theNumber,thePattern,theResult);
}
XalanDOMString nonLocalPattern = UnlocalizePatternFunctor(*theDFS)(thePattern);
DecimalFormatType* theFormatter = getCachedDecimalFormat(*theDFS);
if (theFormatter != 0)
{
return doICUFormat(theNumber, nonLocalPattern, theResult, theFormatter);
}
else
{
XalanAutoPtr<DecimalFormatType> theDecimalFormatGuard(createDecimalFormat(*theDFS));
if (theDecimalFormatGuard.get() !=0)
{
// OK, there was no error, so cache the instance...
cacheDecimalFormat(theDecimalFormatGuard.get(), *theDFS);
// Release the collator, since it's in the cache and
// will be controlled by the cache...
DecimalFormatType * theDecimalFormat = theDecimalFormatGuard.release();
return doICUFormat(theNumber, nonLocalPattern, theResult, theDecimalFormat);
}
else
{
return doICUFormat(theNumber,nonLocalPattern,theResult);
}
}
}
ICUFormatNumberFunctor::DecimalFormatType *
ICUFormatNumberFunctor::createDecimalFormat(
const XalanDecimalFormatSymbols& theXalanDFS) const
{
UErrorCode theStatus = U_ZERO_ERROR;
// Use a XalanAutoPtr, to keep this safe until we construct the DecimalFormat instance.
XalanAutoPtr<DecimalFormatSymbols> theDFS(new DecimalFormatSymbols(theStatus));
// We got a XalanDecimalFormatSymbols, so set the
// corresponding data in the ICU DecimalFormatSymbols.
theDFS->setSymbol(DecimalFormatSymbols::kZeroDigitSymbol, UChar(theXalanDFS.getZeroDigit()));
theDFS->setSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol, UChar(theXalanDFS.getGroupingSeparator()));
theDFS->setSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol, UChar(theXalanDFS.getDecimalSeparator()));
theDFS->setSymbol(DecimalFormatSymbols::kPerMillSymbol, UChar(theXalanDFS.getPerMill()));
theDFS->setSymbol(DecimalFormatSymbols::kPercentSymbol, UChar(theXalanDFS.getPercent()));
theDFS->setSymbol(DecimalFormatSymbols::kDigitSymbol, UChar(theXalanDFS.getDigit()));
theDFS->setSymbol(DecimalFormatSymbols::kPatternSeparatorSymbol, UChar(theXalanDFS.getPatternSeparator()));
theDFS->setSymbol(DecimalFormatSymbols::kInfinitySymbol, ICUBridge::XalanDOMStringToUnicodeString(theXalanDFS.getInfinity()));
theDFS->setSymbol(DecimalFormatSymbols::kNaNSymbol, ICUBridge::XalanDOMStringToUnicodeString(theXalanDFS.getNaN()));
theDFS->setSymbol(DecimalFormatSymbols::kMinusSignSymbol, UChar(theXalanDFS.getMinusSign()));
theDFS->setSymbol(DecimalFormatSymbols::kCurrencySymbol, ICUBridge::XalanDOMStringToUnicodeString(theXalanDFS.getCurrencySymbol()));
theDFS->setSymbol(DecimalFormatSymbols::kIntlCurrencySymbol, ICUBridge::XalanDOMStringToUnicodeString(theXalanDFS.getInternationalCurrencySymbol()));
theDFS->setSymbol(DecimalFormatSymbols::kMonetarySeparatorSymbol, UChar(theXalanDFS.getMonetaryDecimalSeparator()));
// Construct a DecimalFormat. Note that we release the XalanAutoPtr, since the
// DecimalFormat will adopt the DecimalFormatSymbols instance.
DecimalFormatType * theFormatter= new DecimalFormatType("", theDFS.release(), theStatus);
if (U_SUCCESS(theStatus))
{
return theFormatter;
}
else
{
delete theFormatter;
return 0;
}
}
void
ICUFormatNumberFunctor::cacheDecimalFormat(
DecimalFormatType * theFormatter,
const XalanDecimalFormatSymbols& theDFS) const
{
assert(theFormatter != 0);
DecimalFormatCacheListType& theNonConstCache =
#if defined(XALAN_NO_MUTABLE)
(DecimalFormatCacheListType&)m_decimalFormatCache;
#else
m_decimalFormatCache;
#endif
// Is the cache full?
if (theNonConstCache.size() == eCacheMax)
{
// Yes, so guard the collator instance, in case pop_back() throws...
XalanAutoPtr<DecimalFormatType> theDecimalFormatGuard(theNonConstCache.back().m_formatter);
theNonConstCache.pop_back();
}
theNonConstCache.push_front(DecimalFormatCacheListType::value_type());
DecimalFormatCacheListType::value_type& theEntry =
theNonConstCache.front();
theEntry.m_formatter = theFormatter;
theEntry.m_DFS = theDFS;
}
bool
ICUFormatNumberFunctor::doICUFormat(
double theNumber,
const XalanDOMString& thePattern,
XalanDOMString& theResult,
DecimalFormatType* theFormatter) const
{
UErrorCode theStatus = U_ZERO_ERROR;
if (theFormatter == 0)
{
if (m_defaultDecimalFormat != 0)
{
theFormatter = m_defaultDecimalFormat;
}
else
{
return false;
}
}
theFormatter->applyPattern(ICUBridge::XalanDOMStringToUnicodeString(thePattern),theStatus);
if (U_SUCCESS(theStatus))
{
// Do the format...
UnicodeString theUnicodeResult;
theFormatter->format(theNumber, theUnicodeResult);
ICUBridge::UnicodeStringToXalanDOMString(theUnicodeResult, theResult);
}
return U_SUCCESS(theStatus);
}
XalanDOMString
ICUFormatNumberFunctor::UnlocalizePatternFunctor::operator()(const XalanDOMString& thePattern) const
{
XalanDOMString theResult;
XalanDecimalFormatSymbols defaultDFS;
XalanDOMString::const_iterator iterator = thePattern.begin();
while( iterator != thePattern.end())
{
if( m_DFS.getDecimalSeparator() == *iterator )
{
theResult.push_back(defaultDFS.getDecimalSeparator());
}
else if(m_DFS.getDigit() == *iterator)
{
theResult.push_back(defaultDFS.getDigit());
}
else if(m_DFS.getGroupingSeparator() == *iterator)
{
theResult.push_back(defaultDFS.getGroupingSeparator());
}
else if(m_DFS.getMinusSign() == *iterator)
{
theResult.push_back(defaultDFS.getMinusSign());
}
else if(m_DFS.getPatternSeparator() == *iterator)
{
theResult.push_back(defaultDFS.getPatternSeparator());
}
else if(m_DFS.getPercent() == *iterator)
{
theResult.push_back(defaultDFS.getPercent());
}
else if(m_DFS.getPerMill() == *iterator)
{
theResult.push_back(defaultDFS.getPerMill());
}
else if(m_DFS.getZeroDigit() == *iterator)
{
theResult.push_back(defaultDFS.getZeroDigit());
}
else
{
switch(*iterator)
{
case XalanUnicode::charFullStop:
case XalanUnicode::charNumberSign:
case XalanUnicode::charComma:
case XalanUnicode::charHyphenMinus:
case XalanUnicode::charSemicolon:
case XalanUnicode::charPercentSign:
case XalanUnicode::charPerMilleSign:
case XalanUnicode::charDigit_0:
{
theResult.push_back(XalanUnicode::charAmpersand);
theResult.push_back(*iterator);
theResult.push_back(XalanUnicode::charAmpersand);
}
}
}
iterator++;
}
return theResult;
}
XALAN_CPP_NAMESPACE_END
<commit_msg>Cleaned up compiler warning.<commit_after>/*
* Copyright 1999-2004 The Apache Software 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.
*/
#include <algorithm>
#include "ICUFormatNumberFunctor.hpp"
#include <xalanc/ICUBridge/ICUBridge.hpp>
#include <xalanc/Include/XalanAutoPtr.hpp>
#include <xalanc/PlatformSupport/DOMStringHelper.hpp>
#include <xalanc/PlatformSupport/XalanDecimalFormatSymbols.hpp>
#include <xalanc/PlatformSupport/XalanMessageLoader.hpp>
#include <xalanc/XPath/XPathExecutionContext.hpp>
XALAN_CPP_NAMESPACE_BEGIN
ICUFormatNumberFunctor::ICUFormatNumberFunctor()
{
XalanDecimalFormatSymbols defaultXalanDFS;
m_defaultDecimalFormat = createDecimalFormat(defaultXalanDFS);
}
ICUFormatNumberFunctor::~ICUFormatNumberFunctor()
{
delete m_defaultDecimalFormat;
XALAN_USING_STD(for_each)
for_each(
m_decimalFormatCache.begin(),
m_decimalFormatCache.end(),
DecimalFormatCacheStruct::DecimalFormatDeleteFunctor());
}
void
ICUFormatNumberFunctor::operator() (
XPathExecutionContext& executionContext,
double theNumber,
const XalanDOMString& thePattern,
const XalanDecimalFormatSymbols* theDFS,
XalanDOMString& theResult,
const XalanNode* context,
const LocatorType* locator) const
{
if (!doFormat(theNumber, thePattern, theResult, theDFS))
{
executionContext.warn(
XalanMessageLoader::getMessage(XalanMessages::FormatNumberFailed_1Param),
context,
locator);
}
}
ICUFormatNumberFunctor::DecimalFormatType *
ICUFormatNumberFunctor::getCachedDecimalFormat(const XalanDecimalFormatSymbols &theDFS) const
{
XALAN_USING_STD(find_if)
DecimalFormatCacheListType& theNonConstCache =
#if defined(XALAN_NO_MUTABLE)
(DecimalFormatCacheListType&)m_decimalFormatCache;
#else
m_decimalFormatCache;
#endif
DecimalFormatCacheListType::iterator i =
find_if(
theNonConstCache.begin(),
theNonConstCache.end(),
DecimalFormatCacheStruct::DecimalFormatFindFunctor(&theDFS));
if (i == theNonConstCache.end())
{
return 0;
}
else
{
// Let's do a quick check to see if we found the first entry.
// If so, we don't have to update the cache, so just return the
// appropriate value...
const DecimalFormatCacheListType::iterator theBegin =
theNonConstCache.begin();
if (i == theBegin)
{
return (*i).m_formatter;
}
else
{
// Save the formatter, because splice() may invalidate
// i.
DecimalFormatType* const theFormatter = (*i).m_formatter;
// Move the entry to the beginning the cache
theNonConstCache.splice(theBegin, theNonConstCache, i);
return theFormatter;
}
}
}
bool
ICUFormatNumberFunctor::doFormat(
double theNumber,
const XalanDOMString& thePattern,
XalanDOMString& theResult,
const XalanDecimalFormatSymbols* theDFS) const
{
if (theDFS == 0)
{
return doICUFormat(theNumber,thePattern,theResult);
}
XalanDOMString nonLocalPattern = UnlocalizePatternFunctor(*theDFS)(thePattern);
DecimalFormatType* theFormatter = getCachedDecimalFormat(*theDFS);
if (theFormatter != 0)
{
return doICUFormat(theNumber, nonLocalPattern, theResult, theFormatter);
}
else
{
XalanAutoPtr<DecimalFormatType> theDecimalFormatGuard(createDecimalFormat(*theDFS));
if (theDecimalFormatGuard.get() !=0)
{
// OK, there was no error, so cache the instance...
cacheDecimalFormat(theDecimalFormatGuard.get(), *theDFS);
// Release the collator, since it's in the cache and
// will be controlled by the cache...
DecimalFormatType * theDecimalFormat = theDecimalFormatGuard.release();
return doICUFormat(theNumber, nonLocalPattern, theResult, theDecimalFormat);
}
else
{
return doICUFormat(theNumber,nonLocalPattern,theResult);
}
}
}
ICUFormatNumberFunctor::DecimalFormatType *
ICUFormatNumberFunctor::createDecimalFormat(
const XalanDecimalFormatSymbols& theXalanDFS) const
{
UErrorCode theStatus = U_ZERO_ERROR;
// Use a XalanAutoPtr, to keep this safe until we construct the DecimalFormat instance.
XalanAutoPtr<DecimalFormatSymbols> theDFS(new DecimalFormatSymbols(theStatus));
// We got a XalanDecimalFormatSymbols, so set the
// corresponding data in the ICU DecimalFormatSymbols.
theDFS->setSymbol(DecimalFormatSymbols::kZeroDigitSymbol, UChar(theXalanDFS.getZeroDigit()));
theDFS->setSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol, UChar(theXalanDFS.getGroupingSeparator()));
theDFS->setSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol, UChar(theXalanDFS.getDecimalSeparator()));
theDFS->setSymbol(DecimalFormatSymbols::kPerMillSymbol, UChar(theXalanDFS.getPerMill()));
theDFS->setSymbol(DecimalFormatSymbols::kPercentSymbol, UChar(theXalanDFS.getPercent()));
theDFS->setSymbol(DecimalFormatSymbols::kDigitSymbol, UChar(theXalanDFS.getDigit()));
theDFS->setSymbol(DecimalFormatSymbols::kPatternSeparatorSymbol, UChar(theXalanDFS.getPatternSeparator()));
theDFS->setSymbol(DecimalFormatSymbols::kInfinitySymbol, ICUBridge::XalanDOMStringToUnicodeString(theXalanDFS.getInfinity()));
theDFS->setSymbol(DecimalFormatSymbols::kNaNSymbol, ICUBridge::XalanDOMStringToUnicodeString(theXalanDFS.getNaN()));
theDFS->setSymbol(DecimalFormatSymbols::kMinusSignSymbol, UChar(theXalanDFS.getMinusSign()));
theDFS->setSymbol(DecimalFormatSymbols::kCurrencySymbol, ICUBridge::XalanDOMStringToUnicodeString(theXalanDFS.getCurrencySymbol()));
theDFS->setSymbol(DecimalFormatSymbols::kIntlCurrencySymbol, ICUBridge::XalanDOMStringToUnicodeString(theXalanDFS.getInternationalCurrencySymbol()));
theDFS->setSymbol(DecimalFormatSymbols::kMonetarySeparatorSymbol, UChar(theXalanDFS.getMonetaryDecimalSeparator()));
// Construct a DecimalFormat. Note that we release the XalanAutoPtr, since the
// DecimalFormat will adopt the DecimalFormatSymbols instance.
DecimalFormatType * theFormatter= new DecimalFormatType("", theDFS.release(), theStatus);
if (U_SUCCESS(theStatus))
{
return theFormatter;
}
else
{
delete theFormatter;
return 0;
}
}
void
ICUFormatNumberFunctor::cacheDecimalFormat(
DecimalFormatType * theFormatter,
const XalanDecimalFormatSymbols& theDFS) const
{
assert(theFormatter != 0);
DecimalFormatCacheListType& theNonConstCache =
#if defined(XALAN_NO_MUTABLE)
(DecimalFormatCacheListType&)m_decimalFormatCache;
#else
m_decimalFormatCache;
#endif
// Is the cache full?
if (theNonConstCache.size() == eCacheMax)
{
// Yes, so guard the collator instance, in case pop_back() throws...
XalanAutoPtr<DecimalFormatType> theDecimalFormatGuard(theNonConstCache.back().m_formatter);
theNonConstCache.pop_back();
}
theNonConstCache.push_front(DecimalFormatCacheListType::value_type());
DecimalFormatCacheListType::value_type& theEntry =
theNonConstCache.front();
theEntry.m_formatter = theFormatter;
theEntry.m_DFS = theDFS;
}
bool
ICUFormatNumberFunctor::doICUFormat(
double theNumber,
const XalanDOMString& thePattern,
XalanDOMString& theResult,
DecimalFormatType* theFormatter) const
{
UErrorCode theStatus = U_ZERO_ERROR;
if (theFormatter == 0)
{
if (m_defaultDecimalFormat != 0)
{
theFormatter = m_defaultDecimalFormat;
}
else
{
return false;
}
}
theFormatter->applyPattern(ICUBridge::XalanDOMStringToUnicodeString(thePattern),theStatus);
if (U_SUCCESS(theStatus))
{
// Do the format...
UnicodeString theUnicodeResult;
theFormatter->format(theNumber, theUnicodeResult);
ICUBridge::UnicodeStringToXalanDOMString(theUnicodeResult, theResult);
}
return U_SUCCESS(theStatus) ? true : false;
}
XalanDOMString
ICUFormatNumberFunctor::UnlocalizePatternFunctor::operator()(const XalanDOMString& thePattern) const
{
XalanDOMString theResult;
XalanDecimalFormatSymbols defaultDFS;
XalanDOMString::const_iterator iterator = thePattern.begin();
while( iterator != thePattern.end())
{
if( m_DFS.getDecimalSeparator() == *iterator )
{
theResult.push_back(defaultDFS.getDecimalSeparator());
}
else if(m_DFS.getDigit() == *iterator)
{
theResult.push_back(defaultDFS.getDigit());
}
else if(m_DFS.getGroupingSeparator() == *iterator)
{
theResult.push_back(defaultDFS.getGroupingSeparator());
}
else if(m_DFS.getMinusSign() == *iterator)
{
theResult.push_back(defaultDFS.getMinusSign());
}
else if(m_DFS.getPatternSeparator() == *iterator)
{
theResult.push_back(defaultDFS.getPatternSeparator());
}
else if(m_DFS.getPercent() == *iterator)
{
theResult.push_back(defaultDFS.getPercent());
}
else if(m_DFS.getPerMill() == *iterator)
{
theResult.push_back(defaultDFS.getPerMill());
}
else if(m_DFS.getZeroDigit() == *iterator)
{
theResult.push_back(defaultDFS.getZeroDigit());
}
else
{
switch(*iterator)
{
case XalanUnicode::charFullStop:
case XalanUnicode::charNumberSign:
case XalanUnicode::charComma:
case XalanUnicode::charHyphenMinus:
case XalanUnicode::charSemicolon:
case XalanUnicode::charPercentSign:
case XalanUnicode::charPerMilleSign:
case XalanUnicode::charDigit_0:
{
theResult.push_back(XalanUnicode::charAmpersand);
theResult.push_back(*iterator);
theResult.push_back(XalanUnicode::charAmpersand);
}
}
}
iterator++;
}
return theResult;
}
XALAN_CPP_NAMESPACE_END
<|endoftext|>
|
<commit_before>/****************************************************************************
* Copyright (c) 2012-2018 by the DataTransferKit authors *
* All rights reserved. *
* *
* This file is part of the DataTransferKit library. DataTransferKit is *
* distributed under a BSD 3-clause license. For the licensing terms see *
* the LICENSE file in the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
#include <DTK_LinearBVH.hpp>
#include <Kokkos_DefaultNode.hpp>
#include <Teuchos_CommandLineProcessor.hpp>
#include <Teuchos_StandardCatchMacros.hpp>
#include <chrono>
#include <cmath> // cbrt
#include <random>
template <class NO>
int main_( Teuchos::CommandLineProcessor &clp, int argc, char *argv[] )
{
using DeviceType = typename NO::device_type;
using ExecutionSpace = typename DeviceType::execution_space;
int n_values = 50000;
int n_queries = 20000;
int n_neighbors = 10;
bool perform_knn_search = true;
bool perform_radius_search = true;
clp.setOption( "values", &n_values, "number of indexable values (source)" );
clp.setOption( "queries", &n_queries, "number of queries (target)" );
clp.setOption( "neighbors", &n_neighbors,
"desired number of results per query" );
clp.setOption( "perform-knn-search", "do-not-perform-knn-search",
&perform_knn_search,
"whether or not to perform kNN search" );
clp.setOption( "perform-radius-search", "do-not-perform-radius-search",
&perform_radius_search,
"whether or not to perform radius search" );
clp.recogniseAllOptions( true );
switch ( clp.parse( argc, argv ) )
{
case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED:
return EXIT_SUCCESS;
case Teuchos::CommandLineProcessor::PARSE_ERROR:
case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION:
return EXIT_FAILURE;
case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL:
break;
}
Kokkos::View<DataTransferKit::Point *, DeviceType> random_points(
"random_points" );
{
// Random points are "reused" between building the tree and performing
// queries. You may change it if you have a problem with it. These
// don't really need to be stored in the 1st place. What is needed is
// indexable objects/values (here boxes) to build a tree and queries
// (here kNN and radius searches) with mean to control the amount of
// work per query as the problem size varies.
auto n = std::max( n_values, n_queries );
Kokkos::resize( random_points, n );
auto random_points_host = Kokkos::create_mirror_view( random_points );
// Generate random points uniformely distributed within a box. The
// edge length of the box chosen such that object density (here objects
// will be boxes 2x2x2 centered around a random point) will remain
// constant as problem size is changed.
auto const a = std::cbrt( n_values );
std::uniform_real_distribution<double> distribution( -a, +a );
std::default_random_engine generator;
auto random = [&distribution, &generator]() {
return distribution( generator );
};
for ( int i = 0; i < n; ++i )
random_points_host( i ) = {{random(), random(), random()}};
Kokkos::deep_copy( random_points, random_points_host );
}
Kokkos::View<DataTransferKit::Box *, DeviceType> bounding_boxes(
"bounding_boxes", n_values );
Kokkos::parallel_for( Kokkos::RangePolicy<ExecutionSpace>( 0, n_values ),
KOKKOS_LAMBDA( int i ) {
double const x = random_points( i )[0];
double const y = random_points( i )[1];
double const z = random_points( i )[2];
bounding_boxes( i ) = {
{{x - 1., y - 1., z - 1.}},
{{x + 1., y + 1., z + 1.}}};
} );
Kokkos::fence();
std::ostream &os = std::cout;
auto start = std::chrono::high_resolution_clock::now();
DataTransferKit::BVH<DeviceType> bvh( bounding_boxes );
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
os << "construction " << elapsed_seconds.count() << "\n";
if ( perform_knn_search )
{
Kokkos::View<DataTransferKit::Nearest<DataTransferKit::Point> *,
DeviceType>
queries( "queries", n_queries );
Kokkos::parallel_for(
Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ),
KOKKOS_LAMBDA( int i ) {
queries( i ) = DataTransferKit::nearest<DataTransferKit::Point>(
random_points( i ), n_neighbors );
} );
Kokkos::fence();
Kokkos::View<int *, DeviceType> offset( "offset" );
Kokkos::View<int *, DeviceType> indices( "indices" );
start = std::chrono::high_resolution_clock::now();
bvh.query( queries, indices, offset );
end = std::chrono::high_resolution_clock::now();
elapsed_seconds = end - start;
os << "knn " << elapsed_seconds.count() << "\n";
}
if ( perform_radius_search )
{
Kokkos::View<DataTransferKit::Within *, DeviceType> queries(
"queries", n_queries );
// radius chosen in order to control the number of results per query
// NOTE: minus "1+sqrt(3)/2 \approx 1.37" matches the size of the boxes
// inserted into the tree (mid-point between half-edge and
// half-diagonal)
double const r = 2. * std::cbrt( static_cast<double>( n_neighbors ) *
3. / ( 4. * M_PI ) ) -
( 1. + std::sqrt( 3. ) ) / 2.;
Kokkos::parallel_for(
Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ),
KOKKOS_LAMBDA( int i ) {
queries( i ) = DataTransferKit::within( random_points( i ), r );
} );
Kokkos::fence();
Kokkos::View<int *, DeviceType> offset( "offset" );
Kokkos::View<int *, DeviceType> indices( "indices" );
start = std::chrono::high_resolution_clock::now();
bvh.query( queries, indices, offset );
end = std::chrono::high_resolution_clock::now();
elapsed_seconds = end - start;
os << "radius " << elapsed_seconds.count() << "\n";
}
return 0;
}
int main( int argc, char *argv[] )
{
Kokkos::initialize( argc, argv );
bool success = true;
bool verbose = true;
try
{
const bool throwExceptions = false;
Teuchos::CommandLineProcessor clp( throwExceptions );
std::string node = "";
clp.setOption( "node", &node, "node type (serial | openmp | cuda)" );
clp.recogniseAllOptions( false );
switch ( clp.parse( argc, argv, NULL ) )
{
case Teuchos::CommandLineProcessor::PARSE_ERROR:
success = false;
case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED:
case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION:
case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL:
break;
}
if ( !success )
{
// do nothing, just skip other if clauses
}
else if ( node == "" )
{
typedef KokkosClassic::DefaultNode::DefaultNodeType Node;
main_<Node>( clp, argc, argv );
}
else if ( node == "serial" )
{
#ifdef KOKKOS_HAVE_SERIAL
typedef Kokkos::Compat::KokkosSerialWrapperNode Node;
main_<Node>( clp, argc, argv );
#else
throw std::runtime_error( "Serial node type is disabled" );
#endif
}
else if ( node == "openmp" )
{
#ifdef KOKKOS_HAVE_OPENMP
typedef Kokkos::Compat::KokkosOpenMPWrapperNode Node;
main_<Node>( clp, argc, argv );
#else
throw std::runtime_error( "OpenMP node type is disabled" );
#endif
}
else if ( node == "cuda" )
{
#ifdef KOKKOS_HAVE_CUDA
typedef Kokkos::Compat::KokkosCudaWrapperNode Node;
main_<Node>( clp, argc, argv );
#else
throw std::runtime_error( "CUDA node type is disabled" );
#endif
}
else
{
throw std::runtime_error( "Unrecognized node type" );
}
}
TEUCHOS_STANDARD_CATCH_STATEMENTS( verbose, std::cerr, success );
Kokkos::finalize();
return ( success ? EXIT_SUCCESS : EXIT_FAILURE );
}
<commit_msg>KOKKOS_HAVE -> KOKKOS_ENABLE in Search package<commit_after>/****************************************************************************
* Copyright (c) 2012-2018 by the DataTransferKit authors *
* All rights reserved. *
* *
* This file is part of the DataTransferKit library. DataTransferKit is *
* distributed under a BSD 3-clause license. For the licensing terms see *
* the LICENSE file in the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
#include <DTK_LinearBVH.hpp>
#include <Kokkos_DefaultNode.hpp>
#include <Teuchos_CommandLineProcessor.hpp>
#include <Teuchos_StandardCatchMacros.hpp>
#include <chrono>
#include <cmath> // cbrt
#include <random>
template <class NO>
int main_( Teuchos::CommandLineProcessor &clp, int argc, char *argv[] )
{
using DeviceType = typename NO::device_type;
using ExecutionSpace = typename DeviceType::execution_space;
int n_values = 50000;
int n_queries = 20000;
int n_neighbors = 10;
bool perform_knn_search = true;
bool perform_radius_search = true;
clp.setOption( "values", &n_values, "number of indexable values (source)" );
clp.setOption( "queries", &n_queries, "number of queries (target)" );
clp.setOption( "neighbors", &n_neighbors,
"desired number of results per query" );
clp.setOption( "perform-knn-search", "do-not-perform-knn-search",
&perform_knn_search,
"whether or not to perform kNN search" );
clp.setOption( "perform-radius-search", "do-not-perform-radius-search",
&perform_radius_search,
"whether or not to perform radius search" );
clp.recogniseAllOptions( true );
switch ( clp.parse( argc, argv ) )
{
case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED:
return EXIT_SUCCESS;
case Teuchos::CommandLineProcessor::PARSE_ERROR:
case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION:
return EXIT_FAILURE;
case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL:
break;
}
Kokkos::View<DataTransferKit::Point *, DeviceType> random_points(
"random_points" );
{
// Random points are "reused" between building the tree and performing
// queries. You may change it if you have a problem with it. These
// don't really need to be stored in the 1st place. What is needed is
// indexable objects/values (here boxes) to build a tree and queries
// (here kNN and radius searches) with mean to control the amount of
// work per query as the problem size varies.
auto n = std::max( n_values, n_queries );
Kokkos::resize( random_points, n );
auto random_points_host = Kokkos::create_mirror_view( random_points );
// Generate random points uniformely distributed within a box. The
// edge length of the box chosen such that object density (here objects
// will be boxes 2x2x2 centered around a random point) will remain
// constant as problem size is changed.
auto const a = std::cbrt( n_values );
std::uniform_real_distribution<double> distribution( -a, +a );
std::default_random_engine generator;
auto random = [&distribution, &generator]() {
return distribution( generator );
};
for ( int i = 0; i < n; ++i )
random_points_host( i ) = {{random(), random(), random()}};
Kokkos::deep_copy( random_points, random_points_host );
}
Kokkos::View<DataTransferKit::Box *, DeviceType> bounding_boxes(
"bounding_boxes", n_values );
Kokkos::parallel_for( Kokkos::RangePolicy<ExecutionSpace>( 0, n_values ),
KOKKOS_LAMBDA( int i ) {
double const x = random_points( i )[0];
double const y = random_points( i )[1];
double const z = random_points( i )[2];
bounding_boxes( i ) = {
{{x - 1., y - 1., z - 1.}},
{{x + 1., y + 1., z + 1.}}};
} );
Kokkos::fence();
std::ostream &os = std::cout;
auto start = std::chrono::high_resolution_clock::now();
DataTransferKit::BVH<DeviceType> bvh( bounding_boxes );
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
os << "construction " << elapsed_seconds.count() << "\n";
if ( perform_knn_search )
{
Kokkos::View<DataTransferKit::Nearest<DataTransferKit::Point> *,
DeviceType>
queries( "queries", n_queries );
Kokkos::parallel_for(
Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ),
KOKKOS_LAMBDA( int i ) {
queries( i ) = DataTransferKit::nearest<DataTransferKit::Point>(
random_points( i ), n_neighbors );
} );
Kokkos::fence();
Kokkos::View<int *, DeviceType> offset( "offset" );
Kokkos::View<int *, DeviceType> indices( "indices" );
start = std::chrono::high_resolution_clock::now();
bvh.query( queries, indices, offset );
end = std::chrono::high_resolution_clock::now();
elapsed_seconds = end - start;
os << "knn " << elapsed_seconds.count() << "\n";
}
if ( perform_radius_search )
{
Kokkos::View<DataTransferKit::Within *, DeviceType> queries(
"queries", n_queries );
// radius chosen in order to control the number of results per query
// NOTE: minus "1+sqrt(3)/2 \approx 1.37" matches the size of the boxes
// inserted into the tree (mid-point between half-edge and
// half-diagonal)
double const r = 2. * std::cbrt( static_cast<double>( n_neighbors ) *
3. / ( 4. * M_PI ) ) -
( 1. + std::sqrt( 3. ) ) / 2.;
Kokkos::parallel_for(
Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ),
KOKKOS_LAMBDA( int i ) {
queries( i ) = DataTransferKit::within( random_points( i ), r );
} );
Kokkos::fence();
Kokkos::View<int *, DeviceType> offset( "offset" );
Kokkos::View<int *, DeviceType> indices( "indices" );
start = std::chrono::high_resolution_clock::now();
bvh.query( queries, indices, offset );
end = std::chrono::high_resolution_clock::now();
elapsed_seconds = end - start;
os << "radius " << elapsed_seconds.count() << "\n";
}
return 0;
}
int main( int argc, char *argv[] )
{
Kokkos::initialize( argc, argv );
bool success = true;
bool verbose = true;
try
{
const bool throwExceptions = false;
Teuchos::CommandLineProcessor clp( throwExceptions );
std::string node = "";
clp.setOption( "node", &node, "node type (serial | openmp | cuda)" );
clp.recogniseAllOptions( false );
switch ( clp.parse( argc, argv, NULL ) )
{
case Teuchos::CommandLineProcessor::PARSE_ERROR:
success = false;
case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED:
case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION:
case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL:
break;
}
if ( !success )
{
// do nothing, just skip other if clauses
}
else if ( node == "" )
{
typedef KokkosClassic::DefaultNode::DefaultNodeType Node;
main_<Node>( clp, argc, argv );
}
else if ( node == "serial" )
{
#ifdef KOKKOS_ENABLE_SERIAL
typedef Kokkos::Compat::KokkosSerialWrapperNode Node;
main_<Node>( clp, argc, argv );
#else
throw std::runtime_error( "Serial node type is disabled" );
#endif
}
else if ( node == "openmp" )
{
#ifdef KOKKOS_ENABLE_OPENMP
typedef Kokkos::Compat::KokkosOpenMPWrapperNode Node;
main_<Node>( clp, argc, argv );
#else
throw std::runtime_error( "OpenMP node type is disabled" );
#endif
}
else if ( node == "cuda" )
{
#ifdef KOKKOS_ENABLE_CUDA
typedef Kokkos::Compat::KokkosCudaWrapperNode Node;
main_<Node>( clp, argc, argv );
#else
throw std::runtime_error( "CUDA node type is disabled" );
#endif
}
else
{
throw std::runtime_error( "Unrecognized node type" );
}
}
TEUCHOS_STANDARD_CATCH_STATEMENTS( verbose, std::cerr, success );
Kokkos::finalize();
return ( success ? EXIT_SUCCESS : EXIT_FAILURE );
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkBilateralImageFilterTest2.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include <fstream>
#include "itkBilateralImageFilter.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImageRegionIterator.h"
int itkBilateralImageFilterTest2(int ac, char* av[] )
{
if(ac < 3)
{
std::cerr << "Usage: " << av[0] << " InputImage OutputImage\n";
return -1;
}
typedef unsigned char PixelType;
const unsigned int dimension = 2;
typedef itk::Image<PixelType, dimension> myImage;
itk::ImageFileReader<myImage>::Pointer input
= itk::ImageFileReader<myImage>::New();
input->SetFileName(av[1]);
// Create a filter
typedef itk::BilateralImageFilter<myImage,myImage> FilterType;
FilterType::Pointer filter = FilterType::New();
filter->SetInput(input->GetOutput());
// these settings reduce the amount of noise by a factor of 10
// when the original signal to noise level is 5
filter->SetDomainSigma( 4.0 );
filter->SetRangeSigma( 50.0 );
// Test itkSetVectorMacro
float domainSigma[dimension];
for (unsigned int i = 0; i < dimension; i++)
{
domainSigma[i] = 4.0f;
}
filter->SetDomainSigma(domainSigma);
// Test itkGetVectorMacro
const double * domainSigma2 = filter->GetDomainSigma();
std::cout << "filter->GetDomainSigma(): " << domainSigma2 << std::endl;
// Test itkSetMacro
double filterDimensionality = dimension;
unsigned long numberOfRangeGaussianSamples = 100;
filter->SetFilterDimensionality(filterDimensionality);
filter->SetNumberOfRangeGaussianSamples(numberOfRangeGaussianSamples);
// Test itkGetMacro
const double rangeSigma2 = filter->GetRangeSigma();
std::cout << "filter->GetRangeSigma(): " << rangeSigma2 << std::endl;
double filterDimensionality2 = filter->GetFilterDimensionality();
std::cout << "filter->GetFilterDimensionality(): " << filterDimensionality2 << std::endl;
unsigned long numberOfRangeGaussianSamples2 = filter->GetNumberOfRangeGaussianSamples();
std::cout << "filter->GetNumberOfRangeGaussianSamples(): " << numberOfRangeGaussianSamples2 << std::endl;
try
{
input->Update();
filter->Update();
}
catch (itk::ExceptionObject& e)
{
std::cerr << "Exception detected: " << e.GetDescription();
return -1;
}
catch (...)
{
std::cerr << "Some other exception occurred" << std::endl;
return -2;
}
// Generate test image
itk::ImageFileWriter<myImage>::Pointer writer;
writer = itk::ImageFileWriter<myImage>::New();
writer->SetInput( filter->GetOutput() );
writer->SetFileName( av[2] );
writer->Update();
return 0;
}
<commit_msg>ERR: warnings.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkBilateralImageFilterTest2.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include <fstream>
#include "itkBilateralImageFilter.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImageRegionIterator.h"
int itkBilateralImageFilterTest2(int ac, char* av[] )
{
if(ac < 3)
{
std::cerr << "Usage: " << av[0] << " InputImage OutputImage\n";
return -1;
}
typedef unsigned char PixelType;
const unsigned int dimension = 2;
typedef itk::Image<PixelType, dimension> myImage;
itk::ImageFileReader<myImage>::Pointer input
= itk::ImageFileReader<myImage>::New();
input->SetFileName(av[1]);
// Create a filter
typedef itk::BilateralImageFilter<myImage,myImage> FilterType;
FilterType::Pointer filter = FilterType::New();
filter->SetInput(input->GetOutput());
// these settings reduce the amount of noise by a factor of 10
// when the original signal to noise level is 5
filter->SetDomainSigma( 4.0 );
filter->SetRangeSigma( 50.0 );
// Test itkSetVectorMacro
float domainSigma[dimension];
for (unsigned int i = 0; i < dimension; i++)
{
domainSigma[i] = 4.0f;
}
filter->SetDomainSigma(domainSigma);
// Test itkGetVectorMacro
const double * domainSigma2 = filter->GetDomainSigma();
std::cout << "filter->GetDomainSigma(): " << domainSigma2 << std::endl;
// Test itkSetMacro
unsigned int filterDimensionality = dimension;
unsigned long numberOfRangeGaussianSamples = 100;
filter->SetFilterDimensionality(filterDimensionality);
filter->SetNumberOfRangeGaussianSamples(numberOfRangeGaussianSamples);
// Test itkGetMacro
const double rangeSigma2 = filter->GetRangeSigma();
std::cout << "filter->GetRangeSigma(): " << rangeSigma2 << std::endl;
double filterDimensionality2 = filter->GetFilterDimensionality();
std::cout << "filter->GetFilterDimensionality(): " << filterDimensionality2 << std::endl;
unsigned long numberOfRangeGaussianSamples2 = filter->GetNumberOfRangeGaussianSamples();
std::cout << "filter->GetNumberOfRangeGaussianSamples(): " << numberOfRangeGaussianSamples2 << std::endl;
try
{
input->Update();
filter->Update();
}
catch (itk::ExceptionObject& e)
{
std::cerr << "Exception detected: " << e.GetDescription();
return -1;
}
catch (...)
{
std::cerr << "Some other exception occurred" << std::endl;
return -2;
}
// Generate test image
itk::ImageFileWriter<myImage>::Pointer writer;
writer = itk::ImageFileWriter<myImage>::New();
writer->SetInput( filter->GetOutput() );
writer->SetFileName( av[2] );
writer->Update();
return 0;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkRigid3DPerspectiveTransformTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include <iostream>
#include "itkRigid3DPerspectiveTransform.h"
#include "vnl/vnl_vector_fixed.h"
#include "itkVector.h"
int itkRigid3DPerspectiveTransformTest(int argc,char **argv)
{
typedef itk::Rigid3DPerspectiveTransform<double> TransformType;
const double epsilon = 1e-10;
const unsigned int N = 3;
const double focal = 100.0;
const double width = 100.0;
const double height = 100.0;
bool Ok = true;
/* Create a 3D identity transformation and show its parameters */
{
TransformType::Pointer identityTransform = TransformType::New();
identityTransform->SetFocalDistance( focal );
identityTransform->SetHeight( height );
identityTransform->SetWidth( width );
TransformType::OffsetType offset = identityTransform->GetOffset();
std::cout << "Vector from instantiating an identity transform: ";
std::cout << offset << std::endl;
for(unsigned int i=0; i<N; i++)
{
if( fabs( offset[i]-0.0 ) > epsilon )
{
Ok = false;
break;
}
}
if( !Ok )
{
std::cerr << "Identity doesn't have a null offset" << std::endl;
return EXIT_FAILURE;
}
}
/* Create a Rigid 3D transform with translation */
{
TransformType::Pointer translation = TransformType::New();
translation->SetFocalDistance( focal );
translation->SetHeight( height );
translation->SetWidth( width );
TransformType::OffsetType ioffset;
ioffset.Fill(0.0);
translation->SetOffset( ioffset );
TransformType::OffsetType offset = translation->GetOffset();
std::cout << "pure Translation test: ";
std::cout << offset << std::endl;
for(unsigned int i=0; i<N; i++)
{
if( fabs( offset[i]- ioffset[i] ) > epsilon )
{
Ok = false;
break;
}
}
if( !Ok )
{
std::cerr << "Get Offset differs from SetOffset value " << std::endl;
return EXIT_FAILURE;
}
{
// Project an itk::Point
TransformType::InputPointType p;
p.Fill(0.0);
TransformType::InputPointType q;
q = p + ioffset;
TransformType::OutputPointType s;
const double factor = height/(q[2]+focal);
s[0] = q[0] * factor + width/2.0;
s[1] = q[1] * factor + height/2.0;
TransformType::OutputPointType r;
r = translation->TransformPoint( p );
for(unsigned int i=0; i<N-1; i++)
{
if( fabs( s[i]- r[i] ) > epsilon )
{
Ok = false;
break;
}
}
if( !Ok )
{
std::cerr << "Error translating point: " << p << std::endl;
std::cerr << "Result should be : " << s << std::endl;
std::cerr << "Reported Result is : " << r << std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << "Ok translating an itk::Point " << std::endl;
}
}
{
// Projecting an itk::Point
TransformType::InputPointType p;
p[0] = 10;
p[1] = 10;
p[2] = 10;
TransformType::InputPointType q;
q = p + ioffset;
TransformType::OutputPointType s;
const double factor = height/(q[2]+focal);
s[0] = q[0] * factor + width/2.0;
s[1] = q[1] * factor + height/2.0;
TransformType::OutputPointType r;
r = translation->TransformPoint( p );
for(unsigned int i=0; i<N-1; i++)
{
if( fabs( s[i]- r[i] ) > epsilon )
{
Ok = false;
break;
}
}
if( !Ok )
{
std::cerr << "Error translating point: " << p << std::endl;
std::cerr << "Result should be : " << s << std::endl;
std::cerr << "Reported Result is : " << r << std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << "Ok translating an itk::Point " << std::endl;
}
}
}
/* Create a Rigid 3D transform with a rotation */
{
TransformType::Pointer rigid = TransformType::New();
rigid->SetFocalDistance( focal );
rigid->SetHeight( height );
rigid->SetWidth( width );
TransformType::OffsetType ioffset;
ioffset.Fill(0.0);
rigid->SetOffset( ioffset );
TransformType::OffsetType offset = rigid->GetOffset();
std::cout << "pure Translation test: ";
std::cout << offset << std::endl;
typedef TransformType::VersorType VersorType;
VersorType rotation;
VersorType::VectorType axis;
VersorType::ValueType angle = 30.0f * atan( 1.0f ) / 45.0f;
axis[0] = 1.0f;
axis[1] = 1.0f;
axis[2] = 1.0f;
rotation.Set( axis, angle );
rigid->SetRotation( rotation );
{
// Project an itk::Point
TransformType::InputPointType p;
p.Fill(0.0);
TransformType::InputPointType q;
q = p + ioffset;
TransformType::OutputPointType s;
const double factor = height/(q[2]+focal);
s[0] = q[0] * factor + width/2.0;
s[1] = q[1] * factor + height/2.0;
TransformType::OutputPointType r;
r = rigid->TransformPoint( p );
for(unsigned int i=0; i<N-1; i++)
{
if( fabs( s[i]- r[i] ) > epsilon )
{
Ok = false;
break;
}
}
if( !Ok )
{
std::cerr << "Error rotating point: " << p << std::endl;
std::cerr << "Result should be : " << s << std::endl;
std::cerr << "Reported Result is : " << r << std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << "Ok rotating an itk::Point " << std::endl;
}
}
{
// Projecting an itk::Point
TransformType::InputPointType p;
p[0] = 10;
p[1] = 10;
p[2] = 10;
TransformType::InputPointType q;
q = p + ioffset;
TransformType::OutputPointType s;
const double factor = height/(q[2]+focal);
s[0] = q[0] * factor + width/2.0;
s[1] = q[1] * factor + height/2.0;
TransformType::OutputPointType r;
r = rigid->TransformPoint( p );
for(unsigned int i=0; i<N-1; i++)
{
if( fabs( s[i]- r[i] ) > epsilon )
{
Ok = false;
break;
}
}
if( !Ok )
{
std::cerr << "Error rotating point: " << p << std::endl;
std::cerr << "Result should be : " << s << std::endl;
std::cerr << "Reported Result is : " << r << std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << "Ok translating an itk::Point " << std::endl;
}
}
}
return EXIT_SUCCESS;
}
<commit_msg>FIX: Perspective transform was modified<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkRigid3DPerspectiveTransformTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include <iostream>
#include "itkRigid3DPerspectiveTransform.h"
#include "vnl/vnl_vector_fixed.h"
#include "itkVector.h"
int itkRigid3DPerspectiveTransformTest(int argc,char **argv)
{
typedef itk::Rigid3DPerspectiveTransform<double> TransformType;
const double epsilon = 1e-10;
const unsigned int N = 3;
const double focal = 100.0;
const double width = 100.0;
const double height = 100.0;
bool Ok = true;
/* Create a 3D identity transformation and show its parameters */
{
TransformType::Pointer identityTransform = TransformType::New();
identityTransform->SetFocalDistance( focal );
identityTransform->SetHeight( height );
identityTransform->SetWidth( width );
TransformType::OffsetType offset = identityTransform->GetOffset();
std::cout << "Vector from instantiating an identity transform: ";
std::cout << offset << std::endl;
for(unsigned int i=0; i<N; i++)
{
if( fabs( offset[i]-0.0 ) > epsilon )
{
Ok = false;
break;
}
}
if( !Ok )
{
std::cerr << "Identity doesn't have a null offset" << std::endl;
return EXIT_FAILURE;
}
}
/* Create a Rigid 3D transform with translation */
{
TransformType::Pointer translation = TransformType::New();
translation->SetFocalDistance( focal );
translation->SetHeight( height );
translation->SetWidth( width );
TransformType::OffsetType ioffset;
ioffset.Fill(0.0);
translation->SetOffset( ioffset );
TransformType::OffsetType offset = translation->GetOffset();
std::cout << "pure Translation test: ";
std::cout << offset << std::endl;
for(unsigned int i=0; i<N; i++)
{
if( fabs( offset[i]- ioffset[i] ) > epsilon )
{
Ok = false;
break;
}
}
if( !Ok )
{
std::cerr << "Get Offset differs from SetOffset value " << std::endl;
return EXIT_FAILURE;
}
{
// Project an itk::Point
TransformType::InputPointType p;
p.Fill(0.0);
TransformType::InputPointType q;
q = p + ioffset;
TransformType::OutputPointType s;
const double factor = focal/q[2];
s[0] = q[0] * factor;
s[1] = q[1] * factor;
TransformType::OutputPointType r;
r = translation->TransformPoint( p );
for(unsigned int i=0; i<N-1; i++)
{
if( fabs( s[i]- r[i] ) > epsilon )
{
Ok = false;
break;
}
}
if( !Ok )
{
std::cerr << "Error translating point: " << p << std::endl;
std::cerr << "Result should be : " << s << std::endl;
std::cerr << "Reported Result is : " << r << std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << "Ok translating an itk::Point " << std::endl;
}
}
{
// Projecting an itk::Point
TransformType::InputPointType p;
p[0] = 10;
p[1] = 10;
p[2] = 10;
TransformType::InputPointType q;
q = p + ioffset;
TransformType::OutputPointType s;
const double factor = focal/q[2];
s[0] = q[0] * factor;
s[1] = q[1] * factor;
TransformType::OutputPointType r;
r = translation->TransformPoint( p );
for(unsigned int i=0; i<N-1; i++)
{
if( fabs( s[i]- r[i] ) > epsilon )
{
Ok = false;
break;
}
}
if( !Ok )
{
std::cerr << "Error translating point: " << p << std::endl;
std::cerr << "Result should be : " << s << std::endl;
std::cerr << "Reported Result is : " << r << std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << "Ok translating an itk::Point " << std::endl;
}
}
}
/* Create a Rigid 3D transform with a rotation */
{
TransformType::Pointer rigid = TransformType::New();
rigid->SetFocalDistance( focal );
rigid->SetHeight( height );
rigid->SetWidth( width );
TransformType::OffsetType ioffset;
ioffset.Fill(0.0);
rigid->SetOffset( ioffset );
TransformType::OffsetType offset = rigid->GetOffset();
std::cout << "pure Translation test: ";
std::cout << offset << std::endl;
typedef TransformType::VersorType VersorType;
VersorType rotation;
VersorType::VectorType axis;
VersorType::ValueType angle = 30.0f * atan( 1.0f ) / 45.0f;
axis[0] = 1.0f;
axis[1] = 1.0f;
axis[2] = 1.0f;
rotation.Set( axis, angle );
rigid->SetRotation( rotation );
{
// Project an itk::Point
TransformType::InputPointType p;
p.Fill(0.0);
TransformType::InputPointType q;
q = p + ioffset;
TransformType::OutputPointType s;
const double factor = focal/q[2];
s[0] = q[0] * factor;
s[1] = q[1] * factor;
TransformType::OutputPointType r;
r = rigid->TransformPoint( p );
for(unsigned int i=0; i<N-1; i++)
{
if( fabs( s[i]- r[i] ) > epsilon )
{
Ok = false;
break;
}
}
if( !Ok )
{
std::cerr << "Error rotating point: " << p << std::endl;
std::cerr << "Result should be : " << s << std::endl;
std::cerr << "Reported Result is : " << r << std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << "Ok rotating an itk::Point " << std::endl;
}
}
{
// Projecting an itk::Point
TransformType::InputPointType p;
p[0] = 10;
p[1] = 10;
p[2] = 10;
TransformType::InputPointType q;
q = p + ioffset;
TransformType::OutputPointType s;
const double factor = focal/q[2];
s[0] = q[0] * factor;
s[1] = q[1] * factor;
TransformType::OutputPointType r;
r = rigid->TransformPoint( p );
for(unsigned int i=0; i<N-1; i++)
{
if( fabs( s[i]- r[i] ) > epsilon )
{
Ok = false;
break;
}
}
if( !Ok )
{
std::cerr << "Error translatin point: " << p << std::endl;
std::cerr << "Result should be : " << s << std::endl;
std::cerr << "Reported Result is : " << r << std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << "Ok translating an itk::Point " << std::endl;
}
}
}
std::cout << "Test successful" << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/***************************************************************************
*
* Project: libLAS -- C/C++ read/write library for LAS LIDAR data
* Purpose: LAS translation with optional configuration
* Author: Howard Butler, hobu.inc at gmail.com
***************************************************************************
* Copyright (c) 2010, Howard Butler, hobu.inc at gmail.com
*
* See LICENSE.txt in this source distribution for more information.
**************************************************************************/
#include <iostream>
#include <libpc/exceptions.hpp>
//#include <libpc/libpc_config.hpp>
//#include <libpc/Bounds.hpp>
//#include <libpc/Color.hpp>
//#include <libpc/Dimension.hpp>
//#include <libpc/Schema.hpp>
#include <libpc/filters/Chipper.hpp>
//#include <libpc/ColorFilter.hpp>
//#include <libpc/MosaicFilter.hpp>
//#include <libpc/FauxReader.hpp>
//#include <libpc/FauxWriter.hpp>
#include <libpc/drivers/las/Reader.hpp>
//#include <libpc/LasHeader.hpp>
#include <libpc/drivers/las/Writer.hpp>
#include <libpc/filters/CacheFilter.hpp>
#include <libpc/drivers/liblas/Writer.hpp>
#include <libpc/drivers/liblas/Reader.hpp>
#ifdef LIBPC_HAVE_ORACLE
#include <libpc/drivers/oci/Writer.hpp>
#include <libpc/drivers/oci/Reader.hpp>
#endif
#include <boost/property_tree/xml_parser.hpp>
#include "Application.hpp"
using namespace libpc;
namespace po = boost::program_options;
class Application_pc2pc : public Application
{
public:
Application_pc2pc(int argc, char* argv[]);
int execute();
private:
void addOptions();
bool validateOptions();
std::string m_inputFile;
std::string m_outputFile;
std::string m_xml;
std::string m_srs;
bool m_bCompress;
};
Application_pc2pc::Application_pc2pc(int argc, char* argv[])
: Application(argc, argv, "pc2pc")
{
}
bool Application_pc2pc::validateOptions()
{
if (!hasOption("input"))
{
usageError("--input/-i required");
return false;
}
if (!hasOption("output"))
{
usageError("--output/-o required");
return false;
}
return true;
}
void Application_pc2pc::addOptions()
{
po::options_description* file_options = new po::options_description("file options");
file_options->add_options()
("input,i", po::value<std::string>(&m_inputFile), "input file name")
("output,o", po::value<std::string>(&m_outputFile), "output file name")
("native", "use native LAS classes (not liblas)")
("oracle-writer", "Read data from LAS file and write to Oracle")
("oracle-reader", "Read data from Oracle and write to LAS")
("a_srs", po::value<std::string>(&m_srs)->default_value(""), "Assign output coordinate system")
("compress", po::value<bool>(&m_bCompress)->zero_tokens()->implicit_value(true),"Compress output data if available")
("xml", po::value<std::string>(&m_xml)->default_value("log.xml"), "XML file to load process (OCI only right now)")
;
addOptionSet(file_options);
}
int Application_pc2pc::execute()
{
if (!Utils::fileExists(m_inputFile))
{
runtimeError("file not found: " + m_inputFile);
return 1;
}
std::ostream* ofs = Utils::createFile(m_outputFile);
if (hasOption("native"))
{
libpc::drivers::las::LasReader reader(m_inputFile);
const boost::uint64_t numPoints = reader.getNumPoints();
libpc::drivers::las::LasWriter writer(reader, *ofs);
//BUG: handle laz writer.setCompressed(false);
//writer.setPointFormat( reader.getPointFormatNumber() );
writer.write(numPoints);
}
else if (hasOption("oracle-writer"))
{
#ifdef LIBPC_HAVE_ORACLE
libpc::drivers::liblas::LiblasReader reader(m_inputFile);
const boost::uint64_t numPoints = reader.getNumPoints();
boost::property_tree::ptree load_tree;
boost::property_tree::read_xml(m_xml, load_tree);
boost::property_tree::ptree oracle_options = load_tree.get_child("drivers.oci.writer");
libpc::Options options(oracle_options);
boost::property_tree::ptree& tree = options.GetPTree();
boost::uint32_t capacity = tree.get<boost::uint32_t>("capacity");
libpc::filters::CacheFilter cache(reader, 1, 1024);
libpc::filters::Chipper chipper(cache, capacity);
libpc::drivers::oci::Writer writer(chipper, options);
writer.write(numPoints);
boost::property_tree::ptree output_tree;
output_tree.put_child(writer.getName(), options.GetPTree());
boost::property_tree::write_xml(m_xml, output_tree);
#else
throw configuration_error("libPC not compiled with Oracle support");
#endif
}
else if (hasOption("oracle-reader"))
{
#ifdef LIBPC_HAVE_ORACLE
boost::property_tree::ptree load_tree;
boost::property_tree::read_xml(m_xml, load_tree);
boost::property_tree::ptree oracle_options = load_tree.get_child("drivers.oci.reader");
libpc::Options options(oracle_options);
libpc::drivers::oci::Reader reader(options);
const boost::uint64_t numPoints = reader.getNumPoints();
libpc::drivers::las::LasWriter writer(reader, *ofs);
if (hasOption("a_srs"))
{
libpc::SpatialReference ref;
ref.setFromUserInput(m_srs);
writer.setSpatialReference(ref);
}
if (hasOption("compress"))
{
writer.setCompressed(true);
}
writer.write(numPoints);
boost::property_tree::ptree output_tree;
output_tree.put_child(reader.getName(), options.GetPTree());
// output_tree.put_child(writer.getName(), )
boost::property_tree::write_xml(m_xml, output_tree);
#else
throw configuration_error("libPC not compiled with Oracle support");
#endif
}
else
{
libpc::drivers::liblas::LiblasReader reader(m_inputFile);
const boost::uint64_t numPoints = reader.getNumPoints();
libpc::drivers::liblas::LiblasWriter writer(reader, *ofs);
//BUG: handle laz writer.setCompressed(false);
writer.setPointFormat( reader.getPointFormat() );
writer.write(numPoints);
}
Utils::closeFile(ofs);
return 0;
}
int main(int argc, char* argv[])
{
Application_pc2pc app(argc, argv);
return app.run();
}
<commit_msg>only try to set the srs if we have one<commit_after>/***************************************************************************
*
* Project: libLAS -- C/C++ read/write library for LAS LIDAR data
* Purpose: LAS translation with optional configuration
* Author: Howard Butler, hobu.inc at gmail.com
***************************************************************************
* Copyright (c) 2010, Howard Butler, hobu.inc at gmail.com
*
* See LICENSE.txt in this source distribution for more information.
**************************************************************************/
#include <iostream>
#include <libpc/exceptions.hpp>
//#include <libpc/libpc_config.hpp>
//#include <libpc/Bounds.hpp>
//#include <libpc/Color.hpp>
//#include <libpc/Dimension.hpp>
//#include <libpc/Schema.hpp>
#include <libpc/filters/Chipper.hpp>
//#include <libpc/ColorFilter.hpp>
//#include <libpc/MosaicFilter.hpp>
//#include <libpc/FauxReader.hpp>
//#include <libpc/FauxWriter.hpp>
#include <libpc/drivers/las/Reader.hpp>
//#include <libpc/LasHeader.hpp>
#include <libpc/drivers/las/Writer.hpp>
#include <libpc/filters/CacheFilter.hpp>
#include <libpc/drivers/liblas/Writer.hpp>
#include <libpc/drivers/liblas/Reader.hpp>
#ifdef LIBPC_HAVE_ORACLE
#include <libpc/drivers/oci/Writer.hpp>
#include <libpc/drivers/oci/Reader.hpp>
#endif
#include <boost/property_tree/xml_parser.hpp>
#include "Application.hpp"
using namespace libpc;
namespace po = boost::program_options;
class Application_pc2pc : public Application
{
public:
Application_pc2pc(int argc, char* argv[]);
int execute();
private:
void addOptions();
bool validateOptions();
std::string m_inputFile;
std::string m_outputFile;
std::string m_xml;
std::string m_srs;
bool m_bCompress;
};
Application_pc2pc::Application_pc2pc(int argc, char* argv[])
: Application(argc, argv, "pc2pc")
{
}
bool Application_pc2pc::validateOptions()
{
if (!hasOption("input"))
{
usageError("--input/-i required");
return false;
}
if (!hasOption("output"))
{
usageError("--output/-o required");
return false;
}
return true;
}
void Application_pc2pc::addOptions()
{
po::options_description* file_options = new po::options_description("file options");
file_options->add_options()
("input,i", po::value<std::string>(&m_inputFile), "input file name")
("output,o", po::value<std::string>(&m_outputFile), "output file name")
("native", "use native LAS classes (not liblas)")
("oracle-writer", "Read data from LAS file and write to Oracle")
("oracle-reader", "Read data from Oracle and write to LAS")
("a_srs", po::value<std::string>(&m_srs)->default_value(""), "Assign output coordinate system")
("compress", po::value<bool>(&m_bCompress)->zero_tokens()->implicit_value(true),"Compress output data if available")
("xml", po::value<std::string>(&m_xml)->default_value("log.xml"), "XML file to load process (OCI only right now)")
;
addOptionSet(file_options);
}
int Application_pc2pc::execute()
{
if (!Utils::fileExists(m_inputFile))
{
runtimeError("file not found: " + m_inputFile);
return 1;
}
std::ostream* ofs = Utils::createFile(m_outputFile);
if (hasOption("native"))
{
libpc::drivers::las::LasReader reader(m_inputFile);
const boost::uint64_t numPoints = reader.getNumPoints();
libpc::drivers::las::LasWriter writer(reader, *ofs);
//BUG: handle laz writer.setCompressed(false);
//writer.setPointFormat( reader.getPointFormatNumber() );
writer.write(numPoints);
}
else if (hasOption("oracle-writer"))
{
#ifdef LIBPC_HAVE_ORACLE
libpc::drivers::liblas::LiblasReader reader(m_inputFile);
const boost::uint64_t numPoints = reader.getNumPoints();
boost::property_tree::ptree load_tree;
boost::property_tree::read_xml(m_xml, load_tree);
boost::property_tree::ptree oracle_options = load_tree.get_child("drivers.oci.writer");
libpc::Options options(oracle_options);
boost::property_tree::ptree& tree = options.GetPTree();
boost::uint32_t capacity = tree.get<boost::uint32_t>("capacity");
libpc::filters::CacheFilter cache(reader, 1, 1024);
libpc::filters::Chipper chipper(cache, capacity);
libpc::drivers::oci::Writer writer(chipper, options);
writer.write(numPoints);
boost::property_tree::ptree output_tree;
output_tree.put_child(writer.getName(), options.GetPTree());
boost::property_tree::write_xml(m_xml, output_tree);
#else
throw configuration_error("libPC not compiled with Oracle support");
#endif
}
else if (hasOption("oracle-reader"))
{
#ifdef LIBPC_HAVE_ORACLE
boost::property_tree::ptree load_tree;
boost::property_tree::read_xml(m_xml, load_tree);
boost::property_tree::ptree oracle_options = load_tree.get_child("drivers.oci.reader");
libpc::Options options(oracle_options);
libpc::drivers::oci::Reader reader(options);
const boost::uint64_t numPoints = reader.getNumPoints();
libpc::drivers::las::LasWriter writer(reader, *ofs);
if (hasOption("a_srs"))
{
libpc::SpatialReference ref;
if (m_srs.size() > 0)
{
ref.setFromUserInput(m_srs);
writer.setSpatialReference(ref);
}
}
if (hasOption("compress"))
{
writer.setCompressed(true);
}
writer.write(numPoints);
boost::property_tree::ptree output_tree;
output_tree.put_child(reader.getName(), options.GetPTree());
// output_tree.put_child(writer.getName(), )
boost::property_tree::write_xml(m_xml, output_tree);
#else
throw configuration_error("libPC not compiled with Oracle support");
#endif
}
else
{
libpc::drivers::liblas::LiblasReader reader(m_inputFile);
const boost::uint64_t numPoints = reader.getNumPoints();
libpc::drivers::liblas::LiblasWriter writer(reader, *ofs);
//BUG: handle laz writer.setCompressed(false);
writer.setPointFormat( reader.getPointFormat() );
writer.write(numPoints);
}
Utils::closeFile(ofs);
return 0;
}
int main(int argc, char* argv[])
{
Application_pc2pc app(argc, argv);
return app.run();
}
<|endoftext|>
|
<commit_before>#include "loss.h"
#include "task.h"
#include "model.h"
#include <fstream>
#include "trainer.h"
#include "enhancer.h"
#include "text/table.h"
#include "accumulator.h"
#include "text/cmdline.h"
#include "text/filesystem.h"
#include "measure_and_log.h"
using namespace nano;
static bool save(const string_t& path, const probes_t& probes)
{
table_t table;
table.header() << "name" << "#flops" << "gflop/s" << "min[us]" << "avg[us]" << "max[us]";
for (const auto& probe : probes)
{
auto& row = table.append();
row << probe.fullname() << probe.flops();
if (probe.timings().min() < int64_t(1))
{
row << "-";
}
else
{
row << probe.gflops();
}
row << probe.timings().min() << probe.timings().avg() << probe.timings().max();
}
std::ofstream os(path.c_str());
return os.is_open() && (os << table);
}
int main(int argc, const char *argv[])
{
// parse the command line
cmdline_t cmdline("train a model");
cmdline.add("", "task", join(get_tasks().ids()));
cmdline.add("", "task-params", "task parameters (if any)", "-");
cmdline.add("", "task-fold", "fold index to use for training", "0");
cmdline.add("", "model-params", "filepath to load the model configuration from");
cmdline.add("", "model-file", "filepath to save the model to");
cmdline.add("", "trainer", join(get_trainers().ids()));
cmdline.add("", "trainer-params", "trainer parameters (if any)");
cmdline.add("", "loss", join(get_losses().ids()));
cmdline.add("", "enhancer", join(get_enhancers().ids()), "default");
cmdline.add("", "enhancer-params", "task enhancer parameters (if any)", "-");
cmdline.add("", "threads", "number of threads to use", physical_cpus());
cmdline.process(argc, argv);
// check arguments and options
const auto cmd_task = cmdline.get<string_t>("task");
const auto cmd_task_params = cmdline.get<string_t>("task-params");
const auto cmd_task_fold = cmdline.get<size_t>("task-fold");
const auto cmd_model_params = cmdline.get<string_t>("model-params");
const auto cmd_model_file = cmdline.get<string_t>("model-file");
const auto cmd_state_file = dirname(cmd_model_file) + stem(cmd_model_file) + ".state";
const auto cmd_probe_file = dirname(cmd_model_file) + stem(cmd_model_file) + ".probes";
const auto cmd_trainer = cmdline.get<string_t>("trainer");
const auto cmd_trainer_params = cmdline.get<string_t>("trainer-params");
const auto cmd_loss = cmdline.get<string_t>("loss");
const auto cmd_enhancer = cmdline.get<string_t>("enhancer");
const auto cmd_enhancer_params = cmdline.get<string_t>("enhancer-params");
const auto cmd_threads = cmdline.get<size_t>("threads");
// create task
const auto task = get_tasks().get(cmd_task);
task->config(cmd_task_params);
measure_critical_and_log(
[&] () { return task->load(); },
"load task <" + cmd_task + ">");
// describe task
describe(*task, cmd_task);
// create loss
const auto loss = get_losses().get(cmd_loss);
// create enhancer
const auto enhancer = get_enhancers().get(cmd_enhancer);
enhancer->config(cmd_enhancer_params);
// create model
model_t model;
measure_critical_and_log(
[&] () { return model.config(cmd_model_params) && model.resize(task->idims(), task->odims()); },
"configure model");
model.random();
model.describe();
if (model != *task)
{
log_error() << "mis-matching model and task!";
return EXIT_FAILURE;
}
// create trainer
const auto trainer = get_trainers().get(cmd_trainer);
trainer->config(cmd_trainer_params);
// train model
accumulator_t acc(model, *loss);
acc.threads(cmd_threads);
// todo: setup the minibatch size
// todo: add --probes && --probes-detailed to print computation statistics
trainer_result_t result;
measure_critical_and_log([&] ()
{
result = trainer->train(*enhancer, *task, cmd_task_fold, acc);
return result.valid();
},
"train model");
if (result.valid())
{
model.params(result.optimum_params());
}
// save the model & its optimization history
measure_critical_and_log(
[&] () { return model.save(cmd_model_file); },
"save model to <" + cmd_model_file + ">");
measure_critical_and_log(
[&] () { return save(cmd_state_file, result.optimum_states()); },
"save state to <" + cmd_state_file + ">");
measure_critical_and_log(
[&] () { return save(cmd_probe_file, acc.probes()); },
"save probes to <" + cmd_probe_file + ">");
// OK
log_info() << done;
return EXIT_SUCCESS;
}
<commit_msg>draft of the training application<commit_after>#include "loss.h"
#include "task.h"
#include "model.h"
#include "io/io.h"
#include <fstream>
#include "trainer.h"
#include "enhancer.h"
#include "text/table.h"
#include "accumulator.h"
#include "text/cmdline.h"
#include "text/filesystem.h"
#include "measure_and_log.h"
using namespace nano;
typename <typename tfactory, typename trobject = typename tfactory::trobject>
static trobject load_object(const tfactory& factory, const cmdline_t& cmdline, const char* name, string_t& json)
{
const auto json_path = cmdline.get<string_t>(name);
measure_critical_and_log(
[&] () { return io::load_string(json_path, json); },
strcat("load json <", json_path, ">"));
string_t id;
measure_critical_and_log(
[&] () { json_reader_t(json).object(name, id); return !id.empty(); },
strcat("load json name <", name, ">"));
trobject object;
measure_critical_and_log(
[&] () { return (object = factory.get(id)) != nullptr; },
strcat("load ", name, " <", id, ">"));
return object;
}
static bool save(const string_t& path, const probes_t& probes)
{
table_t table;
table.header() << "name" << "#flops" << "gflop/s" << "min[us]" << "avg[us]" << "max[us]";
for (const auto& probe : probes)
{
auto& row = table.append();
row << probe.fullname() << probe.flops();
if (probe.timings().min() < int64_t(1))
{
row << "-";
}
else
{
row << probe.gflops();
}
row << probe.timings().min() << probe.timings().avg() << probe.timings().max();
}
std::ofstream os(path.c_str());
return os.is_open() && (os << table);
}
int main(int argc, const char *argv[])
{
// parse the command line
cmdline_t cmdline("train a model");
cmdline.add("", "task", join(get_tasks().ids()) + " (.json)");
cmdline.add("", "fold", "fold index to use for training", "0");
cmdline.add("", "model", "model configuration (.json)");
cmdline.add("", "trainer", join(get_trainers().ids()) + " (.json)");
cmdline.add("", "loss", join(get_losses().ids()));
cmdline.add("", "enhancer", join(get_enhancers().ids()) + " (.json)");
cmdline.add("", "basepath", "basepath where to save results (e.g. model, logs, history)");
cmdline.add("", "threads", "number of threads to use", physical_cpus());
cmdline.process(argc, argv);
// check arguments and options
const auto cmd_fold = cmdline.get<size_t>("fold");
const auto cmd_model_params = cmdline.get<string_t>("model-params");
const auto cmd_model_file = cmdline.get<string_t>("model-file");
const auto cmd_state_file = dirname(cmd_model_file) + stem(cmd_model_file) + ".state";
const auto cmd_probe_file = dirname(cmd_model_file) + stem(cmd_model_file) + ".probes";
const auto cmd_threads = cmdline.get<size_t>("threads");
// load task
string_t task_params;
const auto task = load_object(get_tasks(), cmdline, "task", task_params);
task->config(cmd_task_params);
measure_critical_and_log(
[&] () { return task->load(); },
"load task <" + cmd_task + ">");
describe(*task, cmd_task);
// load loss
string_t loss_params;
const auto loss = load_object(get_losses(), cmdline, "loss", loss_params);
// load enhancer
string_t enhancer_params;
const auto enhancer = load_object(get_enhancers(), cmdline, "enhancer", enhancer_params);
enhancer->config(enhancer_params);
// load model
string_t
model_t model;
measure_critical_and_log(
[&] () { return model.config(cmd_model_params) && model.resize(task->idims(), task->odims()); },
"configure model");
model.random();
model.describe();
if (model != *task)
{
log_error() << "mis-matching model and task!";
return EXIT_FAILURE;
}
// create trainer
const auto trainer = get_trainers().get(cmd_trainer);
trainer->config(cmd_trainer_params);
// train model
accumulator_t acc(model, *loss);
acc.threads(cmd_threads);
// todo: setup the minibatch size
// todo: add --probes && --probes-detailed to print computation statistics
trainer_result_t result;
measure_critical_and_log([&] ()
{
result = trainer->train(*enhancer, *task, cmd_task_fold, acc);
return result.valid();
},
"train model");
if (result.valid())
{
model.params(result.optimum_params());
}
// save the model & its optimization history
measure_critical_and_log(
[&] () { return model.save(cmd_model_file); },
"save model to <" + cmd_model_file + ">");
measure_critical_and_log(
[&] () { return save(cmd_state_file, result.optimum_states()); },
"save state to <" + cmd_state_file + ">");
measure_critical_and_log(
[&] () { return save(cmd_probe_file, acc.probes()); },
"save probes to <" + cmd_probe_file + ">");
// OK
log_info() << done;
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*
*
* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker 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 Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* iot_support at tid dot es
*
* Author: Ken Zangelin
*/
#include <string>
#include "logMsg/logMsg.h"
#include "common/globals.h"
#include "common/tag.h"
#include "ngsi/Request.h"
#include "ngsi/AttributeList.h"
#include "ngsi/EntityIdVector.h"
#include "ngsi/Restriction.h"
#include "ngsi10/QueryContextResponse.h"
#include "ngsi10/QueryContextRequest.h"
#include "rest/ConnectionInfo.h"
#include "rest/EntityTypeInfo.h"
/* ****************************************************************************
*
* QueryContextRequest::QueryContextRequest
*
* Explicit constructor needed to initialize primitive types so they don't get
* random values from the stack
*/
QueryContextRequest::QueryContextRequest()
{
restrictions = 0;
}
/* ****************************************************************************
*
* QueryContextRequest::render -
*/
std::string QueryContextRequest::render(RequestType requestType, Format format, const std::string& indent)
{
std::string out = "";
std::string tag = "queryContextRequest";
bool attributeListRendered = attributeList.size() != 0;
bool restrictionRendered = restrictions != 0;
bool commaAfterAttributeList = restrictionRendered;
bool commaAfterEntityIdVector = attributeListRendered || restrictionRendered;
out += startTag(indent, tag, format, false);
out += entityIdVector.render(format, indent + " ", commaAfterEntityIdVector);
out += attributeList.render(format, indent + " ", commaAfterAttributeList);
out += restriction.render(format, indent + " ", restrictions, false);
out += endTag(indent, tag, format);
return out;
}
/* ****************************************************************************
*
* QueryContextRequest::check -
*/
std::string QueryContextRequest::check(ConnectionInfo* ciP, RequestType requestType, const std::string& indent, const std::string& predetectedError, int counter)
{
std::string res;
QueryContextResponse response;
if (predetectedError != "")
{
response.errorCode.fill(SccBadRequest, predetectedError);
}
else if (((res = entityIdVector.check(QueryContext, ciP->outFormat, indent, predetectedError, 0)) != "OK") ||
((res = attributeList.check(QueryContext, ciP->outFormat, indent, predetectedError, 0)) != "OK") ||
((res = restriction.check(QueryContext, ciP->outFormat, indent, predetectedError, restrictions)) != "OK"))
{
LM_W(("Bad Input (%s)", res.c_str()));
response.errorCode.fill(SccBadRequest, res);
}
else
{
return "OK";
}
return response.render(ciP, QueryContext, indent);
}
/* ****************************************************************************
*
* QueryContextRequest::present -
*/
void QueryContextRequest::present(const std::string& indent)
{
entityIdVector.present(indent);
attributeList.present(indent);
restriction.present(indent);
}
/* ****************************************************************************
*
* QueryContextRequest::release -
*/
void QueryContextRequest::release(void)
{
entityIdVector.release();
restriction.release();
}
/* ****************************************************************************
*
* QueryContextRequest::fill -
*/
void QueryContextRequest::fill(const std::string& entityId, const std::string& entityType, const std::string& attributeName)
{
EntityId* eidP = new EntityId(entityId, entityType, "true");
entityIdVector.push_back(eidP);
if (attributeName != "")
{
attributeList.push_back(attributeName);
}
}
/* ****************************************************************************
*
* QueryContextRequest::fill -
*/
void QueryContextRequest::fill
(
const std::string& entityId,
const std::string& entityType,
EntityTypeInfo typeInfo,
const std::string& attributeName
)
{
EntityId* eidP = new EntityId(entityId, entityType, "false");
entityIdVector.push_back(eidP);
if ((typeInfo == EntityTypeEmpty) || (typeInfo == EntityTypeNotEmpty))
{
Scope* scopeP = new Scope(SCOPE_FILTER_EXISTENCE, SCOPE_VALUE_ENTITY_TYPE);
scopeP->oper = (typeInfo == EntityTypeEmpty)? SCOPE_OPERATOR_NOT : "";
restriction.scopeVector.push_back(scopeP);
}
if (attributeName != "")
{
attributeList.push_back(attributeName);
}
}
<commit_msg>pre-PR fixes 2<commit_after>/*
*
* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker 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 Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* iot_support at tid dot es
*
* Author: Ken Zangelin
*/
#include <string>
#include "logMsg/logMsg.h"
#include "common/globals.h"
#include "common/tag.h"
#include "ngsi/Request.h"
#include "ngsi/AttributeList.h"
#include "ngsi/EntityIdVector.h"
#include "ngsi/Restriction.h"
#include "ngsi10/QueryContextResponse.h"
#include "ngsi10/QueryContextRequest.h"
#include "rest/ConnectionInfo.h"
#include "rest/EntityTypeInfo.h"
/* ****************************************************************************
*
* QueryContextRequest::QueryContextRequest
*
* Explicit constructor needed to initialize primitive types so they don't get
* random values from the stack
*/
QueryContextRequest::QueryContextRequest()
{
restrictions = 0;
}
/* ****************************************************************************
*
* QueryContextRequest::render -
*/
std::string QueryContextRequest::render(RequestType requestType, Format format, const std::string& indent)
{
std::string out = "";
std::string tag = "queryContextRequest";
bool attributeListRendered = attributeList.size() != 0;
bool restrictionRendered = restrictions != 0;
bool commaAfterAttributeList = restrictionRendered;
bool commaAfterEntityIdVector = attributeListRendered || restrictionRendered;
out += startTag(indent, tag, format, false);
out += entityIdVector.render(format, indent + " ", commaAfterEntityIdVector);
out += attributeList.render(format, indent + " ", commaAfterAttributeList);
out += restriction.render(format, indent + " ", restrictions, false);
out += endTag(indent, tag, format);
return out;
}
/* ****************************************************************************
*
* QueryContextRequest::check -
*/
std::string QueryContextRequest::check(ConnectionInfo* ciP, RequestType requestType, const std::string& indent, const std::string& predetectedError, int counter)
{
std::string res;
QueryContextResponse response;
if (predetectedError != "")
{
response.errorCode.fill(SccBadRequest, predetectedError);
}
else if (((res = entityIdVector.check(QueryContext, ciP->outFormat, indent, predetectedError, 0)) != "OK") ||
((res = attributeList.check(QueryContext, ciP->outFormat, indent, predetectedError, 0)) != "OK") ||
((res = restriction.check(QueryContext, ciP->outFormat, indent, predetectedError, restrictions)) != "OK"))
{
LM_W(("Bad Input (%s)", res.c_str()));
response.errorCode.fill(SccBadRequest, res);
}
else
{
return "OK";
}
return response.render(ciP, QueryContext, indent);
}
/* ****************************************************************************
*
* QueryContextRequest::present -
*/
void QueryContextRequest::present(const std::string& indent)
{
entityIdVector.present(indent);
attributeList.present(indent);
restriction.present(indent);
}
/* ****************************************************************************
*
* QueryContextRequest::release -
*/
void QueryContextRequest::release(void)
{
entityIdVector.release();
restriction.release();
}
/* ****************************************************************************
*
* QueryContextRequest::fill -
*/
void QueryContextRequest::fill(const std::string& entityId, const std::string& entityType, const std::string& attributeName)
{
EntityId* eidP = new EntityId(entityId, entityType, "true");
entityIdVector.push_back(eidP);
if (attributeName != "")
{
attributeList.push_back(attributeName);
}
}
/* ****************************************************************************
*
* QueryContextRequest::fill -
*/
void QueryContextRequest::fill
(
const std::string& entityId,
const std::string& entityType,
EntityTypeInfo typeInfo,
const std::string& attributeName
)
{
EntityId* eidP = new EntityId(entityId, entityType, "false");
entityIdVector.push_back(eidP);
if ((typeInfo == EntityTypeEmpty) || (typeInfo == EntityTypeNotEmpty))
{
Scope* scopeP = new Scope(SCOPE_FILTER_EXISTENCE, SCOPE_VALUE_ENTITY_TYPE);
scopeP->oper = (typeInfo == EntityTypeEmpty)? SCOPE_OPERATOR_NOT : "";
restriction.scopeVector.push_back(scopeP);
}
if (attributeName != "")
{
attributeList.push_back(attributeName);
}
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/generic/memory/lib/utils/bit_count.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2017 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file bit_count.H
/// @brief count bits
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: HB:FSP
#ifndef _MSS_BIT_COUNT_H_
#define _MSS_BIT_COUNT_H_
#include <fapi2.H>
namespace mss
{
///
/// @brief Count the bits in a T which are set (1)
/// @tparam T an integral type. e.g., uint64_t, uint8_t
/// @param[in] i_value the value to check, count
/// @return uint64_t the number of bits set in the input
///
template< typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
inline uint64_t bit_count(const T& i_value)
{
if (i_value == 0)
{
return 0;
}
else
{
return bit_count(i_value >> 1) + (i_value & 0x01);
}
}
///
/// @brief Return the bit position of the first bit set, from the left
/// @tparam T, an integral type. e.g., uint64_t, uint8_t
/// @param[in] i_value the value to check
/// @return uint64_t the bit position of the first set bit
/// @bote assumes you checked to make sure there were bits set because it will return 0
///
template< typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
inline uint64_t first_bit_set(const T& i_value, const uint64_t i_pos = 0)
{
if (i_value == 0)
{
return 0;
}
if (fapi2::buffer<T>(i_value).template getBit(i_pos))
{
return i_pos;
}
else
{
return first_bit_set(i_value, i_pos + 1);
}
}
}
#endif
<commit_msg>L3 work for mss xmls<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/generic/memory/lib/utils/bit_count.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2017 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file bit_count.H
/// @brief count bits
///
// *HWP HWP Owner: Jacob Harvey <jlharvey@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: HB:FSP
#ifndef _MSS_BIT_COUNT_H_
#define _MSS_BIT_COUNT_H_
#include <fapi2.H>
namespace mss
{
///
/// @brief Count the bits in a T which are set (1)
/// @tparam T an integral type. e.g., uint64_t, uint8_t
/// @param[in] i_value the value to check, count
/// @return uint64_t the number of bits set in the input
///
template< typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
inline uint64_t bit_count(const T& i_value)
{
if (i_value == 0)
{
return 0;
}
else
{
return bit_count(i_value >> 1) + (i_value & 0x01);
}
}
///
/// @brief Return the bit position of the first bit set, from the left
/// @tparam T, an integral type. e.g., uint64_t, uint8_t
/// @param[in] i_value the value to check
/// @return uint64_t the bit position of the first set bit
/// @bote assumes you checked to make sure there were bits set because it will return 0
///
template< typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
inline uint64_t first_bit_set(const T& i_value, const uint64_t i_pos = 0)
{
if (i_value == 0)
{
return 0;
}
if (fapi2::buffer<T>(i_value).template getBit(i_pos))
{
return i_pos;
}
else
{
return first_bit_set(i_value, i_pos + 1);
}
}
}
#endif
<|endoftext|>
|
<commit_before>// Licence 2
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include "dart_api.h"
//#include "dart_native_api.h"
struct termios tio;
struct termios stdio;
struct termios old_stdio;
int tty_fd;
/*
Called the first time a native function with a given name is called,
to resolve the Dart name of the native function into a C function pointer.
*/
Dart_NativeFunction ResolveName(Dart_Handle name, int argc);
/*
Called when the extension is loaded.
*/
DART_EXPORT Dart_Handle serial_port_Init(Dart_Handle parent_library) {
if (Dart_IsError(parent_library)) { return parent_library; }
Dart_Handle result_code = Dart_SetNativeResolver(parent_library, ResolveName);
if (Dart_IsError(result_code)) return result_code;
return Dart_Null();
}
Dart_Handle HandleError(Dart_Handle handle) {
if (Dart_IsError(handle)) Dart_PropagateError(handle);
return handle;
}
speed_t toBaudrate(int speed){
switch(speed){
case 50: return B50;
case 75: return B75;
case 110: return B110;
case 134: return B134;
case 150: return B150;
case 200: return B200;
case 300: return B300;
case 600: return B600;
case 1200: return B1200;
case 1800: return B1800;
case 2400: return B2400;
case 4800: return B4800;
case 9600: return B9600;
case 19200: return B19200;
case 38400: return B38400;
case 57600: return B57600;
case 115200: return B115200;
case 230400: return B230400;
}
throw "Unknown baudrate";
}
void SystemOpen(Dart_NativeArguments arguments) {
Dart_EnterScope();
// START opening
tcgetattr(STDOUT_FILENO,&old_stdio);
// TODO values from method
const char *portname = "/dev/tty.usbmodemfd131";
speed_t baudrate = toBaudrate(9600);
memset(&stdio,0,sizeof(stdio));
stdio.c_iflag=0;
stdio.c_oflag=0;
stdio.c_cflag=0;
stdio.c_lflag=0;
stdio.c_cc[VMIN]=1;
stdio.c_cc[VTIME]=0;
tcsetattr(STDOUT_FILENO,TCSANOW,&stdio);
tcsetattr(STDOUT_FILENO,TCSAFLUSH,&stdio);
fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK); // make the reads non-blocking
memset(&tio,0,sizeof(tio));
tio.c_iflag=0;
tio.c_oflag=0;
tio.c_cflag=CS8|CREAD|CLOCAL; // 8n1, see termios.h for more information
tio.c_lflag=0;
tio.c_cc[VMIN]=1;
tio.c_cc[VTIME]=5;
tty_fd=open(portname, O_RDWR | O_NONBLOCK);
bool success = (tty_fd != -1);
if(success){
cfsetospeed(&tio, baudrate);
cfsetispeed(&tio, baudrate);
tcsetattr(tty_fd,TCSANOW,&tio);
}
// END
Dart_SetReturnValue(arguments, HandleError(Dart_NewBoolean(success)));
Dart_ExitScope();
}
void SystemClose(Dart_NativeArguments arguments){
Dart_EnterScope();
close(tty_fd);
tcsetattr(STDOUT_FILENO,TCSANOW,&old_stdio);
Dart_SetReturnValue(arguments, HandleError(Dart_NewBoolean(true)));
Dart_ExitScope();
}
Dart_NativeFunction ResolveName(Dart_Handle name, int argc) {
// If we fail, we return NULL, and Dart throws an exception.
if (!Dart_IsString(name)) return NULL;
Dart_NativeFunction result = NULL;
const char* cname;
HandleError(Dart_StringToCString(name, &cname));
if (strcmp("SystemOpen", cname) == 0) result = SystemOpen;
if (strcmp("SystemClose", cname) == 0) result = SystemClose;
Dart_ExitScope();
return result;
}
/*
void SystemSrand(Dart_NativeArguments arguments) {
Dart_EnterScope();
bool success = false;
Dart_Handle seed_object = HandleError(Dart_GetNativeArgument(arguments, 0));
if (Dart_IsInteger(seed_object)) {
bool fits;
HandleError(Dart_IntegerFitsIntoInt64(seed_object, &fits));
if (fits) {
int64_t seed;
HandleError(Dart_IntegerToInt64(seed_object, &seed));
srand(static_cast<unsigned>(seed));
success = true;
}
}
Dart_SetReturnValue(arguments, HandleError(Dart_NewBoolean(success)));
Dart_ExitScope();
}
uint8_t* randomArray(int seed, int length) {
if (length <= 0 || length > 10000000) return NULL;
uint8_t* values = reinterpret_cast<uint8_t*>(malloc(length));
if (NULL == values) return NULL;
srand(seed);
for (int i = 0; i < length; ++i) {
values[i] = rand() % 256;
}
return values;
}
void wrappedRandomArray(Dart_Port dest_port_id,
Dart_CObject* message) {
Dart_Port reply_port_id = ILLEGAL_PORT;
if (message->type == Dart_CObject_kArray &&
3 == message->value.as_array.length) {
// Use .as_array and .as_int32 to access the data in the Dart_CObject.
Dart_CObject* param0 = message->value.as_array.values[0];
Dart_CObject* param1 = message->value.as_array.values[1];
Dart_CObject* param2 = message->value.as_array.values[2];
if (param0->type == Dart_CObject_kInt32 &&
param1->type == Dart_CObject_kInt32 &&
param2->type == Dart_CObject_kSendPort) {
int seed = param0->value.as_int32;
int length = param1->value.as_int32;
reply_port_id = param2->value.as_send_port;
uint8_t* values = randomArray(seed, length);
if (values != NULL) {
Dart_CObject result;
result.type = Dart_CObject_kTypedData;
result.value.as_typed_data.type = Dart_TypedData_kUint8;
result.value.as_typed_data.values = values;
result.value.as_typed_data.length = length;
Dart_PostCObject(reply_port_id, &result);
free(values);
// It is OK that result is destroyed when function exits.
// Dart_PostCObject has copied its data.
return;
}
}
}
Dart_CObject result;
result.type = Dart_CObject_kNull;
Dart_PostCObject(reply_port_id, &result);
}
void randomArrayServicePort(Dart_NativeArguments arguments) {
Dart_EnterScope();
Dart_SetReturnValue(arguments, Dart_Null());
Dart_Port service_port =
Dart_NewNativePort("RandomArrayService", wrappedRandomArray, true);
if (service_port != ILLEGAL_PORT) {
Dart_Handle send_port = HandleError(Dart_NewSendPort(service_port));
Dart_SetReturnValue(arguments, send_port);
}
Dart_ExitScope();
}
struct FunctionLookup {
const char* name;
Dart_NativeFunction function;
};
FunctionLookup function_list[] = {
{"SystemRand", SystemRand},
{"SystemSrand", SystemSrand},
{"RandomArray_ServicePort", randomArrayServicePort},
{NULL, NULL}};
Dart_NativeFunction ResolveName(Dart_Handle name, int argc) {
if (!Dart_IsString(name)) return NULL;
Dart_NativeFunction result = NULL;
Dart_EnterScope();
const char* cname;
HandleError(Dart_StringToCString(name, &cname));
for (int i=0; function_list[i].name != NULL; ++i) {
if (strcmp(function_list[i].name, cname) == 0) {
result = function_list[i].function;
break;
}
}
Dart_ExitScope();
return result;
}
}
*/
<commit_msg>refacto c internal code<commit_after>// Licence 2
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include "dart_api.h"
//#include "dart_native_api.h"
struct termios tio;
struct termios stdio;
struct termios old_stdio;
int tty_fd;
speed_t toBaudrate(int speed){
switch(speed){
case 50: return B50;
case 75: return B75;
case 110: return B110;
case 134: return B134;
case 150: return B150;
case 200: return B200;
case 300: return B300;
case 600: return B600;
case 1200: return B1200;
case 1800: return B1800;
case 2400: return B2400;
case 4800: return B4800;
case 9600: return B9600;
case 19200: return B19200;
case 38400: return B38400;
case 57600: return B57600;
case 115200: return B115200;
case 230400: return B230400;
}
throw "Unknown baudrate";
}
bool open(){
tcgetattr(STDOUT_FILENO,&old_stdio);
// TODO values from method
const char *portname = "/dev/tty.usbmodemfd131";
speed_t baudrate = toBaudrate(9600);
memset(&stdio,0,sizeof(stdio));
stdio.c_iflag=0;
stdio.c_oflag=0;
stdio.c_cflag=0;
stdio.c_lflag=0;
stdio.c_cc[VMIN]=1;
stdio.c_cc[VTIME]=0;
tcsetattr(STDOUT_FILENO,TCSANOW,&stdio);
tcsetattr(STDOUT_FILENO,TCSAFLUSH,&stdio);
fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK); // make the reads non-blocking
memset(&tio,0,sizeof(tio));
tio.c_iflag=0;
tio.c_oflag=0;
tio.c_cflag=CS8|CREAD|CLOCAL; // 8n1, see termios.h for more information
tio.c_lflag=0;
tio.c_cc[VMIN]=1;
tio.c_cc[VTIME]=5;
tty_fd=open(portname, O_RDWR | O_NONBLOCK);
bool success = (tty_fd != -1);
if(success){
cfsetospeed(&tio, baudrate);
cfsetispeed(&tio, baudrate);
tcsetattr(tty_fd,TCSANOW,&tio);
}
return success;
}
void close(){
close(tty_fd);
tcsetattr(STDOUT_FILENO,TCSANOW,&old_stdio);
}
/*
Called the first time a native function with a given name is called,
to resolve the Dart name of the native function into a C function pointer.
*/
Dart_NativeFunction ResolveName(Dart_Handle name, int argc);
/*
Called when the extension is loaded.
*/
DART_EXPORT Dart_Handle serial_port_Init(Dart_Handle parent_library) {
if (Dart_IsError(parent_library)) { return parent_library; }
Dart_Handle result_code = Dart_SetNativeResolver(parent_library, ResolveName);
if (Dart_IsError(result_code)) return result_code;
return Dart_Null();
}
Dart_Handle HandleError(Dart_Handle handle) {
if (Dart_IsError(handle)) Dart_PropagateError(handle);
return handle;
}
void SystemOpen(Dart_NativeArguments arguments) {
Dart_EnterScope();
bool success = open();
Dart_SetReturnValue(arguments, HandleError(Dart_NewBoolean(success)));
Dart_ExitScope();
}
void SystemClose(Dart_NativeArguments arguments){
Dart_EnterScope();
close();
Dart_SetReturnValue(arguments, HandleError(Dart_NewBoolean(true)));
Dart_ExitScope();
}
Dart_NativeFunction ResolveName(Dart_Handle name, int argc) {
// If we fail, we return NULL, and Dart throws an exception.
if (!Dart_IsString(name)) return NULL;
Dart_NativeFunction result = NULL;
const char* cname;
HandleError(Dart_StringToCString(name, &cname));
if (strcmp("SystemOpen", cname) == 0) result = SystemOpen;
if (strcmp("SystemClose", cname) == 0) result = SystemClose;
Dart_ExitScope();
return result;
}
/*
void SystemSrand(Dart_NativeArguments arguments) {
Dart_EnterScope();
bool success = false;
Dart_Handle seed_object = HandleError(Dart_GetNativeArgument(arguments, 0));
if (Dart_IsInteger(seed_object)) {
bool fits;
HandleError(Dart_IntegerFitsIntoInt64(seed_object, &fits));
if (fits) {
int64_t seed;
HandleError(Dart_IntegerToInt64(seed_object, &seed));
srand(static_cast<unsigned>(seed));
success = true;
}
}
Dart_SetReturnValue(arguments, HandleError(Dart_NewBoolean(success)));
Dart_ExitScope();
}
uint8_t* randomArray(int seed, int length) {
if (length <= 0 || length > 10000000) return NULL;
uint8_t* values = reinterpret_cast<uint8_t*>(malloc(length));
if (NULL == values) return NULL;
srand(seed);
for (int i = 0; i < length; ++i) {
values[i] = rand() % 256;
}
return values;
}
void wrappedRandomArray(Dart_Port dest_port_id,
Dart_CObject* message) {
Dart_Port reply_port_id = ILLEGAL_PORT;
if (message->type == Dart_CObject_kArray &&
3 == message->value.as_array.length) {
// Use .as_array and .as_int32 to access the data in the Dart_CObject.
Dart_CObject* param0 = message->value.as_array.values[0];
Dart_CObject* param1 = message->value.as_array.values[1];
Dart_CObject* param2 = message->value.as_array.values[2];
if (param0->type == Dart_CObject_kInt32 &&
param1->type == Dart_CObject_kInt32 &&
param2->type == Dart_CObject_kSendPort) {
int seed = param0->value.as_int32;
int length = param1->value.as_int32;
reply_port_id = param2->value.as_send_port;
uint8_t* values = randomArray(seed, length);
if (values != NULL) {
Dart_CObject result;
result.type = Dart_CObject_kTypedData;
result.value.as_typed_data.type = Dart_TypedData_kUint8;
result.value.as_typed_data.values = values;
result.value.as_typed_data.length = length;
Dart_PostCObject(reply_port_id, &result);
free(values);
// It is OK that result is destroyed when function exits.
// Dart_PostCObject has copied its data.
return;
}
}
}
Dart_CObject result;
result.type = Dart_CObject_kNull;
Dart_PostCObject(reply_port_id, &result);
}
void randomArrayServicePort(Dart_NativeArguments arguments) {
Dart_EnterScope();
Dart_SetReturnValue(arguments, Dart_Null());
Dart_Port service_port =
Dart_NewNativePort("RandomArrayService", wrappedRandomArray, true);
if (service_port != ILLEGAL_PORT) {
Dart_Handle send_port = HandleError(Dart_NewSendPort(service_port));
Dart_SetReturnValue(arguments, send_port);
}
Dart_ExitScope();
}
struct FunctionLookup {
const char* name;
Dart_NativeFunction function;
};
FunctionLookup function_list[] = {
{"SystemRand", SystemRand},
{"SystemSrand", SystemSrand},
{"RandomArray_ServicePort", randomArrayServicePort},
{NULL, NULL}};
Dart_NativeFunction ResolveName(Dart_Handle name, int argc) {
if (!Dart_IsString(name)) return NULL;
Dart_NativeFunction result = NULL;
Dart_EnterScope();
const char* cname;
HandleError(Dart_StringToCString(name, &cname));
for (int i=0; function_list[i].name != NULL; ++i) {
if (strcmp(function_list[i].name, cname) == 0) {
result = function_list[i].function;
break;
}
}
Dart_ExitScope();
return result;
}
}
*/
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#pragma once
#include "core/reactor.hh"
#include "core/iostream.hh"
#include "core/distributed.hh"
#include "core/print.hh"
#include "core/sstring.hh"
#include "net/api.hh"
#include "util/serialization.hh"
#include "gms/inet_address.hh"
#include "rpc/rpc.hh"
#include <unordered_map>
namespace net {
/* All verb handler identifiers */
enum class messaging_verb : int32_t {
MUTATION,
BINARY, // Deprecated
READ_REPAIR,
READ,
REQUEST_RESPONSE, // client-initiated reads and writes
STREAM_INITIATE, // Deprecated
STREAM_INITIATE_DONE, // Deprecated
STREAM_REPLY, // Deprecated
STREAM_REQUEST, // Deprecated
RANGE_SLICE,
BOOTSTRAP_TOKEN, // Deprecated
TREE_REQUEST, // Deprecated
TREE_RESPONSE, // Deprecated
JOIN, // Deprecated
GOSSIP_DIGEST_SYN,
GOSSIP_DIGEST_ACK,
GOSSIP_DIGEST_ACK2,
DEFINITIONS_ANNOUNCE, // Deprecated
DEFINITIONS_UPDATE,
TRUNCATE,
SCHEMA_CHECK,
INDEX_SCAN, // Deprecated
REPLICATION_FINISHED,
INTERNAL_RESPONSE, // responses to internal calls
COUNTER_MUTATION,
STREAMING_REPAIR_REQUEST, // Deprecated
STREAMING_REPAIR_RESPONSE, // Deprecated
SNAPSHOT, // Similar to nt snapshot
MIGRATION_REQUEST,
GOSSIP_SHUTDOWN,
_TRACE,
ECHO,
REPAIR_MESSAGE,
PAXOS_PREPARE,
PAXOS_PROPOSE,
PAXOS_COMMIT,
PAGED_RANGE,
UNUSED_1,
UNUSED_2,
UNUSED_3,
};
} // namespace net
namespace std {
template <>
class hash<net::messaging_verb> {
public:
size_t operator()(const net::messaging_verb& x) const {
return hash<int32_t>()(int32_t(x));
}
};
} // namespace std
namespace net {
struct serializer {
// For integer type
template<typename T>
inline auto operator()(output_stream<char>& out, T&& v, std::enable_if_t<std::is_integral<std::remove_reference_t<T>>::value, void*> = nullptr) {
auto v_ = net::hton(v);
return out.write(reinterpret_cast<const char*>(&v_), sizeof(T));
}
template<typename T>
inline auto operator()(input_stream<char>& in, T& v, std::enable_if_t<std::is_integral<T>::value, void*> = nullptr) {
return in.read_exactly(sizeof(v)).then([&v] (temporary_buffer<char> buf) mutable {
if (buf.size() != sizeof(v)) {
throw rpc::closed_error();
}
v = net::ntoh(*reinterpret_cast<const net::packed<T>*>(buf.get()));
});
}
// For messaging_verb
inline auto operator()(output_stream<char>& out, messaging_verb& v) {
bytes b(bytes::initialized_later(), sizeof(v));
auto _out = b.begin();
serialize_int32(_out, int32_t(v));
return out.write(reinterpret_cast<const char*>(b.c_str()), sizeof(v));
}
inline auto operator()(input_stream<char>& in, messaging_verb& v) {
return in.read_exactly(sizeof(v)).then([&v] (temporary_buffer<char> buf) mutable {
if (buf.size() != sizeof(v)) {
throw rpc::closed_error();
}
bytes_view bv(reinterpret_cast<const int8_t*>(buf.get()), sizeof(v));
v = messaging_verb(read_simple<int32_t>(bv));
});
}
// For sstring
inline auto operator()(output_stream<char>& out, sstring& v) {
auto serialize_string_size = serialize_int16_size + v.size();
auto sz = serialize_int16_size + serialize_string_size;
bytes b(bytes::initialized_later(), sz);
auto _out = b.begin();
serialize_int16(_out, serialize_string_size);
serialize_string(_out, v);
return out.write(reinterpret_cast<const char*>(b.c_str()), sz);
}
inline auto operator()(input_stream<char>& in, sstring& v) {
return in.read_exactly(serialize_int16_size).then([&in, &v] (temporary_buffer<char> buf) mutable {
if (buf.size() != serialize_int16_size) {
throw rpc::closed_error();
}
size_t serialize_string_size = net::ntoh(*reinterpret_cast<const net::packed<int16_t>*>(buf.get()));
return in.read_exactly(serialize_string_size).then([serialize_string_size, &v]
(temporary_buffer<char> buf) mutable {
if (buf.size() != serialize_string_size) {
throw rpc::closed_error();
}
bytes_view bv(reinterpret_cast<const int8_t*>(buf.get()), serialize_string_size);
new (&v) sstring(read_simple_short_string(bv));
return make_ready_future<>();
});
});
}
// For complex types which have serialize()/deserialize(), e.g. gms::gossip_digest_syn, gms::gossip_digest_ack2
template<typename T>
inline auto operator()(output_stream<char>& out, T&& v, std::enable_if_t<!std::is_integral<std::remove_reference_t<T>>::value &&
!std::is_enum<std::remove_reference_t<T>>::value, void*> = nullptr) {
auto sz = serialize_int32_size + v.serialized_size();
bytes b(bytes::initialized_later(), sz);
auto _out = b.begin();
serialize_int32(_out, int32_t(sz - serialize_int32_size));
v.serialize(_out);
return out.write(reinterpret_cast<const char*>(b.c_str()), sz);
}
template<typename T>
inline auto operator()(input_stream<char>& in, T& v, std::enable_if_t<!std::is_integral<T>::value &&
!std::is_enum<T>::value, void*> = nullptr) {
return in.read_exactly(serialize_int32_size).then([&in, &v] (temporary_buffer<char> buf) mutable {
if (buf.size() != serialize_int32_size) {
throw rpc::closed_error();
}
size_t sz = net::ntoh(*reinterpret_cast<const net::packed<int32_t>*>(buf.get()));
return in.read_exactly(sz).then([sz, &v] (temporary_buffer<char> buf) mutable {
if (buf.size() != sz) {
throw rpc::closed_error();
}
bytes_view bv(reinterpret_cast<const int8_t*>(buf.get()), sz);
new (&v) T(T::deserialize(bv));
return make_ready_future<>();
});
});
}
// For std::tuple<int, long>
inline auto operator()(output_stream<char>& out, std::tuple<int, long>& v) {
auto& x = std::get<0>(v);
auto f = operator()(out, x);
return f.then([this, &out, &v]{
auto& y = std::get<1>(v);
return operator()(out, y);
});
}
inline auto operator()(input_stream<char>& in, std::tuple<int, long>& v) {
auto& x = std::get<0>(v);
auto f = operator()(in, x);
return f.then([this, &in, &v]{
auto& y = std::get<1>(v);
return operator()(in, y);
});
}
};
class messaging_service {
public:
struct shard_id {
gms::inet_address addr;
uint32_t cpu_id;
friend inline bool operator==(const shard_id& x, const shard_id& y) {
return x.addr == y.addr && x.cpu_id == y.cpu_id ;
}
friend inline bool operator<(const shard_id& x, const shard_id& y) {
if (x.addr < y.addr) {
return true;
} else if (y.addr < x.addr) {
return false;
} else {
return x.cpu_id < y.cpu_id;
}
}
friend inline std::ostream& operator<<(std::ostream& os, const shard_id& x) {
return os << x.addr << ":" << x.cpu_id;
}
struct hash {
size_t operator()(const shard_id& id) const {
return std::hash<uint32_t>()(id.cpu_id) + std::hash<uint32_t>()(id.addr.raw_addr());
}
};
};
struct shard_info {
shard_info(std::unique_ptr<rpc::protocol<serializer, messaging_verb>::client>&& client)
: rpc_client(std::move(client)) {
}
std::unique_ptr<rpc::protocol<serializer, messaging_verb>::client> rpc_client;
};
private:
static constexpr const uint16_t _default_port = 7000;
gms::inet_address _listen_address;
uint16_t _port;
rpc::protocol<serializer, messaging_verb> _rpc;
rpc::protocol<serializer, messaging_verb>::server _server;
std::unordered_map<shard_id, shard_info, shard_id::hash> _clients;
public:
messaging_service(gms::inet_address ip = gms::inet_address("0.0.0.0"))
: _listen_address(ip)
, _port(_default_port)
, _rpc(serializer{})
, _server(_rpc, ipv4_addr{_listen_address.raw_addr(), _port}) {
}
public:
uint16_t port() {
return _port;
}
auto listen_address() {
return _listen_address;
}
future<> stop() {
return make_ready_future<>();
}
static auto no_wait() {
return rpc::no_wait;
}
public:
// Register a handler (a callback lambda) for verb
template <typename Func>
void register_handler(messaging_verb verb, Func&& func) {
_rpc.register_handler(verb, std::move(func));
}
// Send a message for verb
template <typename MsgIn, typename... MsgOut>
auto send_message(messaging_verb verb, shard_id id, MsgOut&&... msg) {
auto& rpc_client = get_rpc_client(id);
auto rpc_handler = _rpc.make_client<MsgIn(MsgOut...)>(verb);
return rpc_handler(rpc_client, std::forward<MsgOut>(msg)...).then_wrapped([this, id] (auto&& f) {
try {
if (f.failed()) {
f.get();
assert(false); // never reached
}
return std::move(f);
} catch(...) {
// FIXME: we need to distinguish between a transport error and
// a server error.
// remove_rpc_client(id);
throw;
}
});
}
template <typename... MsgOut>
auto send_message_oneway(messaging_verb verb, shard_id id, MsgOut&&... msg) {
return send_message<rpc::no_wait_type>(std::move(verb), std::move(id), std::forward<MsgOut>(msg)...);
}
private:
// Return rpc::protocol::client for a shard which is a ip + cpuid pair.
rpc::protocol<serializer, messaging_verb>::client& get_rpc_client(shard_id id) {
auto it = _clients.find(id);
if (it == _clients.end()) {
auto remote_addr = ipv4_addr(id.addr.raw_addr(), _port);
auto client = std::make_unique<rpc::protocol<serializer, messaging_verb>::client>(_rpc, remote_addr);
it = _clients.emplace(id, shard_info(std::move(client))).first;
return *it->second.rpc_client;
} else {
return *it->second.rpc_client;
}
}
void remove_rpc_client(shard_id id) {
_clients.erase(id);
}
};
extern distributed<messaging_service> _the_messaging_service;
inline distributed<messaging_service>& get_messaging_service() {
return _the_messaging_service;
}
inline messaging_service& get_local_messaging_service() {
return _the_messaging_service.local();
}
} // namespace net
<commit_msg>messaging: bind rpc client to listen-address<commit_after>/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#pragma once
#include "core/reactor.hh"
#include "core/iostream.hh"
#include "core/distributed.hh"
#include "core/print.hh"
#include "core/sstring.hh"
#include "net/api.hh"
#include "util/serialization.hh"
#include "gms/inet_address.hh"
#include "rpc/rpc.hh"
#include <unordered_map>
namespace net {
/* All verb handler identifiers */
enum class messaging_verb : int32_t {
MUTATION,
BINARY, // Deprecated
READ_REPAIR,
READ,
REQUEST_RESPONSE, // client-initiated reads and writes
STREAM_INITIATE, // Deprecated
STREAM_INITIATE_DONE, // Deprecated
STREAM_REPLY, // Deprecated
STREAM_REQUEST, // Deprecated
RANGE_SLICE,
BOOTSTRAP_TOKEN, // Deprecated
TREE_REQUEST, // Deprecated
TREE_RESPONSE, // Deprecated
JOIN, // Deprecated
GOSSIP_DIGEST_SYN,
GOSSIP_DIGEST_ACK,
GOSSIP_DIGEST_ACK2,
DEFINITIONS_ANNOUNCE, // Deprecated
DEFINITIONS_UPDATE,
TRUNCATE,
SCHEMA_CHECK,
INDEX_SCAN, // Deprecated
REPLICATION_FINISHED,
INTERNAL_RESPONSE, // responses to internal calls
COUNTER_MUTATION,
STREAMING_REPAIR_REQUEST, // Deprecated
STREAMING_REPAIR_RESPONSE, // Deprecated
SNAPSHOT, // Similar to nt snapshot
MIGRATION_REQUEST,
GOSSIP_SHUTDOWN,
_TRACE,
ECHO,
REPAIR_MESSAGE,
PAXOS_PREPARE,
PAXOS_PROPOSE,
PAXOS_COMMIT,
PAGED_RANGE,
UNUSED_1,
UNUSED_2,
UNUSED_3,
};
} // namespace net
namespace std {
template <>
class hash<net::messaging_verb> {
public:
size_t operator()(const net::messaging_verb& x) const {
return hash<int32_t>()(int32_t(x));
}
};
} // namespace std
namespace net {
struct serializer {
// For integer type
template<typename T>
inline auto operator()(output_stream<char>& out, T&& v, std::enable_if_t<std::is_integral<std::remove_reference_t<T>>::value, void*> = nullptr) {
auto v_ = net::hton(v);
return out.write(reinterpret_cast<const char*>(&v_), sizeof(T));
}
template<typename T>
inline auto operator()(input_stream<char>& in, T& v, std::enable_if_t<std::is_integral<T>::value, void*> = nullptr) {
return in.read_exactly(sizeof(v)).then([&v] (temporary_buffer<char> buf) mutable {
if (buf.size() != sizeof(v)) {
throw rpc::closed_error();
}
v = net::ntoh(*reinterpret_cast<const net::packed<T>*>(buf.get()));
});
}
// For messaging_verb
inline auto operator()(output_stream<char>& out, messaging_verb& v) {
bytes b(bytes::initialized_later(), sizeof(v));
auto _out = b.begin();
serialize_int32(_out, int32_t(v));
return out.write(reinterpret_cast<const char*>(b.c_str()), sizeof(v));
}
inline auto operator()(input_stream<char>& in, messaging_verb& v) {
return in.read_exactly(sizeof(v)).then([&v] (temporary_buffer<char> buf) mutable {
if (buf.size() != sizeof(v)) {
throw rpc::closed_error();
}
bytes_view bv(reinterpret_cast<const int8_t*>(buf.get()), sizeof(v));
v = messaging_verb(read_simple<int32_t>(bv));
});
}
// For sstring
inline auto operator()(output_stream<char>& out, sstring& v) {
auto serialize_string_size = serialize_int16_size + v.size();
auto sz = serialize_int16_size + serialize_string_size;
bytes b(bytes::initialized_later(), sz);
auto _out = b.begin();
serialize_int16(_out, serialize_string_size);
serialize_string(_out, v);
return out.write(reinterpret_cast<const char*>(b.c_str()), sz);
}
inline auto operator()(input_stream<char>& in, sstring& v) {
return in.read_exactly(serialize_int16_size).then([&in, &v] (temporary_buffer<char> buf) mutable {
if (buf.size() != serialize_int16_size) {
throw rpc::closed_error();
}
size_t serialize_string_size = net::ntoh(*reinterpret_cast<const net::packed<int16_t>*>(buf.get()));
return in.read_exactly(serialize_string_size).then([serialize_string_size, &v]
(temporary_buffer<char> buf) mutable {
if (buf.size() != serialize_string_size) {
throw rpc::closed_error();
}
bytes_view bv(reinterpret_cast<const int8_t*>(buf.get()), serialize_string_size);
new (&v) sstring(read_simple_short_string(bv));
return make_ready_future<>();
});
});
}
// For complex types which have serialize()/deserialize(), e.g. gms::gossip_digest_syn, gms::gossip_digest_ack2
template<typename T>
inline auto operator()(output_stream<char>& out, T&& v, std::enable_if_t<!std::is_integral<std::remove_reference_t<T>>::value &&
!std::is_enum<std::remove_reference_t<T>>::value, void*> = nullptr) {
auto sz = serialize_int32_size + v.serialized_size();
bytes b(bytes::initialized_later(), sz);
auto _out = b.begin();
serialize_int32(_out, int32_t(sz - serialize_int32_size));
v.serialize(_out);
return out.write(reinterpret_cast<const char*>(b.c_str()), sz);
}
template<typename T>
inline auto operator()(input_stream<char>& in, T& v, std::enable_if_t<!std::is_integral<T>::value &&
!std::is_enum<T>::value, void*> = nullptr) {
return in.read_exactly(serialize_int32_size).then([&in, &v] (temporary_buffer<char> buf) mutable {
if (buf.size() != serialize_int32_size) {
throw rpc::closed_error();
}
size_t sz = net::ntoh(*reinterpret_cast<const net::packed<int32_t>*>(buf.get()));
return in.read_exactly(sz).then([sz, &v] (temporary_buffer<char> buf) mutable {
if (buf.size() != sz) {
throw rpc::closed_error();
}
bytes_view bv(reinterpret_cast<const int8_t*>(buf.get()), sz);
new (&v) T(T::deserialize(bv));
return make_ready_future<>();
});
});
}
// For std::tuple<int, long>
inline auto operator()(output_stream<char>& out, std::tuple<int, long>& v) {
auto& x = std::get<0>(v);
auto f = operator()(out, x);
return f.then([this, &out, &v]{
auto& y = std::get<1>(v);
return operator()(out, y);
});
}
inline auto operator()(input_stream<char>& in, std::tuple<int, long>& v) {
auto& x = std::get<0>(v);
auto f = operator()(in, x);
return f.then([this, &in, &v]{
auto& y = std::get<1>(v);
return operator()(in, y);
});
}
};
class messaging_service {
public:
struct shard_id {
gms::inet_address addr;
uint32_t cpu_id;
friend inline bool operator==(const shard_id& x, const shard_id& y) {
return x.addr == y.addr && x.cpu_id == y.cpu_id ;
}
friend inline bool operator<(const shard_id& x, const shard_id& y) {
if (x.addr < y.addr) {
return true;
} else if (y.addr < x.addr) {
return false;
} else {
return x.cpu_id < y.cpu_id;
}
}
friend inline std::ostream& operator<<(std::ostream& os, const shard_id& x) {
return os << x.addr << ":" << x.cpu_id;
}
struct hash {
size_t operator()(const shard_id& id) const {
return std::hash<uint32_t>()(id.cpu_id) + std::hash<uint32_t>()(id.addr.raw_addr());
}
};
};
struct shard_info {
shard_info(std::unique_ptr<rpc::protocol<serializer, messaging_verb>::client>&& client)
: rpc_client(std::move(client)) {
}
std::unique_ptr<rpc::protocol<serializer, messaging_verb>::client> rpc_client;
};
private:
static constexpr const uint16_t _default_port = 7000;
gms::inet_address _listen_address;
uint16_t _port;
rpc::protocol<serializer, messaging_verb> _rpc;
rpc::protocol<serializer, messaging_verb>::server _server;
std::unordered_map<shard_id, shard_info, shard_id::hash> _clients;
public:
messaging_service(gms::inet_address ip = gms::inet_address("0.0.0.0"))
: _listen_address(ip)
, _port(_default_port)
, _rpc(serializer{})
, _server(_rpc, ipv4_addr{_listen_address.raw_addr(), _port}) {
}
public:
uint16_t port() {
return _port;
}
auto listen_address() {
return _listen_address;
}
future<> stop() {
return make_ready_future<>();
}
static auto no_wait() {
return rpc::no_wait;
}
public:
// Register a handler (a callback lambda) for verb
template <typename Func>
void register_handler(messaging_verb verb, Func&& func) {
_rpc.register_handler(verb, std::move(func));
}
// Send a message for verb
template <typename MsgIn, typename... MsgOut>
auto send_message(messaging_verb verb, shard_id id, MsgOut&&... msg) {
auto& rpc_client = get_rpc_client(id);
auto rpc_handler = _rpc.make_client<MsgIn(MsgOut...)>(verb);
return rpc_handler(rpc_client, std::forward<MsgOut>(msg)...).then_wrapped([this, id] (auto&& f) {
try {
if (f.failed()) {
f.get();
assert(false); // never reached
}
return std::move(f);
} catch(...) {
// FIXME: we need to distinguish between a transport error and
// a server error.
// remove_rpc_client(id);
throw;
}
});
}
template <typename... MsgOut>
auto send_message_oneway(messaging_verb verb, shard_id id, MsgOut&&... msg) {
return send_message<rpc::no_wait_type>(std::move(verb), std::move(id), std::forward<MsgOut>(msg)...);
}
private:
// Return rpc::protocol::client for a shard which is a ip + cpuid pair.
rpc::protocol<serializer, messaging_verb>::client& get_rpc_client(shard_id id) {
auto it = _clients.find(id);
if (it == _clients.end()) {
auto remote_addr = ipv4_addr(id.addr.raw_addr(), _port);
auto client = std::make_unique<rpc::protocol<serializer, messaging_verb>::client>(_rpc, remote_addr, ipv4_addr{_listen_address.raw_addr(), 0});
it = _clients.emplace(id, shard_info(std::move(client))).first;
return *it->second.rpc_client;
} else {
return *it->second.rpc_client;
}
}
void remove_rpc_client(shard_id id) {
_clients.erase(id);
}
};
extern distributed<messaging_service> _the_messaging_service;
inline distributed<messaging_service>& get_messaging_service() {
return _the_messaging_service;
}
inline messaging_service& get_local_messaging_service() {
return _the_messaging_service.local();
}
} // namespace net
<|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 "base/command_line.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "chrome/browser/automation/ui_controls.h"
#include "chrome/browser/chromeos/cros/cros_in_process_browser_test.h"
#include "chrome/browser/chromeos/cros/mock_input_method_library.h"
#include "chrome/browser/chromeos/cros/mock_screen_lock_library.h"
#include "chrome/browser/chromeos/login/mock_authenticator.h"
#include "chrome/browser/chromeos/login/screen_locker.h"
#include "chrome/browser/chromeos/login/screen_locker_tester.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/views/browser_dialogs.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui_test_utils.h"
#include "content/common/notification_service.h"
#include "content/common/notification_type.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "views/controls/textfield/textfield.h"
#include "views/window/window_gtk.h"
namespace {
// An object that wait for lock state and fullscreen state.
class Waiter : public NotificationObserver {
public:
explicit Waiter(Browser* browser)
: browser_(browser),
running_(false) {
registrar_.Add(this,
NotificationType::SCREEN_LOCK_STATE_CHANGED,
NotificationService::AllSources());
handler_id_ = g_signal_connect(
G_OBJECT(browser_->window()->GetNativeHandle()),
"window-state-event",
G_CALLBACK(OnWindowStateEventThunk),
this);
}
~Waiter() {
g_signal_handler_disconnect(
G_OBJECT(browser_->window()->GetNativeHandle()),
handler_id_);
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(type == NotificationType::SCREEN_LOCK_STATE_CHANGED);
if (running_)
MessageLoop::current()->Quit();
}
// Wait until the two conditions are met.
void Wait(bool locker_state, bool fullscreen) {
running_ = true;
scoped_ptr<chromeos::test::ScreenLockerTester>
tester(chromeos::ScreenLocker::GetTester());
while (tester->IsLocked() != locker_state ||
browser_->window()->IsFullscreen() != fullscreen) {
ui_test_utils::RunMessageLoop();
}
// Make sure all pending tasks are executed.
ui_test_utils::RunAllPendingInMessageLoop();
running_ = false;
}
CHROMEGTK_CALLBACK_1(Waiter, gboolean, OnWindowStateEvent,
GdkEventWindowState*);
private:
Browser* browser_;
gulong handler_id_;
NotificationRegistrar registrar_;
// Are we currently running the message loop?
bool running_;
DISALLOW_COPY_AND_ASSIGN(Waiter);
};
gboolean Waiter::OnWindowStateEvent(GtkWidget* widget,
GdkEventWindowState* event) {
MessageLoop::current()->Quit();
return false;
}
} // namespace
namespace chromeos {
class ScreenLockerTest : public CrosInProcessBrowserTest {
public:
ScreenLockerTest() : mock_screen_lock_library_(NULL),
mock_input_method_library_(NULL) {
}
protected:
MockScreenLockLibrary *mock_screen_lock_library_;
MockInputMethodLibrary *mock_input_method_library_;
// Test the no password mode with different unlock scheme given by
// |unlock| function.
void TestNoPassword(void (unlock)(views::Widget*)) {
EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
.Times(1)
.RetiresOnSaturation();
UserManager::Get()->OffTheRecordUserLoggedIn();
ScreenLocker::Show();
scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
tester->EmulateWindowManagerReady();
if (!chromeos::ScreenLocker::GetTester()->IsLocked())
ui_test_utils::WaitForNotification(
NotificationType::SCREEN_LOCK_STATE_CHANGED);
EXPECT_TRUE(tester->IsLocked());
tester->InjectMockAuthenticator("", "");
unlock(tester->GetWidget());
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_TRUE(tester->IsLocked());
// Emulate LockScreen request from PowerManager (via SessionManager).
ScreenLocker::Hide();
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(tester->IsLocked());
}
void LockScreenWithUser(test::ScreenLockerTester* tester,
const std::string& user) {
UserManager::Get()->UserLoggedIn(user);
ScreenLocker::Show();
tester->EmulateWindowManagerReady();
if (!tester->IsLocked()) {
ui_test_utils::WaitForNotification(
NotificationType::SCREEN_LOCK_STATE_CHANGED);
}
EXPECT_TRUE(tester->IsLocked());
}
private:
virtual void SetUpInProcessBrowserTestFixture() {
cros_mock_->InitStatusAreaMocks();
cros_mock_->InitMockScreenLockLibrary();
mock_screen_lock_library_ = cros_mock_->mock_screen_lock_library();
mock_input_method_library_ = cros_mock_->mock_input_method_library();
EXPECT_CALL(*mock_screen_lock_library_, AddObserver(testing::_))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockCompleted())
.Times(1)
.RetiresOnSaturation();
// Expectations for the status are on the screen lock window.
cros_mock_->SetStatusAreaMocksExpectations();
// Expectations for the status area on the browser window.
cros_mock_->SetStatusAreaMocksExpectations();
}
virtual void SetUpCommandLine(CommandLine* command_line) {
command_line->AppendSwitchASCII(switches::kLoginProfile, "user");
command_line->AppendSwitch(switches::kNoFirstRun);
}
DISALLOW_COPY_AND_ASSIGN(ScreenLockerTest);
};
IN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestBasic) {
EXPECT_CALL(*mock_input_method_library_, GetNumActiveInputMethods())
.Times(1)
.WillRepeatedly((testing::Return(0)))
.RetiresOnSaturation();
EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
.Times(1)
.RetiresOnSaturation();
UserManager::Get()->UserLoggedIn("user");
ScreenLocker::Show();
scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
tester->EmulateWindowManagerReady();
if (!chromeos::ScreenLocker::GetTester()->IsLocked())
ui_test_utils::WaitForNotification(
NotificationType::SCREEN_LOCK_STATE_CHANGED);
// Test to make sure that the widget is actually appearing and is of
// reasonable size, preventing a regression of
// http://code.google.com/p/chromium-os/issues/detail?id=5987
gfx::Rect lock_bounds = tester->GetChildWidget()->GetWindowScreenBounds();
EXPECT_GT(lock_bounds.width(), 10);
EXPECT_GT(lock_bounds.height(), 10);
tester->InjectMockAuthenticator("user", "pass");
EXPECT_TRUE(tester->IsLocked());
tester->EnterPassword("fail");
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_TRUE(tester->IsLocked());
tester->EnterPassword("pass");
ui_test_utils::RunAllPendingInMessageLoop();
// Successful authentication simply send a unlock request to PowerManager.
EXPECT_TRUE(tester->IsLocked());
// Emulate LockScreen request from PowerManager (via SessionManager).
// TODO(oshima): Find out better way to handle this in mock.
ScreenLocker::Hide();
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(tester->IsLocked());
}
// Temporarily disabling screen locker tests while investigating the
// issue crbug.com/78764.
IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestFullscreenExit) {
EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
.Times(1)
.RetiresOnSaturation();
scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
{
Waiter waiter(browser());
browser()->ToggleFullscreenMode();
waiter.Wait(false /* not locked */, true /* full screen */);
EXPECT_TRUE(browser()->window()->IsFullscreen());
EXPECT_FALSE(tester->IsLocked());
}
{
Waiter waiter(browser());
UserManager::Get()->UserLoggedIn("user");
ScreenLocker::Show();
tester->EmulateWindowManagerReady();
waiter.Wait(true /* locked */, false /* full screen */);
EXPECT_FALSE(browser()->window()->IsFullscreen());
EXPECT_TRUE(tester->IsLocked());
}
tester->InjectMockAuthenticator("user", "pass");
tester->EnterPassword("pass");
ui_test_utils::RunAllPendingInMessageLoop();
ScreenLocker::Hide();
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(tester->IsLocked());
}
void MouseMove(views::Widget* widget) {
ui_controls::SendMouseMove(10, 10);
}
IN_PROC_BROWSER_TEST_F(ScreenLockerTest,
DISABLED_TestNoPasswordWithMouseMove) {
TestNoPassword(MouseMove);
}
void MouseClick(views::Widget* widget) {
ui_controls::SendMouseClick(ui_controls::RIGHT);
}
IN_PROC_BROWSER_TEST_F(ScreenLockerTest,
DISABLED_TestNoPasswordWithMouseClick) {
TestNoPassword(MouseClick);
}
void KeyPress(views::Widget* widget) {
ui_controls::SendKeyPress(GTK_WINDOW(widget->GetNativeView()),
ui::VKEY_SPACE, false, false, false, false);
}
IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestNoPasswordWithKeyPress) {
TestNoPassword(KeyPress);
}
IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestShowTwice) {
EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
.Times(2)
.RetiresOnSaturation();
scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
LockScreenWithUser(tester.get(), "user");
// Ensure there's a profile or this test crashes.
ProfileManager::GetDefaultProfile();
// Calling Show again simply send LockCompleted signal.
ScreenLocker::Show();
EXPECT_TRUE(tester->IsLocked());
// Close the locker to match expectations.
ScreenLocker::Hide();
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(tester->IsLocked());
}
IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestEscape) {
EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
.Times(1)
.RetiresOnSaturation();
scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
LockScreenWithUser(tester.get(), "user");
// Ensure there's a profile or this test crashes.
ProfileManager::GetDefaultProfile();
tester->SetPassword("password");
EXPECT_EQ("password", tester->GetPassword());
// Escape clears the password.
ui_controls::SendKeyPress(GTK_WINDOW(tester->GetWidget()->GetNativeView()),
ui::VKEY_ESCAPE, false, false, false, false);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_EQ("", tester->GetPassword());
// Close the locker to match expectations.
ScreenLocker::Hide();
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(tester->IsLocked());
}
} // namespace chromeos
<commit_msg>Tag (ScreenLockerTest.TestBasic as flaky.<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 "base/command_line.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "chrome/browser/automation/ui_controls.h"
#include "chrome/browser/chromeos/cros/cros_in_process_browser_test.h"
#include "chrome/browser/chromeos/cros/mock_input_method_library.h"
#include "chrome/browser/chromeos/cros/mock_screen_lock_library.h"
#include "chrome/browser/chromeos/login/mock_authenticator.h"
#include "chrome/browser/chromeos/login/screen_locker.h"
#include "chrome/browser/chromeos/login/screen_locker_tester.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/views/browser_dialogs.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui_test_utils.h"
#include "content/common/notification_service.h"
#include "content/common/notification_type.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "views/controls/textfield/textfield.h"
#include "views/window/window_gtk.h"
namespace {
// An object that wait for lock state and fullscreen state.
class Waiter : public NotificationObserver {
public:
explicit Waiter(Browser* browser)
: browser_(browser),
running_(false) {
registrar_.Add(this,
NotificationType::SCREEN_LOCK_STATE_CHANGED,
NotificationService::AllSources());
handler_id_ = g_signal_connect(
G_OBJECT(browser_->window()->GetNativeHandle()),
"window-state-event",
G_CALLBACK(OnWindowStateEventThunk),
this);
}
~Waiter() {
g_signal_handler_disconnect(
G_OBJECT(browser_->window()->GetNativeHandle()),
handler_id_);
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(type == NotificationType::SCREEN_LOCK_STATE_CHANGED);
if (running_)
MessageLoop::current()->Quit();
}
// Wait until the two conditions are met.
void Wait(bool locker_state, bool fullscreen) {
running_ = true;
scoped_ptr<chromeos::test::ScreenLockerTester>
tester(chromeos::ScreenLocker::GetTester());
while (tester->IsLocked() != locker_state ||
browser_->window()->IsFullscreen() != fullscreen) {
ui_test_utils::RunMessageLoop();
}
// Make sure all pending tasks are executed.
ui_test_utils::RunAllPendingInMessageLoop();
running_ = false;
}
CHROMEGTK_CALLBACK_1(Waiter, gboolean, OnWindowStateEvent,
GdkEventWindowState*);
private:
Browser* browser_;
gulong handler_id_;
NotificationRegistrar registrar_;
// Are we currently running the message loop?
bool running_;
DISALLOW_COPY_AND_ASSIGN(Waiter);
};
gboolean Waiter::OnWindowStateEvent(GtkWidget* widget,
GdkEventWindowState* event) {
MessageLoop::current()->Quit();
return false;
}
} // namespace
namespace chromeos {
class ScreenLockerTest : public CrosInProcessBrowserTest {
public:
ScreenLockerTest() : mock_screen_lock_library_(NULL),
mock_input_method_library_(NULL) {
}
protected:
MockScreenLockLibrary *mock_screen_lock_library_;
MockInputMethodLibrary *mock_input_method_library_;
// Test the no password mode with different unlock scheme given by
// |unlock| function.
void TestNoPassword(void (unlock)(views::Widget*)) {
EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
.Times(1)
.RetiresOnSaturation();
UserManager::Get()->OffTheRecordUserLoggedIn();
ScreenLocker::Show();
scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
tester->EmulateWindowManagerReady();
if (!chromeos::ScreenLocker::GetTester()->IsLocked())
ui_test_utils::WaitForNotification(
NotificationType::SCREEN_LOCK_STATE_CHANGED);
EXPECT_TRUE(tester->IsLocked());
tester->InjectMockAuthenticator("", "");
unlock(tester->GetWidget());
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_TRUE(tester->IsLocked());
// Emulate LockScreen request from PowerManager (via SessionManager).
ScreenLocker::Hide();
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(tester->IsLocked());
}
void LockScreenWithUser(test::ScreenLockerTester* tester,
const std::string& user) {
UserManager::Get()->UserLoggedIn(user);
ScreenLocker::Show();
tester->EmulateWindowManagerReady();
if (!tester->IsLocked()) {
ui_test_utils::WaitForNotification(
NotificationType::SCREEN_LOCK_STATE_CHANGED);
}
EXPECT_TRUE(tester->IsLocked());
}
private:
virtual void SetUpInProcessBrowserTestFixture() {
cros_mock_->InitStatusAreaMocks();
cros_mock_->InitMockScreenLockLibrary();
mock_screen_lock_library_ = cros_mock_->mock_screen_lock_library();
mock_input_method_library_ = cros_mock_->mock_input_method_library();
EXPECT_CALL(*mock_screen_lock_library_, AddObserver(testing::_))
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockCompleted())
.Times(1)
.RetiresOnSaturation();
// Expectations for the status are on the screen lock window.
cros_mock_->SetStatusAreaMocksExpectations();
// Expectations for the status area on the browser window.
cros_mock_->SetStatusAreaMocksExpectations();
}
virtual void SetUpCommandLine(CommandLine* command_line) {
command_line->AppendSwitchASCII(switches::kLoginProfile, "user");
command_line->AppendSwitch(switches::kNoFirstRun);
}
DISALLOW_COPY_AND_ASSIGN(ScreenLockerTest);
};
// See http://crbug.com/79374
IN_PROC_BROWSER_TEST_F(ScreenLockerTest, FLAKY_TestBasic) {
EXPECT_CALL(*mock_input_method_library_, GetNumActiveInputMethods())
.Times(1)
.WillRepeatedly((testing::Return(0)))
.RetiresOnSaturation();
EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
.Times(1)
.RetiresOnSaturation();
UserManager::Get()->UserLoggedIn("user");
ScreenLocker::Show();
scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
tester->EmulateWindowManagerReady();
if (!chromeos::ScreenLocker::GetTester()->IsLocked())
ui_test_utils::WaitForNotification(
NotificationType::SCREEN_LOCK_STATE_CHANGED);
// Test to make sure that the widget is actually appearing and is of
// reasonable size, preventing a regression of
// http://code.google.com/p/chromium-os/issues/detail?id=5987
gfx::Rect lock_bounds = tester->GetChildWidget()->GetWindowScreenBounds();
EXPECT_GT(lock_bounds.width(), 10);
EXPECT_GT(lock_bounds.height(), 10);
tester->InjectMockAuthenticator("user", "pass");
EXPECT_TRUE(tester->IsLocked());
tester->EnterPassword("fail");
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_TRUE(tester->IsLocked());
tester->EnterPassword("pass");
ui_test_utils::RunAllPendingInMessageLoop();
// Successful authentication simply send a unlock request to PowerManager.
EXPECT_TRUE(tester->IsLocked());
// Emulate LockScreen request from PowerManager (via SessionManager).
// TODO(oshima): Find out better way to handle this in mock.
ScreenLocker::Hide();
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(tester->IsLocked());
}
// Temporarily disabling screen locker tests while investigating the
// issue crbug.com/78764.
IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestFullscreenExit) {
EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())
.Times(1)
.RetiresOnSaturation();
EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
.Times(1)
.RetiresOnSaturation();
scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
{
Waiter waiter(browser());
browser()->ToggleFullscreenMode();
waiter.Wait(false /* not locked */, true /* full screen */);
EXPECT_TRUE(browser()->window()->IsFullscreen());
EXPECT_FALSE(tester->IsLocked());
}
{
Waiter waiter(browser());
UserManager::Get()->UserLoggedIn("user");
ScreenLocker::Show();
tester->EmulateWindowManagerReady();
waiter.Wait(true /* locked */, false /* full screen */);
EXPECT_FALSE(browser()->window()->IsFullscreen());
EXPECT_TRUE(tester->IsLocked());
}
tester->InjectMockAuthenticator("user", "pass");
tester->EnterPassword("pass");
ui_test_utils::RunAllPendingInMessageLoop();
ScreenLocker::Hide();
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(tester->IsLocked());
}
void MouseMove(views::Widget* widget) {
ui_controls::SendMouseMove(10, 10);
}
IN_PROC_BROWSER_TEST_F(ScreenLockerTest,
DISABLED_TestNoPasswordWithMouseMove) {
TestNoPassword(MouseMove);
}
void MouseClick(views::Widget* widget) {
ui_controls::SendMouseClick(ui_controls::RIGHT);
}
IN_PROC_BROWSER_TEST_F(ScreenLockerTest,
DISABLED_TestNoPasswordWithMouseClick) {
TestNoPassword(MouseClick);
}
void KeyPress(views::Widget* widget) {
ui_controls::SendKeyPress(GTK_WINDOW(widget->GetNativeView()),
ui::VKEY_SPACE, false, false, false, false);
}
IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestNoPasswordWithKeyPress) {
TestNoPassword(KeyPress);
}
IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestShowTwice) {
EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
.Times(2)
.RetiresOnSaturation();
scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
LockScreenWithUser(tester.get(), "user");
// Ensure there's a profile or this test crashes.
ProfileManager::GetDefaultProfile();
// Calling Show again simply send LockCompleted signal.
ScreenLocker::Show();
EXPECT_TRUE(tester->IsLocked());
// Close the locker to match expectations.
ScreenLocker::Hide();
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(tester->IsLocked());
}
IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestEscape) {
EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
.Times(1)
.RetiresOnSaturation();
scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
LockScreenWithUser(tester.get(), "user");
// Ensure there's a profile or this test crashes.
ProfileManager::GetDefaultProfile();
tester->SetPassword("password");
EXPECT_EQ("password", tester->GetPassword());
// Escape clears the password.
ui_controls::SendKeyPress(GTK_WINDOW(tester->GetWidget()->GetNativeView()),
ui::VKEY_ESCAPE, false, false, false, false);
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_EQ("", tester->GetPassword());
// Close the locker to match expectations.
ScreenLocker::Hide();
ui_test_utils::RunAllPendingInMessageLoop();
EXPECT_FALSE(tester->IsLocked());
}
} // namespace chromeos
<|endoftext|>
|
<commit_before>// Copyright (c) 2008 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 <vector>
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/user_script_master.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_details.h"
#include "chrome/common/notification_observer.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/net_util.h"
// This file contains high-level startup tests for the extensions system. We've
// had many silly bugs where command line flags did not get propagated correctly
// into the services, so we didn't start correctly.
class ExtensionStartupTestBase : public InProcessBrowserTest {
public:
ExtensionStartupTestBase() : enable_extensions_(false) {
}
protected:
// InProcessBrowserTest
virtual void SetUpCommandLine(CommandLine* command_line) {
EnableDOMAutomation();
FilePath profile_dir;
PathService::Get(chrome::DIR_USER_DATA, &profile_dir);
profile_dir = profile_dir.AppendASCII("Default");
file_util::CreateDirectory(profile_dir);
preferences_file_ = profile_dir.AppendASCII("Preferences");
user_scripts_dir_ = profile_dir.AppendASCII("User Scripts");
extensions_dir_ = profile_dir.AppendASCII("Extensions");
if (enable_extensions_) {
FilePath src_dir;
PathService::Get(chrome::DIR_TEST_DATA, &src_dir);
src_dir = src_dir.AppendASCII("extensions").AppendASCII("good");
file_util::CopyFile(src_dir.AppendASCII("Preferences"),
preferences_file_);
file_util::CopyDirectory(src_dir.AppendASCII("Extensions"),
profile_dir, true); // recursive
} else {
command_line->AppendSwitch(switches::kDisableExtensions);
}
if (!load_extension_.value().empty()) {
command_line->AppendSwitchWithValue(switches::kLoadExtension,
load_extension_.ToWStringHack());
}
}
virtual void TearDown() {
EXPECT_TRUE(file_util::Delete(preferences_file_, false));
// TODO(phajdan.jr): Check return values of the functions below, carefully.
file_util::Delete(user_scripts_dir_, true);
file_util::Delete(extensions_dir_, true);
}
void WaitForServicesToStart(int num_expected_extensions,
bool expect_extensions_enabled) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
if (!service->is_ready())
ui_test_utils::WaitForNotification(NotificationType::EXTENSIONS_READY);
ASSERT_TRUE(service->is_ready());
ASSERT_EQ(static_cast<uint32>(num_expected_extensions),
service->extensions()->size());
ASSERT_EQ(expect_extensions_enabled, service->extensions_enabled());
UserScriptMaster* master = browser()->profile()->GetUserScriptMaster();
if (!master->ScriptsReady()) {
ui_test_utils::WaitForNotification(
NotificationType::USER_SCRIPTS_UPDATED);
}
ASSERT_TRUE(master->ScriptsReady());
}
void TestInjection(bool expect_css, bool expect_script) {
// Load a page affected by the content script and test to see the effect.
FilePath test_file;
PathService::Get(chrome::DIR_TEST_DATA, &test_file);
test_file = test_file.AppendASCII("extensions")
.AppendASCII("test_file.html");
ui_test_utils::NavigateToURL(browser(), net::FilePathToFileURL(test_file));
bool result = false;
ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send("
L"document.defaultView.getComputedStyle(document.body, null)."
L"getPropertyValue('background-color') == 'rgb(245, 245, 220)')",
&result);
EXPECT_EQ(expect_css, result);
result = false;
ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send(document.title == 'Modified')",
&result);
EXPECT_EQ(expect_script, result);
}
FilePath preferences_file_;
FilePath extensions_dir_;
FilePath user_scripts_dir_;
bool enable_extensions_;
FilePath load_extension_;
};
// ExtensionsStartupTest
// Ensures that we can startup the browser with --enable-extensions and some
// extensions installed and see them run and do basic things.
class ExtensionsStartupTest : public ExtensionStartupTestBase {
public:
ExtensionsStartupTest() {
enable_extensions_ = true;
}
};
IN_PROC_BROWSER_TEST_F(ExtensionsStartupTest, MAYBE_Test) {
WaitForServicesToStart(4, true); // 1 component extension and 3 others.
TestInjection(true, true);
}
// ExtensionsLoadTest
// Ensures that we can startup the browser with --load-extension and see them
// run.
class ExtensionsLoadTest : public ExtensionStartupTestBase {
public:
ExtensionsLoadTest() {
PathService::Get(chrome::DIR_TEST_DATA, &load_extension_);
load_extension_ = load_extension_
.AppendASCII("extensions")
.AppendASCII("good")
.AppendASCII("Extensions")
.AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
.AppendASCII("1.0.0.0");
}
};
// Flaky (times out) on Mac/Windows. http://crbug.com/46301.
#if defined(OS_MAC) || defined(OS_WIN)
#define MAYBE_Test FLAKY_Test
#else
#define MAYBE_Test Test
#endif
IN_PROC_BROWSER_TEST_F(ExtensionsLoadTest, MAYBE_Test) {
WaitForServicesToStart(1, false);
TestInjection(true, true);
}
<commit_msg>Remove MAYBE_ prefix from ExtensionStartupTesst.Test (fixing my mistake)<commit_after>// Copyright (c) 2008 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 <vector>
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/user_script_master.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_details.h"
#include "chrome/common/notification_observer.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/net_util.h"
// This file contains high-level startup tests for the extensions system. We've
// had many silly bugs where command line flags did not get propagated correctly
// into the services, so we didn't start correctly.
class ExtensionStartupTestBase : public InProcessBrowserTest {
public:
ExtensionStartupTestBase() : enable_extensions_(false) {
}
protected:
// InProcessBrowserTest
virtual void SetUpCommandLine(CommandLine* command_line) {
EnableDOMAutomation();
FilePath profile_dir;
PathService::Get(chrome::DIR_USER_DATA, &profile_dir);
profile_dir = profile_dir.AppendASCII("Default");
file_util::CreateDirectory(profile_dir);
preferences_file_ = profile_dir.AppendASCII("Preferences");
user_scripts_dir_ = profile_dir.AppendASCII("User Scripts");
extensions_dir_ = profile_dir.AppendASCII("Extensions");
if (enable_extensions_) {
FilePath src_dir;
PathService::Get(chrome::DIR_TEST_DATA, &src_dir);
src_dir = src_dir.AppendASCII("extensions").AppendASCII("good");
file_util::CopyFile(src_dir.AppendASCII("Preferences"),
preferences_file_);
file_util::CopyDirectory(src_dir.AppendASCII("Extensions"),
profile_dir, true); // recursive
} else {
command_line->AppendSwitch(switches::kDisableExtensions);
}
if (!load_extension_.value().empty()) {
command_line->AppendSwitchWithValue(switches::kLoadExtension,
load_extension_.ToWStringHack());
}
}
virtual void TearDown() {
EXPECT_TRUE(file_util::Delete(preferences_file_, false));
// TODO(phajdan.jr): Check return values of the functions below, carefully.
file_util::Delete(user_scripts_dir_, true);
file_util::Delete(extensions_dir_, true);
}
void WaitForServicesToStart(int num_expected_extensions,
bool expect_extensions_enabled) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
if (!service->is_ready())
ui_test_utils::WaitForNotification(NotificationType::EXTENSIONS_READY);
ASSERT_TRUE(service->is_ready());
ASSERT_EQ(static_cast<uint32>(num_expected_extensions),
service->extensions()->size());
ASSERT_EQ(expect_extensions_enabled, service->extensions_enabled());
UserScriptMaster* master = browser()->profile()->GetUserScriptMaster();
if (!master->ScriptsReady()) {
ui_test_utils::WaitForNotification(
NotificationType::USER_SCRIPTS_UPDATED);
}
ASSERT_TRUE(master->ScriptsReady());
}
void TestInjection(bool expect_css, bool expect_script) {
// Load a page affected by the content script and test to see the effect.
FilePath test_file;
PathService::Get(chrome::DIR_TEST_DATA, &test_file);
test_file = test_file.AppendASCII("extensions")
.AppendASCII("test_file.html");
ui_test_utils::NavigateToURL(browser(), net::FilePathToFileURL(test_file));
bool result = false;
ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send("
L"document.defaultView.getComputedStyle(document.body, null)."
L"getPropertyValue('background-color') == 'rgb(245, 245, 220)')",
&result);
EXPECT_EQ(expect_css, result);
result = false;
ui_test_utils::ExecuteJavaScriptAndExtractBool(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send(document.title == 'Modified')",
&result);
EXPECT_EQ(expect_script, result);
}
FilePath preferences_file_;
FilePath extensions_dir_;
FilePath user_scripts_dir_;
bool enable_extensions_;
FilePath load_extension_;
};
// ExtensionsStartupTest
// Ensures that we can startup the browser with --enable-extensions and some
// extensions installed and see them run and do basic things.
class ExtensionsStartupTest : public ExtensionStartupTestBase {
public:
ExtensionsStartupTest() {
enable_extensions_ = true;
}
};
IN_PROC_BROWSER_TEST_F(ExtensionsStartupTest, Test) {
WaitForServicesToStart(4, true); // 1 component extension and 3 others.
TestInjection(true, true);
}
// ExtensionsLoadTest
// Ensures that we can startup the browser with --load-extension and see them
// run.
class ExtensionsLoadTest : public ExtensionStartupTestBase {
public:
ExtensionsLoadTest() {
PathService::Get(chrome::DIR_TEST_DATA, &load_extension_);
load_extension_ = load_extension_
.AppendASCII("extensions")
.AppendASCII("good")
.AppendASCII("Extensions")
.AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
.AppendASCII("1.0.0.0");
}
};
// Flaky (times out) on Mac/Windows. http://crbug.com/46301.
#if defined(OS_MAC) || defined(OS_WIN)
#define MAYBE_Test FLAKY_Test
#else
#define MAYBE_Test Test
#endif
IN_PROC_BROWSER_TEST_F(ExtensionsLoadTest, MAYBE_Test) {
WaitForServicesToStart(1, false);
TestInjection(true, true);
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.