text
stringlengths 54
60.6k
|
|---|
<commit_before>/*
* Copyright 2013 Coherent Theory LLC
*
* This program 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, 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 Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "updatedassetsmodel.h"
#include "assethandler.h"
#include "assetbriefsjob.h"
#include "session.h"
#include <QDebug>
#include <QFile>
#include <QMetaEnum>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
#include <QSqlRecord>
#define SESSION_ID(store, warehouse) store + QLatin1Char('_') + warehouse
namespace Bodega {
class UpdatedAssetsModel::Private
{
public:
Private(UpdatedAssetsModel *parent) :
q(parent)
{
}
~Private()
{
}
UpdatedAssetsModel *q;
QList<AssetInfo> assets;
QHash<QString, QStringList> pendingAssets;
QHash<QString, Session *> sessions;
QSqlDatabase db;
void briefsJobFinished(Bodega::NetworkJob *);
void reloadFromNetwork(bool);
void fetchBriefs(const QString &store, const QString &warehouse, const QStringList &assets);
void sessionAuthenticated(bool authed);
};
void UpdatedAssetsModel::Private::briefsJobFinished(Bodega::NetworkJob *job)
{
AssetBriefsJob *briefsJob = qobject_cast<AssetBriefsJob *>(job);
if (!briefsJob) {
return;
}
if (briefsJob->assets().isEmpty()) {
return;
}
q->beginInsertRows(QModelIndex(), assets.size(), assets.size() + briefsJob->assets().size());
assets.append(briefsJob->assets());
q->endInsertRows();
}
void UpdatedAssetsModel::Private::fetchBriefs(const QString &store, const QString &warehouse, const QStringList &assets)
{
const QString sessionId(SESSION_ID(store, warehouse));
Bodega::Session *session = sessions.value(sessionId);
if (!session) {
pendingAssets[sessionId].append(assets);
session = new Bodega::Session(q);
session->setBaseUrl(warehouse);
session->setStoreId(store);
//FIXME!
session->setUserName(QLatin1String("zack@kde.org"));
session->setPassword(QLatin1String("zack"));
sessions.insert(sessionId, session);
connect(session, SIGNAL(authenticated(bool)), q, SLOT(sessionAuthenticated(bool)));
} else if (session->isAuthenticated()) {
Bodega::AssetBriefsJob *job = session->assetBriefs(assets);
connect(job, SIGNAL(jobFinished(Bodega::NetworkJob*)),
q, SLOT(briefsJobFinished(Bodega::NetworkJob*)));
} else {
pendingAssets[sessionId].append(assets);
}
}
void UpdatedAssetsModel::Private::sessionAuthenticated(bool authed)
{
if (!authed) {
//TODO: show an error, re-auth?
return;
}
Bodega::Session *session = qobject_cast<Bodega::Session *>(q->sender());
if (!session) {
return;
}
disconnect(session, SIGNAL(authenticated(bool)), q, SLOT(sessionAuthenticated(bool)));
const QString warehouse = session->baseUrl().toString();
const QString sessionId = SESSION_ID(session->storeId(), warehouse);
if (!pendingAssets.value(sessionId).isEmpty()) {
fetchBriefs(session->storeId(), warehouse, pendingAssets.value(sessionId));
}
}
UpdatedAssetsModel::UpdatedAssetsModel(QObject *parent)
: d(new Private(this))
{
QHash<int, QByteArray> roles;
roles.insert(Qt::DisplayRole, "DisplayRole");
roles.insert(Qt::DecorationRole, "DecorationRole");
QMetaEnum e = metaObject()->enumerator(metaObject()->indexOfEnumerator("DisplayRoles"));
for (int i = 0; i < e.keyCount(); ++i) {
roles.insert(e.value(i), e.key(i));
}
setRoleNames(roles);
}
UpdatedAssetsModel::~UpdatedAssetsModel()
{
delete d;
}
void UpdatedAssetsModel::reload()
{
beginResetModel();
d->assets.clear();
endResetModel();
if (!d->db.isValid()) {
const QString dbPath = Bodega::AssetHandler::updateDatabasePath();
if (QFile::exists(dbPath)) {
d->db = Bodega::AssetHandler::updateDatabase();
}
if (!d->db.isValid()) {
return;
}
}
QSqlQuery query(d->db);
query.prepare(QLatin1String("SELECT store, warehouse, asset FROM assets WHERE updated ORDER BY warehouse, store"));
if (!query.exec()) {
qDebug() << "Failed to get updated asset list from database:" << query.lastError();
return;
}
QString currentStore;
QString currentWarehouse;
QSqlRecord record = query.record();
const int storeCol = record.indexOf(QLatin1String("store"));
const int warehouseCol = record.indexOf(QLatin1String("warehouse"));
const int assetCol = record.indexOf(QLatin1String("asset"));
QStringList assets;
while (query.next()) {
const QString store = query.value(storeCol).toString();
const QString warehouse = query.value(warehouseCol).toString();
const QString asset = query.value(assetCol).toString();
if (currentStore != store || currentWarehouse != warehouse) {
if (!currentStore.isEmpty()) {
d->fetchBriefs(currentStore, currentWarehouse, assets);
assets.clear();
}
currentStore = store;
currentWarehouse = warehouse;
}
assets.append(asset);
}
if (!assets.isEmpty()) {
d->fetchBriefs(currentStore, currentWarehouse, assets);
}
}
int UpdatedAssetsModel::columnCount(const QModelIndex &parent) const
{
return 1;
}
QVariant UpdatedAssetsModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || index.row() > d->assets.size()) {
return QVariant();
}
const AssetInfo &info = d->assets.at(index.row());
switch (role) {
case Qt::DisplayRole:
return info.name;
case AssetIdRole:
return info.id;
case AssetNameRole:
return info.name;
case AssetVersionRole:
return info.version;
case AssetFilenameRole:
return info.filename;
case AssetLicenseRole:
return info.license;
case AssetLicenseTextRole:
return info.licenseText;
case AssetPartnerIdRole:
return info.partnerId;
case AssetPartnerNameRole:
return info.partnerName;
case ImageTinyRole:
return info.images.value(Bodega::ImageTiny);
case ImageSmallRole:
return info.images.value(Bodega::ImageSmall);
case ImageMediumRole:
return info.images.value(Bodega::ImageMedium);
case ImageLargeRole:
return info.images.value(Bodega::ImageLarge);
case ImageHugeRole:
return info.images.value(Bodega::ImageHuge);
case ImagePreviewsRole:
return info.images.value(Bodega::ImagePreviews);
case SessionRole:
default:
return QVariant();
}
}
bool UpdatedAssetsModel::hasChildren(const QModelIndex &parent) const
{
return false;
}
QModelIndex UpdatedAssetsModel::index(int row, int column, const QModelIndex &parent) const
{
if (!hasIndex(row, column, parent)) {
return QModelIndex();
}
return createIndex(row, column);
}
QModelIndex UpdatedAssetsModel::parent(const QModelIndex &index) const
{
return QModelIndex();
}
int UpdatedAssetsModel::rowCount(const QModelIndex &parent) const
{
return d->assets.size();
}
}
#include "updatedassetsmodel.moc"
<commit_msg>assets -> assetIds<commit_after>/*
* Copyright 2013 Coherent Theory LLC
*
* This program 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, 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 Library General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "updatedassetsmodel.h"
#include "assethandler.h"
#include "assetbriefsjob.h"
#include "session.h"
#include <QDebug>
#include <QFile>
#include <QMetaEnum>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
#include <QSqlRecord>
#define SESSION_ID(store, warehouse) store + QLatin1Char('_') + warehouse
namespace Bodega {
class UpdatedAssetsModel::Private
{
public:
Private(UpdatedAssetsModel *parent) :
q(parent)
{
}
~Private()
{
}
UpdatedAssetsModel *q;
QList<AssetInfo> assets;
QHash<QString, QStringList> pendingAssets;
QHash<QString, Session *> sessions;
QSqlDatabase db;
void briefsJobFinished(Bodega::NetworkJob *);
void reloadFromNetwork(bool);
void fetchBriefs(const QString &store, const QString &warehouse, const QStringList &assets);
void sessionAuthenticated(bool authed);
};
void UpdatedAssetsModel::Private::briefsJobFinished(Bodega::NetworkJob *job)
{
AssetBriefsJob *briefsJob = qobject_cast<AssetBriefsJob *>(job);
if (!briefsJob) {
return;
}
if (briefsJob->assets().isEmpty()) {
return;
}
q->beginInsertRows(QModelIndex(), assets.size(), assets.size() + briefsJob->assets().size());
assets.append(briefsJob->assets());
q->endInsertRows();
}
void UpdatedAssetsModel::Private::fetchBriefs(const QString &store, const QString &warehouse, const QStringList &assets)
{
const QString sessionId(SESSION_ID(store, warehouse));
Bodega::Session *session = sessions.value(sessionId);
if (!session) {
pendingAssets[sessionId].append(assets);
session = new Bodega::Session(q);
session->setBaseUrl(warehouse);
session->setStoreId(store);
//FIXME!
session->setUserName(QLatin1String("zack@kde.org"));
session->setPassword(QLatin1String("zack"));
sessions.insert(sessionId, session);
connect(session, SIGNAL(authenticated(bool)), q, SLOT(sessionAuthenticated(bool)));
} else if (session->isAuthenticated()) {
Bodega::AssetBriefsJob *job = session->assetBriefs(assets);
connect(job, SIGNAL(jobFinished(Bodega::NetworkJob*)),
q, SLOT(briefsJobFinished(Bodega::NetworkJob*)));
} else {
pendingAssets[sessionId].append(assets);
}
}
void UpdatedAssetsModel::Private::sessionAuthenticated(bool authed)
{
if (!authed) {
//TODO: show an error, re-auth?
return;
}
Bodega::Session *session = qobject_cast<Bodega::Session *>(q->sender());
if (!session) {
return;
}
disconnect(session, SIGNAL(authenticated(bool)), q, SLOT(sessionAuthenticated(bool)));
const QString warehouse = session->baseUrl().toString();
const QString sessionId = SESSION_ID(session->storeId(), warehouse);
if (!pendingAssets.value(sessionId).isEmpty()) {
fetchBriefs(session->storeId(), warehouse, pendingAssets.value(sessionId));
}
}
UpdatedAssetsModel::UpdatedAssetsModel(QObject *parent)
: d(new Private(this))
{
QHash<int, QByteArray> roles;
roles.insert(Qt::DisplayRole, "DisplayRole");
roles.insert(Qt::DecorationRole, "DecorationRole");
QMetaEnum e = metaObject()->enumerator(metaObject()->indexOfEnumerator("DisplayRoles"));
for (int i = 0; i < e.keyCount(); ++i) {
roles.insert(e.value(i), e.key(i));
}
setRoleNames(roles);
}
UpdatedAssetsModel::~UpdatedAssetsModel()
{
delete d;
}
void UpdatedAssetsModel::reload()
{
beginResetModel();
d->assets.clear();
endResetModel();
if (!d->db.isValid()) {
const QString dbPath = Bodega::AssetHandler::updateDatabasePath();
if (QFile::exists(dbPath)) {
d->db = Bodega::AssetHandler::updateDatabase();
}
if (!d->db.isValid()) {
return;
}
}
QSqlQuery query(d->db);
query.prepare(QLatin1String("SELECT store, warehouse, asset FROM assets WHERE updated ORDER BY warehouse, store"));
if (!query.exec()) {
qDebug() << "Failed to get updated asset list from database:" << query.lastError();
return;
}
QString currentStore;
QString currentWarehouse;
QSqlRecord record = query.record();
const int storeCol = record.indexOf(QLatin1String("store"));
const int warehouseCol = record.indexOf(QLatin1String("warehouse"));
const int assetCol = record.indexOf(QLatin1String("asset"));
QStringList assetIds;
while (query.next()) {
const QString store = query.value(storeCol).toString();
const QString warehouse = query.value(warehouseCol).toString();
const QString asset = query.value(assetCol).toString();
if (currentStore != store || currentWarehouse != warehouse) {
if (!currentStore.isEmpty()) {
d->fetchBriefs(currentStore, currentWarehouse, assetIds);
assetIds.clear();
}
currentStore = store;
currentWarehouse = warehouse;
}
assetIds.append(asset);
}
if (!assetIds.isEmpty()) {
d->fetchBriefs(currentStore, currentWarehouse, assetIds);
}
}
int UpdatedAssetsModel::columnCount(const QModelIndex &parent) const
{
return 1;
}
QVariant UpdatedAssetsModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || index.row() > d->assets.size()) {
return QVariant();
}
const AssetInfo &info = d->assets.at(index.row());
switch (role) {
case Qt::DisplayRole:
return info.name;
case AssetIdRole:
return info.id;
case AssetNameRole:
return info.name;
case AssetVersionRole:
return info.version;
case AssetFilenameRole:
return info.filename;
case AssetLicenseRole:
return info.license;
case AssetLicenseTextRole:
return info.licenseText;
case AssetPartnerIdRole:
return info.partnerId;
case AssetPartnerNameRole:
return info.partnerName;
case ImageTinyRole:
return info.images.value(Bodega::ImageTiny);
case ImageSmallRole:
return info.images.value(Bodega::ImageSmall);
case ImageMediumRole:
return info.images.value(Bodega::ImageMedium);
case ImageLargeRole:
return info.images.value(Bodega::ImageLarge);
case ImageHugeRole:
return info.images.value(Bodega::ImageHuge);
case ImagePreviewsRole:
return info.images.value(Bodega::ImagePreviews);
case SessionRole:
default:
return QVariant();
}
}
bool UpdatedAssetsModel::hasChildren(const QModelIndex &parent) const
{
return false;
}
QModelIndex UpdatedAssetsModel::index(int row, int column, const QModelIndex &parent) const
{
if (!hasIndex(row, column, parent)) {
return QModelIndex();
}
return createIndex(row, column);
}
QModelIndex UpdatedAssetsModel::parent(const QModelIndex &index) const
{
return QModelIndex();
}
int UpdatedAssetsModel::rowCount(const QModelIndex &parent) const
{
return d->assets.size();
}
}
#include "updatedassetsmodel.moc"
<|endoftext|>
|
<commit_before>#include <common/buffer.h>
#include <common/endian.h>
#include <xcodec/xcodec.h>
#include <xcodec/xcodec_cache.h>
#include <xcodec/xcodec_encoder.h>
#include <xcodec/xcodec_hash.h>
typedef std::pair<unsigned, uint64_t> offset_hash_pair_t;
struct xcodec_special_p {
bool operator() (uint8_t ch) const
{
return (XCODEC_CHAR_SPECIAL(ch));
}
};
XCodecEncoder::XCodecEncoder(XCodec *codec)
: log_("/xcodec/encoder"),
cache_(codec->cache_),
window_()
{ }
XCodecEncoder::~XCodecEncoder()
{ }
/*
* This takes a view of a data stream and turns it into a series of references
* to other data, declarations of data to be referenced, and data that needs
* escaped.
*/
void
XCodecEncoder::encode(Buffer *output, Buffer *input)
{
if (input->length() < XCODEC_SEGMENT_LENGTH) {
input->escape(XCODEC_ESCAPE_CHAR, xcodec_special_p());
output->append(input);
input->clear();
return;
}
XCodecHash<XCODEC_SEGMENT_LENGTH> xcodec_hash;
offset_hash_pair_t candidate;
bool have_candidate;
Buffer outq;
unsigned o = 0;
have_candidate = false;
while (!input->empty()) {
BufferSegment *seg;
input->moveout(&seg);
outq.append(seg);
const uint8_t *p;
for (p = seg->data(); p < seg->end(); p++) {
xcodec_hash.roll(*p);
if (++o < XCODEC_SEGMENT_LENGTH)
continue;
unsigned start = o - XCODEC_SEGMENT_LENGTH;
uint64_t hash = xcodec_hash.mix();
bool hash_collision;
BufferSegment *oseg = cache_->lookup(hash);
if (oseg != NULL) {
/*
* Before outputing this reference, if we have
* a pending declaration, we should use it.
*/
if (have_candidate && candidate.first + XCODEC_SEGMENT_LENGTH <= start) {
encode_declaration(output, &outq, candidate.first, candidate.second, NULL);
o -= candidate.first + XCODEC_SEGMENT_LENGTH;
start = o - XCODEC_SEGMENT_LENGTH;
have_candidate = false;
}
/*
* This segment already exists. If it's
* identical to this chunk of data, then that's
* positively fantastic.
*/
if (encode_reference(output, &outq, start, hash, oseg)) {
oseg->unref();
o = 0;
have_candidate = false;
continue;
}
oseg->unref();
DEBUG(log_) << "Collision in first pass.";
hash_collision = true;
/*
* Fall through to defining the previous hash if
* it is appropriate to do so.
*/
if (!have_candidate) {
/* Nothing more to do. */
continue;
}
} else {
hash_collision = false;
}
if (have_candidate) {
/*
* If there is a previous hash in the
* offset-hash map that would overlap with this
* hash, then we have no reason to remember this
* hash for later.
*/
if (candidate.first + XCODEC_SEGMENT_LENGTH > start) {
/* We might still find an alternative. */
continue;
}
ASSERT(!hash_collision);
BufferSegment *nseg;
encode_declaration(output, &outq, candidate.first, candidate.second, &nseg);
o -= candidate.first + XCODEC_SEGMENT_LENGTH;
start = o - XCODEC_SEGMENT_LENGTH;
have_candidate = false;
/*
* If this hash is the same as the has for
* the current data, then make sure that they
* are compatible before remembering the
* current hash
*/
if (!hash_collision && hash == candidate.second) {
if (!encode_reference(output, &outq, start, hash, nseg)) {
nseg->unref();
DEBUG(log_) << "Collision in adjacent-declare pass.";
continue;
}
nseg->unref();
DEBUG(log_) << "Hit in adjacent-declare pass.";
o = 0;
continue;
}
nseg->unref();
/*
* Remember the current hash.
*/
}
/*
* No collision, remember this for later.
*/
if (!hash_collision) {
ASSERT(!have_candidate);
candidate.first = start;
candidate.second = hash;
have_candidate = true;
}
}
seg->unref();
}
/*
* There's a hash we can declare, do it.
*/
if (have_candidate) {
ASSERT(!outq.empty());
encode_declaration(output, &outq, candidate.first, candidate.second, NULL);
have_candidate = false;
}
if (!outq.empty()) {
Buffer suffix(outq);
outq.clear();
suffix.escape(XCODEC_ESCAPE_CHAR, xcodec_special_p());
output->append(suffix);
outq.clear();
}
ASSERT(!have_candidate);
ASSERT(outq.empty());
ASSERT(input->empty());
}
void
XCodecEncoder::encode_declaration(Buffer *output, Buffer *input, unsigned offset, uint64_t hash, BufferSegment **segp)
{
if (offset != 0) {
Buffer prefix;
input->moveout(&prefix, 0, offset);
prefix.escape(XCODEC_ESCAPE_CHAR, xcodec_special_p());
output->append(prefix);
prefix.clear();
}
BufferSegment *nseg;
input->copyout(&nseg, XCODEC_SEGMENT_LENGTH);
cache_->enter(hash, nseg);
output->append(XCODEC_DECLARE_CHAR);
uint64_t lehash = LittleEndian::encode(hash);
output->append((const uint8_t *)&lehash, sizeof lehash);
output->append(nseg);
window_.declare(hash, nseg);
if (segp == NULL)
nseg->unref();
/*
* Skip to the end.
*/
input->skip(XCODEC_SEGMENT_LENGTH);
/*
* And output a reference.
*/
uint8_t b;
if (window_.present(hash, &b)) {
output->append(XCODEC_BACKREF_CHAR);
output->append(b);
} else {
NOTREACHED();
}
if (segp != NULL)
*segp = nseg;
}
bool
XCodecEncoder::encode_reference(Buffer *output, Buffer *input, unsigned offset, uint64_t hash, BufferSegment *oseg)
{
uint8_t data[XCODEC_SEGMENT_LENGTH];
input->copyout(data, offset, sizeof data);
if (!oseg->match(data, sizeof data))
return (false);
if (offset != 0) {
Buffer prefix;
input->moveout(&prefix, 0, offset);
prefix.escape(XCODEC_ESCAPE_CHAR, xcodec_special_p());
output->append(prefix);
prefix.clear();
}
/*
* Skip to the end.
*/
input->skip(XCODEC_SEGMENT_LENGTH);
/*
* And output a reference.
*/
uint8_t b;
if (window_.present(hash, &b)) {
output->append(XCODEC_BACKREF_CHAR);
output->append(b);
} else {
output->append(XCODEC_HASHREF_CHAR);
uint64_t lehash = LittleEndian::encode(hash);
output->append((const uint8_t *)&lehash, sizeof lehash);
window_.declare(hash, oseg);
}
return (true);
}
<commit_msg>Massive simplification of XCodecEncoder::encode() given the realizations behind the previous commit.<commit_after>#include <common/buffer.h>
#include <common/endian.h>
#include <xcodec/xcodec.h>
#include <xcodec/xcodec_cache.h>
#include <xcodec/xcodec_encoder.h>
#include <xcodec/xcodec_hash.h>
typedef std::pair<unsigned, uint64_t> offset_hash_pair_t;
struct xcodec_special_p {
bool operator() (uint8_t ch) const
{
return (XCODEC_CHAR_SPECIAL(ch));
}
};
XCodecEncoder::XCodecEncoder(XCodec *codec)
: log_("/xcodec/encoder"),
cache_(codec->cache_),
window_()
{ }
XCodecEncoder::~XCodecEncoder()
{ }
/*
* This takes a view of a data stream and turns it into a series of references
* to other data, declarations of data to be referenced, and data that needs
* escaped.
*/
void
XCodecEncoder::encode(Buffer *output, Buffer *input)
{
if (input->length() < XCODEC_SEGMENT_LENGTH) {
input->escape(XCODEC_ESCAPE_CHAR, xcodec_special_p());
output->append(input);
input->clear();
return;
}
XCodecHash<XCODEC_SEGMENT_LENGTH> xcodec_hash;
offset_hash_pair_t candidate;
bool have_candidate;
Buffer outq;
unsigned o = 0;
have_candidate = false;
while (!input->empty()) {
BufferSegment *seg;
input->moveout(&seg);
outq.append(seg);
const uint8_t *p;
for (p = seg->data(); p < seg->end(); p++) {
xcodec_hash.roll(*p);
if (++o < XCODEC_SEGMENT_LENGTH)
continue;
unsigned start = o - XCODEC_SEGMENT_LENGTH;
uint64_t hash = xcodec_hash.mix();
/*
* If there is a pending candidate hash that wouldn't
* overlap with tis one, declare it now.
*/
if (have_candidate && candidate.first + XCODEC_SEGMENT_LENGTH <= start) {
BufferSegment *nseg;
encode_declaration(output, &outq, candidate.first, candidate.second, &nseg);
o -= candidate.first + XCODEC_SEGMENT_LENGTH;
start = o - XCODEC_SEGMENT_LENGTH;
have_candidate = false;
/*
* If, on top of that, the just-declared hash is
* the same as the current hash, consider referencing
* it immediately.
*/
if (hash == candidate.second) {
if (!encode_reference(output, &outq, start, hash, nseg)) {
nseg->unref();
DEBUG(log_) << "Collision in adjacent-declare pass.";
continue;
}
nseg->unref();
o = 0;
DEBUG(log_) << "Hit in adjacent-declare pass.";
continue;
}
nseg->unref();
}
/*
* Now attempt to encode this hash as a reference if it
* has been defined before.
*/
BufferSegment *oseg = cache_->lookup(hash);
if (oseg != NULL) {
/*
* This segment already exists. If it's
* identical to this chunk of data, then that's
* positively fantastic.
*/
if (encode_reference(output, &outq, start, hash, oseg)) {
oseg->unref();
o = 0;
have_candidate = false;
continue;
}
oseg->unref();
DEBUG(log_) << "Collision in first pass.";
continue;
}
/*
* Not defined before, it's a candidate for declaration if
* we don't already have one.
*/
if (have_candidate) {
ASSERT(candidate.first + XCODEC_SEGMENT_LENGTH > start);
continue;
}
candidate.first = start;
candidate.second = hash;
have_candidate = true;
}
seg->unref();
}
/*
* There's a hash we can declare, do it.
*/
if (have_candidate) {
ASSERT(!outq.empty());
encode_declaration(output, &outq, candidate.first, candidate.second, NULL);
have_candidate = false;
}
if (!outq.empty()) {
Buffer suffix(outq);
outq.clear();
suffix.escape(XCODEC_ESCAPE_CHAR, xcodec_special_p());
output->append(suffix);
outq.clear();
}
ASSERT(!have_candidate);
ASSERT(outq.empty());
ASSERT(input->empty());
}
void
XCodecEncoder::encode_declaration(Buffer *output, Buffer *input, unsigned offset, uint64_t hash, BufferSegment **segp)
{
if (offset != 0) {
Buffer prefix;
input->moveout(&prefix, 0, offset);
prefix.escape(XCODEC_ESCAPE_CHAR, xcodec_special_p());
output->append(prefix);
prefix.clear();
}
BufferSegment *nseg;
input->copyout(&nseg, XCODEC_SEGMENT_LENGTH);
cache_->enter(hash, nseg);
output->append(XCODEC_DECLARE_CHAR);
uint64_t lehash = LittleEndian::encode(hash);
output->append((const uint8_t *)&lehash, sizeof lehash);
output->append(nseg);
window_.declare(hash, nseg);
if (segp == NULL)
nseg->unref();
/*
* Skip to the end.
*/
input->skip(XCODEC_SEGMENT_LENGTH);
/*
* And output a reference.
*/
uint8_t b;
if (window_.present(hash, &b)) {
output->append(XCODEC_BACKREF_CHAR);
output->append(b);
} else {
NOTREACHED();
}
if (segp != NULL)
*segp = nseg;
}
bool
XCodecEncoder::encode_reference(Buffer *output, Buffer *input, unsigned offset, uint64_t hash, BufferSegment *oseg)
{
uint8_t data[XCODEC_SEGMENT_LENGTH];
input->copyout(data, offset, sizeof data);
if (!oseg->match(data, sizeof data))
return (false);
if (offset != 0) {
Buffer prefix;
input->moveout(&prefix, 0, offset);
prefix.escape(XCODEC_ESCAPE_CHAR, xcodec_special_p());
output->append(prefix);
prefix.clear();
}
/*
* Skip to the end.
*/
input->skip(XCODEC_SEGMENT_LENGTH);
/*
* And output a reference.
*/
uint8_t b;
if (window_.present(hash, &b)) {
output->append(XCODEC_BACKREF_CHAR);
output->append(b);
} else {
output->append(XCODEC_HASHREF_CHAR);
uint64_t lehash = LittleEndian::encode(hash);
output->append((const uint8_t *)&lehash, sizeof lehash);
window_.declare(hash, oseg);
}
return (true);
}
<|endoftext|>
|
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2012, 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 Willow Garage, Inc. 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.
*
* $Id$
*
*/
#include "pcl/recognition/ransac_based/model_library.h"
using namespace std;
//============================================================================================================================================
bool
pcl::recognition::ModelLibrary::addModel(const PointCloudIn& /*model*/, const PointCloudN& /*normals*/, const std::string& object_name)
{
// Try to insert a new model entry
pair<map<string,Entry*>::iterator, bool> result = model_entries_.insert(pair<string,Entry*>(object_name, NULL));
// Check if 'object_name' is unique
if ( !result.second )
return false;
// Entry* new_entry = new Entry(object_name);
return true;
}
//============================================================================================================================================
<commit_msg>fixed a compilation error on windows; for some reason 'NULL' needs to be explicitly casted to the pointer type<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2012, 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 Willow Garage, Inc. 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.
*
* $Id$
*
*/
#include "pcl/recognition/ransac_based/model_library.h"
using namespace std;
//============================================================================================================================================
bool
pcl::recognition::ModelLibrary::addModel(const PointCloudIn& /*model*/, const PointCloudN& /*normals*/, const std::string& object_name)
{
// Try to insert a new model entry
pair<map<string,Entry*>::iterator, bool> result = model_entries_.insert(pair<string,Entry*>(object_name, reinterpret_cast<Entry*> (NULL)));
// Check if 'object_name' is unique
if ( !result.second )
return false;
// Entry* new_entry = new Entry(object_name);
return true;
}
//============================================================================================================================================
<|endoftext|>
|
<commit_before>// $Id: anisotropyShiftProcessor.C,v 1.9 2001/12/30 13:28:52 sturm Exp $
#include <BALL/NMR/anisotropyShiftProcessor.h>
#include <BALL/KERNEL/atom.h>
#include <BALL/KERNEL/PTE.h>
#include <BALL/FORMAT/parameterSection.h>
#include <BALL/DATATYPE/string.h>
using namespace std;
namespace BALL
{
const char* AnisotropyShiftProcessor::PROPERTY__ANISOTROPY_SHIFT = "AnisotropyShift";
AnisotropyShiftProcessor::AnisotropyShiftProcessor()
throw()
: ignore_other_chain_(false)
{
}
AnisotropyShiftProcessor::~AnisotropyShiftProcessor()
throw()
{
}
void AnisotropyShiftProcessor::init()
throw()
{
valid_ = false;
if (parameters_ == 0)
{
return;
}
ParameterSection parameter_section;
parameter_section.extractSection(*parameters_, "Anisotropy");
if (parameter_section.options.has("ignore_other_chain"))
{
ignore_other_chain_ = parameter_section.options.getBool("ignore_other_chain");
}
valid_ = true;
}
bool AnisotropyShiftProcessor::finish()
throw()
{
if (!isValid())
{
return false;
}
if (proton_list_.size() == 0)
{
return true;
}
const float dX1 = -13.0;
const float dX2 = -4.0;
const float dXN1 = -11.0;
const float dXN2 = -5.0;
const float ndX1 = -11.0;
const float ndX2 = 1.4;
const float ndXN1 = -7.0;
const float ndXN2 = 1.0;
list<const Atom*>::iterator proton_iter;
list<const Bond*>::iterator eff_iter;
// Iteriere ber alle Protonen in proton_list_
for (proton_iter = proton_list_.begin(); proton_iter != proton_list_.end(); ++proton_iter)
{
float gs = 0;
for (eff_iter = eff_list_.begin(); eff_iter != eff_list_.end(); ++eff_iter)
{
// Fr jedes Proton iteriere ber alle Effektorbindungen in eff_list_
const Atom* patom = *proton_iter;
const Bond* bond = *eff_iter;
const Atom* c_atom = bond->getFirstAtom();
const Atom* o_atom = bond->getSecondAtom();
if (c_atom->getElement() != PTE[Element::C])
{
o_atom = bond->getFirstAtom();
c_atom = bond->getSecondAtom();
}
const Atom* x_atom = 0;
if ((*proton_iter)->getFragment() != c_atom->getFragment())
{
String name = c_atom->getName();
if (name == "C")
{
name = "CA";
}
else
{
if (name == "CG")
{
name = "CB";
}
else
{
if (name == "CD")
{
name = "CG";
}
}
}
for (Position pos = 0; pos < c_atom->countBonds(); pos++)
{
const Bond& hbond = *c_atom->getBond(pos);
if (hbond.getBoundAtom(*c_atom)->getName() == name)
{
x_atom = hbond.getBoundAtom(*c_atom);
break;
}
}
for (Position pos = 0; (x_atom == 0) && (pos < o_atom->countBonds()); pos++)
{
const Bond& hbond = *o_atom->getBond(pos);
if (hbond.getBoundAtom(*o_atom)->getName() == name)
{
x_atom = hbond.getBoundAtom(*o_atom);
break;
}
}
// was passiert wenn x_atom nicht gesetzt ???
if ((c_atom == 0) || (o_atom == 0) || (x_atom == 0))
{
Log.error() << "Could not set all atoms in ASP! c_atom = " << c_atom << " o_atom = " << o_atom << " x_atom = " << x_atom << endl;
Log.error() << "c_atom->getName() = "<< c_atom->getFullName() << " o_atom->getName() = " << o_atom->getFullName() << endl;
continue;
}
else
{
const Vector3& c_pos = c_atom->getPosition();
const Vector3& o_pos = o_atom->getPosition();
const Vector3& x_pos = x_atom->getPosition();
// baue rechtwinkliges Koordinatensystem auf :
Vector3 vz = o_pos - c_pos;
vz /= vz.getLength();
Vector3 vy = vz % (x_pos - c_pos);
vy /= vy.getLength();
Vector3 vx = vz % vy;
vx /= vx.getLength();
const Vector3 cen = c_pos + (vz * 1.1);
const Vector3 v1 = patom->getPosition() - cen;
const Vector3 v2 = v1 % vy;
const Vector3 v3 = v2 % vx;
const float& distance = v1.getLength();
const float stheta = v2.getLength() / (v1.getLength() * vy.getLength());
const float sgamma = v3.getLength() / (v2.getLength() * vx.getLength());
float calc1, calc2;
if ((*proton_iter)->getName() == "H")
{
calc1 = dXN1 * ((3.0 * stheta * stheta) - 2.0);
calc2 = dXN2 * (1.0 - (3.0 * stheta * stheta * sgamma * sgamma));
}
else
{
calc1 = dX1 * ((3.0 * stheta * stheta) - 2.0);
calc2 = dX2 * (1.0 - (3.0 * stheta * stheta * sgamma * sgamma));
}
float shift = (calc1 + calc2) / (3.0 * distance * distance * distance);
// ?????
// check whether effector and nucleus are in the same chain
if ((ignore_other_chain_) && ((*proton_iter)->getResidue() != 0) && (c_atom->getResidue() != 0))
{
if ((*proton_iter)->getResidue()->getChain() == c_atom->getResidue()->getChain())
{
shift = 0.0;
}
}
gs += shift;
}
}
}
for (eff_iter = eff_list_2_.begin(); eff_iter != eff_list_2_.end(); ++eff_iter)
{
const Atom* patom = *proton_iter;
const Bond* bond = *eff_iter;
const Atom* c_atom = bond->getFirstAtom();
const Atom* n_atom = bond->getSecondAtom();
if (c_atom->getElement() != PTE[Element::C])
{
n_atom = bond->getFirstAtom();
c_atom = bond->getSecondAtom();
}
const Atom* o_atom = 0;
// skip the H atom of this residue
if ((*proton_iter)->getName() == "H" && (*proton_iter)->getFragment() == n_atom->getFragment())
{
continue;
}
for (Position pos = 0; pos < c_atom->countBonds(); pos++)
{
const Bond& hbond = *c_atom->getBond(pos);
if (hbond.getBoundAtom(*c_atom)->getName() == "O")
{
o_atom = hbond.getBoundAtom(*c_atom);
break;
}
}
if (o_atom != 0)
{
Vector3 c_pos = c_atom->getPosition();
Vector3 o_pos = o_atom->getPosition();
Vector3 n_pos = n_atom->getPosition();
// baue rechtwinkliges Koordinatensystem auf
Vector3 vz = n_pos - c_pos;
const float vz_scalar = vz.getLength();
vz.normalize();
Vector3 vy = vz % (o_pos - c_pos);
vy.normalize();
Vector3 vx = vz % vy;
vx.normalize();
const Vector3 cen = c_pos + (vz * (0.85 * vz_scalar));
const Vector3 v1 = patom->getPosition() - cen;
const Vector3 v2 = v1 % vy;
const Vector3 v3 = v2 % vx;
const float& distance = v1.getLength();
const float stheta = v2.getLength() / (v1.getLength() * vy.getLength());
const float sgamma = v3.getLength() / (v2.getLength() * vx.getLength());
float calc1, calc2;
if ((*proton_iter)->getName() == "H")
{
calc1 = ndXN1 * ((3.0 * stheta * stheta) - 2.0);
calc2 = ndXN2 * (1.0 - (3.0 * stheta * stheta * sgamma * sgamma));
}
else
{
calc1 = ndX1 * ((3.0 * stheta * stheta) - 2.0);
calc2 = ndX2 * (1.0 - (3.0 * stheta * stheta * sgamma * sgamma));
}
// ?????
float shift = (calc1 + calc2) / (3.0 * distance * distance * distance);
// check whether effector and nucleus are in the same chain
if (ignore_other_chain_ && ((*proton_iter)->getResidue() != 0) && (c_atom->getResidue() != 0))
{
if ((*proton_iter)->getResidue()->getChain() == c_atom->getResidue()->getChain())
{
shift = 0.0;
}
}
gs += shift;
}
else
{
Log.error() << "O atom not found for " << c_atom->getFullName() << "-" << n_atom->getFullName() << endl;
}
}
float shift = (*proton_iter)->getProperty(ShiftModule::PROPERTY__SHIFT).getFloat();
shift -= gs;
(const_cast<Atom*>(*proton_iter))->setProperty(ShiftModule::PROPERTY__SHIFT, shift);
(const_cast<Atom*>(*proton_iter))->setProperty(PROPERTY__ANISOTROPY_SHIFT, -gs);
}
return true;
}
Processor::Result AnisotropyShiftProcessor::operator () (Composite& composite)
throw()
{
// hier werden alle Effektorbindungen gesammelt( C=O ) und in eff_list_ gespeichert.
// hier werden alle Wasserstoffe in proton_list_ gespeichert.
if (!RTTI::isKindOf<Atom>(composite))
{
return Processor::CONTINUE;
}
const Atom* patom = RTTI::castTo<Atom>(composite);
if (patom->getElement() == PTE[Element::H])
{
proton_list_.push_back(patom);
return Processor::CONTINUE;
}
if (patom->getElement() != PTE[Element::C])
{
return Processor::CONTINUE;
}
// suche im Backbone
if (patom->getName() == "C" && patom->isBound())
{
bool foundN = false;
bool foundO = false;
Position bondN = 0;
// laufe alle Bindungen des Atoms durch und suche nach Sauerstoff-Doppelbindung
for (Position pos = 0; pos < patom->countBonds(); pos++)
{
const Bond* bond = patom->getBond(pos);
if ((bond->getBoundAtom(*patom)->getName()) == "N")
{
foundN = true;
bondN = pos;
}
if ((bond->getBoundAtom(*patom)->getName()) == "O")
{
foundO = true;
eff_list_.push_back(bond);
}
}
if (foundN && foundO)
{
eff_list_2_.push_back(patom->getBond(bondN));
}
return Processor::CONTINUE;
}
// suche in der Seitenkette nach ASP ASN GLU GLN
const String& residue_name = patom->getFragment()->getName();
if ((residue_name == "ASP" || residue_name == "ASN") &&
patom->getName() == "CG" && patom->isBound() )
{
// laufe alle Bindungen des Atoms durch und suche nach Sauerstoff-Doppelbindung
for (Position pos = 0; pos < patom->countBonds(); pos++)
{
const Bond* bond = patom->getBond(pos);
if (bond->getBoundAtom(*patom)->getElement() == PTE[Element::O] &&
bond->getBoundAtom(*patom)->getName() == "OD1")
{
eff_list_.push_back(bond);
}
}
return Processor::CONTINUE;
}
if ((residue_name == "GLU" || residue_name == "GLN") &&
patom->getName() == "CD" && patom->isBound() )
{
// laufe alle Bindungen des Atoms durch und suche nach Sauerstoff-Doppelbindung
for (Position pos = 0; pos < patom->countBonds(); pos++)
{
const Bond* bond = patom->getBond(pos);
if (bond->getBoundAtom(*patom)->getElement() == PTE[Element::O] &&
bond->getBoundAtom(*patom)->getName() == "OE1" )
{
eff_list_.push_back(bond);
}
}
}
return Processor::CONTINUE;
}
} // namespace BALL
<commit_msg>added: copy ctor<commit_after>// $Id: anisotropyShiftProcessor.C,v 1.10 2002/01/10 01:32:29 oliver Exp $
#include <BALL/NMR/anisotropyShiftProcessor.h>
#include <BALL/KERNEL/atom.h>
#include <BALL/KERNEL/PTE.h>
#include <BALL/FORMAT/parameterSection.h>
#include <BALL/DATATYPE/string.h>
using namespace std;
namespace BALL
{
const char* AnisotropyShiftProcessor::PROPERTY__ANISOTROPY_SHIFT = "AnisotropyShift";
AnisotropyShiftProcessor::AnisotropyShiftProcessor()
throw()
: ShiftModule(),
proton_list_(),
eff_list_(),
eff_list_2_(),
ignore_other_chain_(false)
{
}
AnisotropyShiftProcessor::AnisotropyShiftProcessor(const AnisotropyShiftProcessor& processor)
throw()
: ShiftModule(processor),
proton_list_(processor.proton_list_),
eff_list_(processor.eff_list_),
eff_list_2_(processor.eff_list_2_),
ignore_other_chain_(processor.ignore_other_chain_)
{
}
AnisotropyShiftProcessor::~AnisotropyShiftProcessor()
throw()
{
}
void AnisotropyShiftProcessor::init()
throw()
{
valid_ = false;
if (parameters_ == 0)
{
return;
}
ParameterSection parameter_section;
parameter_section.extractSection(*parameters_, "Anisotropy");
if (parameter_section.options.has("ignore_other_chain"))
{
ignore_other_chain_ = parameter_section.options.getBool("ignore_other_chain");
}
valid_ = true;
}
bool AnisotropyShiftProcessor::finish()
throw()
{
if (!isValid())
{
return false;
}
if (proton_list_.size() == 0)
{
return true;
}
const float dX1 = -13.0;
const float dX2 = -4.0;
const float dXN1 = -11.0;
const float dXN2 = -5.0;
const float ndX1 = -11.0;
const float ndX2 = 1.4;
const float ndXN1 = -7.0;
const float ndXN2 = 1.0;
list<const Atom*>::iterator proton_iter;
list<const Bond*>::iterator eff_iter;
// Iteriere ber alle Protonen in proton_list_
for (proton_iter = proton_list_.begin(); proton_iter != proton_list_.end(); ++proton_iter)
{
float gs = 0;
for (eff_iter = eff_list_.begin(); eff_iter != eff_list_.end(); ++eff_iter)
{
// Fr jedes Proton iteriere ber alle Effektorbindungen in eff_list_
const Atom* patom = *proton_iter;
const Bond* bond = *eff_iter;
const Atom* c_atom = bond->getFirstAtom();
const Atom* o_atom = bond->getSecondAtom();
if (c_atom->getElement() != PTE[Element::C])
{
o_atom = bond->getFirstAtom();
c_atom = bond->getSecondAtom();
}
const Atom* x_atom = 0;
if ((*proton_iter)->getFragment() != c_atom->getFragment())
{
String name = c_atom->getName();
if (name == "C")
{
name = "CA";
}
else
{
if (name == "CG")
{
name = "CB";
}
else
{
if (name == "CD")
{
name = "CG";
}
}
}
for (Position pos = 0; pos < c_atom->countBonds(); pos++)
{
const Bond& hbond = *c_atom->getBond(pos);
if (hbond.getBoundAtom(*c_atom)->getName() == name)
{
x_atom = hbond.getBoundAtom(*c_atom);
break;
}
}
for (Position pos = 0; (x_atom == 0) && (pos < o_atom->countBonds()); pos++)
{
const Bond& hbond = *o_atom->getBond(pos);
if (hbond.getBoundAtom(*o_atom)->getName() == name)
{
x_atom = hbond.getBoundAtom(*o_atom);
break;
}
}
// was passiert wenn x_atom nicht gesetzt ???
if ((c_atom == 0) || (o_atom == 0) || (x_atom == 0))
{
Log.error() << "Could not set all atoms in ASP! c_atom = " << c_atom << " o_atom = " << o_atom << " x_atom = " << x_atom << endl;
Log.error() << "c_atom->getName() = "<< c_atom->getFullName() << " o_atom->getName() = " << o_atom->getFullName() << endl;
continue;
}
else
{
const Vector3& c_pos = c_atom->getPosition();
const Vector3& o_pos = o_atom->getPosition();
const Vector3& x_pos = x_atom->getPosition();
// baue rechtwinkliges Koordinatensystem auf :
Vector3 vz = o_pos - c_pos;
vz /= vz.getLength();
Vector3 vy = vz % (x_pos - c_pos);
vy /= vy.getLength();
Vector3 vx = vz % vy;
vx /= vx.getLength();
const Vector3 cen = c_pos + (vz * 1.1);
const Vector3 v1 = patom->getPosition() - cen;
const Vector3 v2 = v1 % vy;
const Vector3 v3 = v2 % vx;
const float& distance = v1.getLength();
const float stheta = v2.getLength() / (v1.getLength() * vy.getLength());
const float sgamma = v3.getLength() / (v2.getLength() * vx.getLength());
float calc1, calc2;
if ((*proton_iter)->getName() == "H")
{
calc1 = dXN1 * ((3.0 * stheta * stheta) - 2.0);
calc2 = dXN2 * (1.0 - (3.0 * stheta * stheta * sgamma * sgamma));
}
else
{
calc1 = dX1 * ((3.0 * stheta * stheta) - 2.0);
calc2 = dX2 * (1.0 - (3.0 * stheta * stheta * sgamma * sgamma));
}
float shift = (calc1 + calc2) / (3.0 * distance * distance * distance);
// ?????
// check whether effector and nucleus are in the same chain
if ((ignore_other_chain_) && ((*proton_iter)->getResidue() != 0) && (c_atom->getResidue() != 0))
{
if ((*proton_iter)->getResidue()->getChain() == c_atom->getResidue()->getChain())
{
shift = 0.0;
}
}
gs += shift;
}
}
}
for (eff_iter = eff_list_2_.begin(); eff_iter != eff_list_2_.end(); ++eff_iter)
{
const Atom* patom = *proton_iter;
const Bond* bond = *eff_iter;
const Atom* c_atom = bond->getFirstAtom();
const Atom* n_atom = bond->getSecondAtom();
if (c_atom->getElement() != PTE[Element::C])
{
n_atom = bond->getFirstAtom();
c_atom = bond->getSecondAtom();
}
const Atom* o_atom = 0;
// skip the H atom of this residue
if ((*proton_iter)->getName() == "H" && (*proton_iter)->getFragment() == n_atom->getFragment())
{
continue;
}
for (Position pos = 0; pos < c_atom->countBonds(); pos++)
{
const Bond& hbond = *c_atom->getBond(pos);
if (hbond.getBoundAtom(*c_atom)->getName() == "O")
{
o_atom = hbond.getBoundAtom(*c_atom);
break;
}
}
if (o_atom != 0)
{
Vector3 c_pos = c_atom->getPosition();
Vector3 o_pos = o_atom->getPosition();
Vector3 n_pos = n_atom->getPosition();
// baue rechtwinkliges Koordinatensystem auf
Vector3 vz = n_pos - c_pos;
const float vz_scalar = vz.getLength();
vz.normalize();
Vector3 vy = vz % (o_pos - c_pos);
vy.normalize();
Vector3 vx = vz % vy;
vx.normalize();
const Vector3 cen = c_pos + (vz * (0.85 * vz_scalar));
const Vector3 v1 = patom->getPosition() - cen;
const Vector3 v2 = v1 % vy;
const Vector3 v3 = v2 % vx;
const float& distance = v1.getLength();
const float stheta = v2.getLength() / (v1.getLength() * vy.getLength());
const float sgamma = v3.getLength() / (v2.getLength() * vx.getLength());
float calc1, calc2;
if ((*proton_iter)->getName() == "H")
{
calc1 = ndXN1 * ((3.0 * stheta * stheta) - 2.0);
calc2 = ndXN2 * (1.0 - (3.0 * stheta * stheta * sgamma * sgamma));
}
else
{
calc1 = ndX1 * ((3.0 * stheta * stheta) - 2.0);
calc2 = ndX2 * (1.0 - (3.0 * stheta * stheta * sgamma * sgamma));
}
// ?????
float shift = (calc1 + calc2) / (3.0 * distance * distance * distance);
// check whether effector and nucleus are in the same chain
if (ignore_other_chain_ && ((*proton_iter)->getResidue() != 0) && (c_atom->getResidue() != 0))
{
if ((*proton_iter)->getResidue()->getChain() == c_atom->getResidue()->getChain())
{
shift = 0.0;
}
}
gs += shift;
}
else
{
Log.error() << "O atom not found for " << c_atom->getFullName() << "-" << n_atom->getFullName() << endl;
}
}
float shift = (*proton_iter)->getProperty(ShiftModule::PROPERTY__SHIFT).getFloat();
shift -= gs;
(const_cast<Atom*>(*proton_iter))->setProperty(ShiftModule::PROPERTY__SHIFT, shift);
(const_cast<Atom*>(*proton_iter))->setProperty(PROPERTY__ANISOTROPY_SHIFT, -gs);
}
return true;
}
Processor::Result AnisotropyShiftProcessor::operator () (Composite& composite)
throw()
{
// hier werden alle Effektorbindungen gesammelt( C=O ) und in eff_list_ gespeichert.
// hier werden alle Wasserstoffe in proton_list_ gespeichert.
if (!RTTI::isKindOf<Atom>(composite))
{
return Processor::CONTINUE;
}
const Atom* patom = RTTI::castTo<Atom>(composite);
if (patom->getElement() == PTE[Element::H])
{
proton_list_.push_back(patom);
return Processor::CONTINUE;
}
if (patom->getElement() != PTE[Element::C])
{
return Processor::CONTINUE;
}
// suche im Backbone
if (patom->getName() == "C" && patom->isBound())
{
bool foundN = false;
bool foundO = false;
Position bondN = 0;
// laufe alle Bindungen des Atoms durch und suche nach Sauerstoff-Doppelbindung
for (Position pos = 0; pos < patom->countBonds(); pos++)
{
const Bond* bond = patom->getBond(pos);
if ((bond->getBoundAtom(*patom)->getName()) == "N")
{
foundN = true;
bondN = pos;
}
if ((bond->getBoundAtom(*patom)->getName()) == "O")
{
foundO = true;
eff_list_.push_back(bond);
}
}
if (foundN && foundO)
{
eff_list_2_.push_back(patom->getBond(bondN));
}
return Processor::CONTINUE;
}
// suche in der Seitenkette nach ASP ASN GLU GLN
const String& residue_name = patom->getFragment()->getName();
if ((residue_name == "ASP" || residue_name == "ASN") &&
patom->getName() == "CG" && patom->isBound() )
{
// laufe alle Bindungen des Atoms durch und suche nach Sauerstoff-Doppelbindung
for (Position pos = 0; pos < patom->countBonds(); pos++)
{
const Bond* bond = patom->getBond(pos);
if (bond->getBoundAtom(*patom)->getElement() == PTE[Element::O] &&
bond->getBoundAtom(*patom)->getName() == "OD1")
{
eff_list_.push_back(bond);
}
}
return Processor::CONTINUE;
}
if ((residue_name == "GLU" || residue_name == "GLN") &&
patom->getName() == "CD" && patom->isBound() )
{
// laufe alle Bindungen des Atoms durch und suche nach Sauerstoff-Doppelbindung
for (Position pos = 0; pos < patom->countBonds(); pos++)
{
const Bond* bond = patom->getBond(pos);
if (bond->getBoundAtom(*patom)->getElement() == PTE[Element::O] &&
bond->getBoundAtom(*patom)->getName() == "OE1" )
{
eff_list_.push_back(bond);
}
}
}
return Processor::CONTINUE;
}
} // namespace BALL
<|endoftext|>
|
<commit_before>
#include <cpplocate/cpplocate.h>
#include <cstdlib>
#include <vector>
#include <string>
#if defined SYSTEM_LINUX
#include <unistd.h>
#include <limits.h>
#elif defined SYSTEM_WINDOWS
#include <stdlib.h>
#elif defined SYSTEM_SOLARIS
#include <stdlib.h>
#include <limits.h>
#elif defined SYSTEM_DARWIN
#include <mach-o/dyld.h>
#elif defined SYSTEM_FREEBSD
#include <sys/types.h>
#include <sys/sysctl.h>
#endif
#include <cpplocate/utils.h>
#ifdef SYSTEM_WINDOWS
static const std::string pathDelim = "\\";
#else
static const std::string pathDelim = "/";
#endif
namespace cpplocate
{
std::string getExecutablePath()
{
#if defined SYSTEM_LINUX
char exePath[PATH_MAX];
ssize_t len = ::readlink("/proc/self/exe", exePath, sizeof(exePath));
if (len == -1 || len == sizeof(exePath)) {
len = 0;
}
exePath[len] = '\0';
#elif defined SYSTEM_WINDOWS
char * exePath;
if (_get_pgmptr(&exePath) != 0) {
exePath = "";
}
#elif defined SYSTEM_SOLARIS
char exePath[PATH_MAX];
if (realpath(getexecname(), exePath) == nullptr) {
exePath[0] = '\0';
}
#elif defined SYSTEM_DARWIN
char exePath[PATH_MAX];
uint32_t len = sizeof(exePath);
if (_NSGetExecutablePath(exePath, &len) == 0) {
char * realPath = realpath(exePath, nullptr);
if (realPath) {
strncpy(exePath, realPath, len);
free(realPath);
}
} else {
exePath[0] = '\0';
}
#elif defined SYSTEM_FREEBSD
char exePath[2048];
size_t len = sizeof(exePath);
int mib[4];
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PATHNAME;
mib[3] = -1;
if (sysctl(mib, 4, exePath, &len, nullptr, 0) != 0) {
exePath[0] = '\0';
}
#else
char * exePath = "";
#endif
return std::string(exePath);
}
std::string getModulePath()
{
return utils::getDirectoryPath(getExecutablePath());
}
ModuleInfo findModule(const std::string & name)
{
ModuleInfo info;
// Search at current module location
if (utils::loadModule(getModulePath(), name, info))
{
return info;
}
// Search all paths in CPPLOCATE_PATH
std::vector<std::string> paths;
std::string cppLocatePath = utils::getEnv("CPPLOCATE_PATH");
utils::getPaths(cppLocatePath, paths);
for (std::string path : paths)
{
if (utils::loadModule(path, name, info))
{
return info;
}
if (utils::loadModule(utils::trimPath(path) + pathDelim + name, name, info))
{
return info;
}
}
// Search in standard locations
#if defined SYSTEM_WINDOWS
std::string programFiles64 = getEnv("programfiles");
std::string programFiles32 = getEnv("programfiles(x86)");
if (utils::loadModule(programFiles64 + "\\" + name, name, info))
{
return info;
}
if (utils::loadModule(programFiles32 + "\\" + name, name, info))
{
return info;
}
#else
if (utils::loadModule("/usr/share/" + name, name, info))
{
return info;
}
if (utils::loadModule("/usr/local/share/" + name, name, info))
{
return info;
}
#endif
// Not found
return ModuleInfo();
}
} // namespace cpplocate
<commit_msg>Fix Windows build<commit_after>
#include <cpplocate/cpplocate.h>
#include <cstdlib>
#include <vector>
#include <string>
#if defined SYSTEM_LINUX
#include <unistd.h>
#include <limits.h>
#elif defined SYSTEM_WINDOWS
#include <stdlib.h>
#elif defined SYSTEM_SOLARIS
#include <stdlib.h>
#include <limits.h>
#elif defined SYSTEM_DARWIN
#include <mach-o/dyld.h>
#elif defined SYSTEM_FREEBSD
#include <sys/types.h>
#include <sys/sysctl.h>
#endif
#include <cpplocate/utils.h>
#ifdef SYSTEM_WINDOWS
static const std::string pathDelim = "\\";
#else
static const std::string pathDelim = "/";
#endif
namespace cpplocate
{
std::string getExecutablePath()
{
#if defined SYSTEM_LINUX
char exePath[PATH_MAX];
ssize_t len = ::readlink("/proc/self/exe", exePath, sizeof(exePath));
if (len == -1 || len == sizeof(exePath)) {
len = 0;
}
exePath[len] = '\0';
#elif defined SYSTEM_WINDOWS
char * exePath;
if (_get_pgmptr(&exePath) != 0) {
exePath = "";
}
#elif defined SYSTEM_SOLARIS
char exePath[PATH_MAX];
if (realpath(getexecname(), exePath) == nullptr) {
exePath[0] = '\0';
}
#elif defined SYSTEM_DARWIN
char exePath[PATH_MAX];
uint32_t len = sizeof(exePath);
if (_NSGetExecutablePath(exePath, &len) == 0) {
char * realPath = realpath(exePath, nullptr);
if (realPath) {
strncpy(exePath, realPath, len);
free(realPath);
}
} else {
exePath[0] = '\0';
}
#elif defined SYSTEM_FREEBSD
char exePath[2048];
size_t len = sizeof(exePath);
int mib[4];
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PATHNAME;
mib[3] = -1;
if (sysctl(mib, 4, exePath, &len, nullptr, 0) != 0) {
exePath[0] = '\0';
}
#else
char * exePath = "";
#endif
return std::string(exePath);
}
std::string getModulePath()
{
return utils::getDirectoryPath(getExecutablePath());
}
ModuleInfo findModule(const std::string & name)
{
ModuleInfo info;
// Search at current module location
if (utils::loadModule(getModulePath(), name, info))
{
return info;
}
// Search all paths in CPPLOCATE_PATH
std::vector<std::string> paths;
std::string cppLocatePath = utils::getEnv("CPPLOCATE_PATH");
utils::getPaths(cppLocatePath, paths);
for (std::string path : paths)
{
if (utils::loadModule(path, name, info))
{
return info;
}
if (utils::loadModule(utils::trimPath(path) + pathDelim + name, name, info))
{
return info;
}
}
// Search in standard locations
#if defined SYSTEM_WINDOWS
std::string programFiles64 = utils::getEnv("programfiles");
std::string programFiles32 = utils::getEnv("programfiles(x86)");
if (utils::loadModule(programFiles64 + "\\" + name, name, info))
{
return info;
}
if (utils::loadModule(programFiles32 + "\\" + name, name, info))
{
return info;
}
#else
if (utils::loadModule("/usr/share/" + name, name, info))
{
return info;
}
if (utils::loadModule("/usr/local/share/" + name, name, info))
{
return info;
}
#endif
// Not found
return ModuleInfo();
}
} // namespace cpplocate
<|endoftext|>
|
<commit_before>/*
PubSubClient.cpp - A simple client for MQTT.
Nicholas O'Leary
http://knolleary.net
*/
#include "WConstants.h"
#include "PubSubClient.h"
#include "Client.h"
#include "string.h"
#define MQTTCONNECT 1<<4
#define MQTTPUBLISH 3<<4
#define MQTTSUBSCRIBE 8<<4
PubSubClient::PubSubClient(uint8_t *ip, uint16_t port, void (*callback)(char*,uint8_t*,int)) : _client(ip,port) {
this->callback = callback;
}
int PubSubClient::connect(char *id) {
return connect(id,0,0,0,0);
}
int PubSubClient::connect(char *id, char* willTopic, uint8_t willQos, uint8_t willRetain, char* willMessage) {
if (!_client.connected()) {
if (_client.connect()) {
nextMsgId = 1;
uint8_t d[9] = {0x00,0x06,0x4d,0x51,0x49,0x73,0x64,0x70,0x03};
uint8_t length = 0;
int j;
for (j = 0;j<9;j++) {
buffer[length++] = d[j];
}
if (willTopic) {
buffer[length++] = 0x06|(willQos<<3)|(willRetain<<5);
} else {
buffer[length++] = 0x02;
}
buffer[length++] = 0;
buffer[length++] = (KEEPALIVE/500);
length = writeString(id,buffer,length);
if (willTopic) {
length = writeString(willTopic,buffer,length);
length = writeString(willMessage,buffer,length);
}
write(MQTTCONNECT,buffer,length);
while (!_client.available()) {}
uint8_t len = readPacket();
if (len == 4 && buffer[3] == 0) {
lastActivity = millis();
return 1;
}
_client.stop();
}
}
return 0;
}
uint8_t PubSubClient::readPacket() {
uint8_t len = 0;
buffer[len++] = _client.read();
uint8_t multiplier = 1;
uint8_t length = 0;
uint8_t digit = 0;
do {
digit = _client.read();
buffer[len++] = digit;
length += (digit & 127) * multiplier;
multiplier *= 128;
} while ((digit & 128) != 0);
for (int i = 0;i<length;i++)
{
if (len < MAX_PACKET_SIZE) {
buffer[len++] = _client.read();
} else {
_client.read();
len = 0; // This will cause the packet to be ignored.
}
}
return len;
}
int PubSubClient::loop() {
if (_client.connected()) {
long t = millis();
if (t - lastActivity > KEEPALIVE) {
_client.write(192);
_client.write((uint8_t)0);
lastActivity = t;
}
if (_client.available()) {
uint8_t len = readPacket();
if (len > 0) {
uint8_t type = buffer[0]>>4;
if (type == 3) { // PUBLISH
if (callback) {
uint8_t tl = (buffer[2]<<3)+buffer[3];
char topic[tl+1];
for (int i=0;i<tl;i++) {
topic[i] = buffer[4+i];
}
topic[tl] = 0;
// ignore msgID - only support QoS 0 subs
uint8_t *payload = buffer+4+tl;
callback(topic,payload,len-4-tl);
}
} else if (type == 12) { // PINGREG
_client.write(208);
_client.write((uint8_t)0);
lastActivity = t;
}
}
}
return 1;
}
return 0;
}
int PubSubClient::publish(char* topic, char* payload) {
return publish(topic,(uint8_t*)payload,strlen(payload));
}
int PubSubClient::publish(char* topic, uint8_t* payload, uint8_t plength) {
if (_client.connected()) {
uint8_t length = writeString(topic,buffer,0);
int i;
for (i=0;i<plength;i++) {
buffer[length++] = payload[i];
}
//header |= 1; retain
write(MQTTPUBLISH,buffer,length);
return 1;
}
return 0;
}
int PubSubClient::write(uint8_t header, uint8_t* buf, uint8_t length) {
_client.write(header);
_client.write(length);
for (int i=0;i<length;i++) {
_client.write(buf[i]);
}
return 0;
}
void PubSubClient::subscribe(char* topic) {
if (_client.connected()) {
uint8_t length = 2;
nextMsgId++;
buffer[0] = nextMsgId >> 8;
buffer[1] = nextMsgId - (buffer[0]<<8);
length = writeString(topic, buffer,length);
buffer[length++] = 0; // Only do QoS 0 subs
write(MQTTSUBSCRIBE,buffer,length);
}
}
void PubSubClient::disconnect() {
_client.write(224);
_client.write((uint8_t)0);
_client.stop();
lastActivity = millis();
}
uint8_t PubSubClient::writeString(char* string, uint8_t* buf, uint8_t pos) {
char* idp = string;
uint8_t i = 0;
pos += 2;
while (*idp) {
buf[pos++] = *idp++;
i++;
}
buf[pos-i-2] = 0;
buf[pos-i-1] = i;
return pos;
}
int PubSubClient::connected() {
return (int)_client.connected();
}
<commit_msg>Fixed packet reading issue in PubSubClient.readPacket<commit_after>/*
PubSubClient.cpp - A simple client for MQTT.
Nicholas O'Leary
http://knolleary.net
*/
#include "WConstants.h"
#include "PubSubClient.h"
#include "Client.h"
#include "string.h"
#define MQTTCONNECT 1<<4
#define MQTTPUBLISH 3<<4
#define MQTTSUBSCRIBE 8<<4
PubSubClient::PubSubClient(uint8_t *ip, uint16_t port, void (*callback)(char*,uint8_t*,int)) : _client(ip,port) {
this->callback = callback;
}
int PubSubClient::connect(char *id) {
return connect(id,0,0,0,0);
}
int PubSubClient::connect(char *id, char* willTopic, uint8_t willQos, uint8_t willRetain, char* willMessage) {
if (!_client.connected()) {
if (_client.connect()) {
nextMsgId = 1;
uint8_t d[9] = {0x00,0x06,0x4d,0x51,0x49,0x73,0x64,0x70,0x03};
uint8_t length = 0;
int j;
for (j = 0;j<9;j++) {
buffer[length++] = d[j];
}
if (willTopic) {
buffer[length++] = 0x06|(willQos<<3)|(willRetain<<5);
} else {
buffer[length++] = 0x02;
}
buffer[length++] = 0;
buffer[length++] = (KEEPALIVE/1000);
length = writeString(id,buffer,length);
if (willTopic) {
length = writeString(willTopic,buffer,length);
length = writeString(willMessage,buffer,length);
}
write(MQTTCONNECT,buffer,length);
while (!_client.available()) {}
uint8_t len = readPacket();
if (len == 4 && buffer[3] == 0) {
lastActivity = millis();
return 1;
}
_client.stop();
}
}
return 0;
}
uint8_t PubSubClient::readPacket() {
uint8_t len = 0;
while (!_client.available()) {}
buffer[len++] = _client.read();
uint8_t multiplier = 1;
uint8_t length = 0;
uint8_t digit = 0;
do {
while (!_client.available()) {}
digit = _client.read();
buffer[len++] = digit;
length += (digit & 127) * multiplier;
multiplier *= 128;
} while ((digit & 128) != 0);
for (int i = 0;i<length;i++)
{
if (len < MAX_PACKET_SIZE) {
while (!_client.available()) {}
buffer[len++] = _client.read();
} else {
while (!_client.available()) {}
_client.read();
len = 0; // This will cause the packet to be ignored.
}
}
return len;
}
int PubSubClient::loop() {
if (_client.connected()) {
long t = millis();
if (t - lastActivity > KEEPALIVE) {
_client.write(192);
_client.write((uint8_t)0);
lastActivity = t;
}
if (_client.available()) {
uint8_t len = readPacket();
if (len > 0) {
uint8_t type = buffer[0]>>4;
if (type == 3) { // PUBLISH
if (callback) {
uint8_t tl = (buffer[2]<<3)+buffer[3];
char topic[tl+1];
for (int i=0;i<tl;i++) {
topic[i] = buffer[4+i];
}
topic[tl] = 0;
// ignore msgID - only support QoS 0 subs
uint8_t *payload = buffer+4+tl;
callback(topic,payload,len-4-tl);
}
} else if (type == 12) { // PINGREG
_client.write(208);
_client.write((uint8_t)0);
lastActivity = t;
}
}
}
return 1;
}
return 0;
}
int PubSubClient::publish(char* topic, char* payload) {
return publish(topic,(uint8_t*)payload,strlen(payload));
}
int PubSubClient::publish(char* topic, uint8_t* payload, uint8_t plength) {
if (_client.connected()) {
uint8_t length = writeString(topic,buffer,0);
int i;
for (i=0;i<plength;i++) {
buffer[length++] = payload[i];
}
//header |= 1; retain
write(MQTTPUBLISH,buffer,length);
return 1;
}
return 0;
}
int PubSubClient::write(uint8_t header, uint8_t* buf, uint8_t length) {
_client.write(header);
_client.write(length);
for (int i=0;i<length;i++) {
_client.write(buf[i]);
}
return 0;
}
void PubSubClient::subscribe(char* topic) {
if (_client.connected()) {
uint8_t length = 2;
nextMsgId++;
buffer[0] = nextMsgId >> 8;
buffer[1] = nextMsgId - (buffer[0]<<8);
length = writeString(topic, buffer,length);
buffer[length++] = 0; // Only do QoS 0 subs
write(MQTTSUBSCRIBE,buffer,length);
}
}
void PubSubClient::disconnect() {
_client.write(224);
_client.write((uint8_t)0);
_client.stop();
lastActivity = millis();
}
uint8_t PubSubClient::writeString(char* string, uint8_t* buf, uint8_t pos) {
char* idp = string;
uint8_t i = 0;
pos += 2;
while (*idp) {
buf[pos++] = *idp++;
i++;
}
buf[pos-i-2] = 0;
buf[pos-i-1] = i;
return pos;
}
int PubSubClient::connected() {
return (int)_client.connected();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-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 "base58.h"
#include "init.h"
#include "main.h"
#include "net.h"
#include "netbase.h"
#include "rpcserver.h"
#include "txdb.h"
#include "timedata.h"
#include "util.h"
#ifdef ENABLE_WALLET
#include "wallet.h"
#include "walletdb.h"
#endif
#include <stdint.h>
#include <boost/assign/list_of.hpp>
#include "json/json_spirit_utils.h"
#include "json/json_spirit_value.h"
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
Value getinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getinfo\n"
"Returns an object containing various state info.");
proxyType proxy;
GetProxy(NET_IPV4, proxy);
Object obj, diff;
obj.push_back(Pair("version", FormatFullVersion()));
obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION));
#ifdef ENABLE_WALLET
if (pwalletMain) {
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
obj.push_back(Pair("newmint", ValueFromAmount(pwalletMain->GetNewMint())));
obj.push_back(Pair("stake", ValueFromAmount(pwalletMain->GetStake())));
}
#endif
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("timeoffset", (int64_t)GetTimeOffset()));
obj.push_back(Pair("moneysupply", ValueFromAmount(pindexBest->nMoneySupply)));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("proxy", (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string())));
obj.push_back(Pair("ip", GetLocalAddress(NULL).ToStringIP()));
diff.push_back(Pair("proof-of-work", GetDifficulty()));
diff.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
obj.push_back(Pair("difficulty", diff));
obj.push_back(Pair("testnet", TestNet()));
#ifdef ENABLE_WALLET
if (pwalletMain) {
obj.push_back(Pair("keypoololdest", (int64_t)pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize()));
}
obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee)));
obj.push_back(Pair("mininput", ValueFromAmount(nMinimumInputValue)));
if (pwalletMain && pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", (int64_t)nWalletUnlockTime));
#endif
obj.push_back(Pair("errors", GetWarnings("statusbar")));
return obj;
}
#ifdef ENABLE_WALLET
class DescribeAddressVisitor : public boost::static_visitor<Object>
{
public:
Object operator()(const CNoDestination &dest) const { return Object(); }
Object operator()(const CKeyID &keyID) const {
Object obj;
CPubKey vchPubKey;
pwalletMain->GetPubKey(keyID, vchPubKey);
obj.push_back(Pair("isscript", false));
obj.push_back(Pair("pubkey", HexStr(vchPubKey)));
obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
return obj;
}
Object operator()(const CScriptID &scriptID) const {
Object obj;
obj.push_back(Pair("isscript", true));
CScript subscript;
pwalletMain->GetCScript(scriptID, subscript);
std::vector<CTxDestination> addresses;
txnouttype whichType;
int nRequired;
ExtractDestinations(subscript, whichType, addresses, nRequired);
obj.push_back(Pair("script", GetTxnOutputType(whichType)));
obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end())));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
obj.push_back(Pair("addresses", a));
if (whichType == TX_MULTISIG)
obj.push_back(Pair("sigsrequired", nRequired));
return obj;
}
};
#endif
Value validateaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"validateaddress <Clamaddress>\n"
"Return information about <Clamaddress>.");
CBitcoinAddress address(params[0].get_str());
bool isValid = address.IsValid();
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
#ifdef ENABLE_WALLET
bool fMine = pwalletMain ? IsMine(*pwalletMain, dest) : false;
ret.push_back(Pair("ismine", fMine));
if (fMine) {
Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain && pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest]));
#endif
}
return ret;
}
static void validateoutputs_check_unconfirmed_spend(COutPoint& outpoint, CTransaction& tx, Object& entry)
{
// check whether unconfirmed output is already spent
LOCK(mempool.cs); // protect mempool.mapNextTx
if (mempool.mapNextTx.count(outpoint)) {
// pull details from mempool
CInPoint in = mempool.mapNextTx[outpoint];
Object details;
entry.push_back(Pair("status", "spent"));
details.push_back(Pair("txid", in.ptx->GetHash().GetHex()));
details.push_back(Pair("vin", int(in.n)));
details.push_back(Pair("confirmations", 0));
entry.push_back(Pair("spent", details));
} else {
entry.push_back(Pair("status", "unspent"));
const CScript& pk = tx.vout[outpoint.n].scriptPubKey;
entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end())));
}
}
Value validateoutputs(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"validateoutputs [{\"txid\":txid,\"vout\":n},...]\n"
"Return information about outputs (whether they exist, and whether they have been spent).");
Array inputs = params[0].get_array();
CTxDB txdb("r");
CTxIndex txindex;
Array ret;
BOOST_FOREACH(Value& input, inputs)
{
const Object& o = input.get_obj();
const Value& txid_v = find_value(o, "txid");
if (txid_v.type() != str_type)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing txid key");
string txid = txid_v.get_str();
if (!IsHex(txid))
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
const Value& vout_v = find_value(o, "vout");
if (vout_v.type() != int_type)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
int nOutput = vout_v.get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
Object entry;
entry.push_back(Pair("txid", txid));
entry.push_back(Pair("vout", nOutput));
CTransaction tx;
uint256 hashBlock = 0;
CTxIndex txindex;
COutPoint outpoint(uint256(txid), nOutput);
// find the output
if (!GetTransaction(uint256(txid), tx, hashBlock, txindex)) {
entry.push_back(Pair("status", "txid not found"));
ret.push_back(entry);
continue;
}
// check that the output number is in range
if ((unsigned)nOutput >= tx.vout.size()) {
entry.push_back(Pair("status", "vout too high"));
entry.push_back(Pair("outputs", tx.vout.size()));
ret.push_back(entry);
continue;
}
entry.push_back(Pair("amount", ValueFromAmount(tx.vout[nOutput].nValue)));
// get the address and account
CTxDestination address;
if (ExtractDestination(tx.vout[nOutput].scriptPubKey, address))
{
entry.push_back(Pair("address", CBitcoinAddress(address).ToString()));
if (pwalletMain->mapAddressBook.count(address))
entry.push_back(Pair("account", pwalletMain->mapAddressBook[address]));
}
// is the output confirmed?
if (hashBlock == 0) {
entry.push_back(Pair("confirmations", 0));
validateoutputs_check_unconfirmed_spend(outpoint, tx, entry);
ret.push_back(entry);
continue;
}
// find the block containing the output
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second)
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain()) {
entry.push_back(Pair("height", pindex->nHeight));
entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight));
} else {
LogPrintf("can't find block with hash %s\n", hashBlock.GetHex().c_str());
entry.push_back(Pair("confirmations", 0));
}
}
// check whether any confirmed transaction spends this output
if (txindex.vSpent[nOutput].IsNull()) {
// if not, check for an unconfirmed spend
validateoutputs_check_unconfirmed_spend(outpoint, tx, entry);
ret.push_back(entry);
continue;
}
entry.push_back(Pair("status", "spent"));
Object details;
CTransaction spending_tx;
// load the transaction that spends this output
spending_tx.ReadFromDisk(txindex.vSpent[nOutput]);
details.push_back(Pair("txid", spending_tx.GetHash().GetHex()));
// find this output's input number in the spending transaction
int n = 0;
BOOST_FOREACH(CTxIn input, spending_tx.vin) {
if (input.prevout == outpoint) {
details.push_back(Pair("vin", n));
break;
}
n++;
}
// get the spending transaction
if (GetTransaction(uint256(spending_tx.GetHash()), tx, hashBlock, txindex) && hashBlock != 0) {
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second)
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain()) {
details.push_back(Pair("height", pindex->nHeight));
details.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight));
} else {
LogPrintf("can't find block with hash %s\n", hashBlock.GetHex().c_str());
details.push_back(Pair("confirmations", 0));
}
}
}
entry.push_back(Pair("spent", details));
ret.push_back(entry);
}
return ret;
}
Value validatepubkey(const Array& params, bool fHelp)
{
if (fHelp || !params.size() || params.size() > 2)
throw runtime_error(
"validatepubkey <Clampubkey>\n"
"Return information about <Clampubkey>.");
std::vector<unsigned char> vchPubKey = ParseHex(params[0].get_str());
CPubKey pubKey(vchPubKey);
bool isValid = pubKey.IsValid();
bool isCompressed = pubKey.IsCompressed();
CKeyID keyID = pubKey.GetID();
CBitcoinAddress address;
address.Set(keyID);
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
ret.push_back(Pair("iscompressed", isCompressed));
#ifdef ENABLE_WALLET
bool fMine = pwalletMain ? IsMine(*pwalletMain, dest) : false;
ret.push_back(Pair("ismine", fMine));
if (fMine) {
Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain && pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest]));
#endif
}
return ret;
}
Value verifymessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 3)
throw runtime_error(
"verifymessage <Clamaddress> <signature> <message>\n"
"Verify a signed message");
string strAddress = params[0].get_str();
string strSign = params[1].get_str();
string strMessage = params[2].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
bool fInvalid = false;
vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
if (fInvalid)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
CPubKey pubkey;
if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))
return false;
return (pubkey.GetID() == keyID);
}
<commit_msg>Removing proof-of-work from getinfo, as there are no proof of work blocks in clams<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-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 "base58.h"
#include "init.h"
#include "main.h"
#include "net.h"
#include "netbase.h"
#include "rpcserver.h"
#include "txdb.h"
#include "timedata.h"
#include "util.h"
#ifdef ENABLE_WALLET
#include "wallet.h"
#include "walletdb.h"
#endif
#include <stdint.h>
#include <boost/assign/list_of.hpp>
#include "json/json_spirit_utils.h"
#include "json/json_spirit_value.h"
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
Value getinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getinfo\n"
"Returns an object containing various state info.");
proxyType proxy;
GetProxy(NET_IPV4, proxy);
Object obj, diff;
obj.push_back(Pair("version", FormatFullVersion()));
obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION));
#ifdef ENABLE_WALLET
if (pwalletMain) {
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
obj.push_back(Pair("newmint", ValueFromAmount(pwalletMain->GetNewMint())));
obj.push_back(Pair("stake", ValueFromAmount(pwalletMain->GetStake())));
}
#endif
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("timeoffset", (int64_t)GetTimeOffset()));
obj.push_back(Pair("moneysupply", ValueFromAmount(pindexBest->nMoneySupply)));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("proxy", (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string())));
obj.push_back(Pair("ip", GetLocalAddress(NULL).ToStringIP()));
diff.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
obj.push_back(Pair("difficulty", diff));
obj.push_back(Pair("testnet", TestNet()));
#ifdef ENABLE_WALLET
if (pwalletMain) {
obj.push_back(Pair("keypoololdest", (int64_t)pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize()));
}
obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee)));
obj.push_back(Pair("mininput", ValueFromAmount(nMinimumInputValue)));
if (pwalletMain && pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", (int64_t)nWalletUnlockTime));
#endif
obj.push_back(Pair("errors", GetWarnings("statusbar")));
return obj;
}
#ifdef ENABLE_WALLET
class DescribeAddressVisitor : public boost::static_visitor<Object>
{
public:
Object operator()(const CNoDestination &dest) const { return Object(); }
Object operator()(const CKeyID &keyID) const {
Object obj;
CPubKey vchPubKey;
pwalletMain->GetPubKey(keyID, vchPubKey);
obj.push_back(Pair("isscript", false));
obj.push_back(Pair("pubkey", HexStr(vchPubKey)));
obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
return obj;
}
Object operator()(const CScriptID &scriptID) const {
Object obj;
obj.push_back(Pair("isscript", true));
CScript subscript;
pwalletMain->GetCScript(scriptID, subscript);
std::vector<CTxDestination> addresses;
txnouttype whichType;
int nRequired;
ExtractDestinations(subscript, whichType, addresses, nRequired);
obj.push_back(Pair("script", GetTxnOutputType(whichType)));
obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end())));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
obj.push_back(Pair("addresses", a));
if (whichType == TX_MULTISIG)
obj.push_back(Pair("sigsrequired", nRequired));
return obj;
}
};
#endif
Value validateaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"validateaddress <Clamaddress>\n"
"Return information about <Clamaddress>.");
CBitcoinAddress address(params[0].get_str());
bool isValid = address.IsValid();
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
#ifdef ENABLE_WALLET
bool fMine = pwalletMain ? IsMine(*pwalletMain, dest) : false;
ret.push_back(Pair("ismine", fMine));
if (fMine) {
Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain && pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest]));
#endif
}
return ret;
}
static void validateoutputs_check_unconfirmed_spend(COutPoint& outpoint, CTransaction& tx, Object& entry)
{
// check whether unconfirmed output is already spent
LOCK(mempool.cs); // protect mempool.mapNextTx
if (mempool.mapNextTx.count(outpoint)) {
// pull details from mempool
CInPoint in = mempool.mapNextTx[outpoint];
Object details;
entry.push_back(Pair("status", "spent"));
details.push_back(Pair("txid", in.ptx->GetHash().GetHex()));
details.push_back(Pair("vin", int(in.n)));
details.push_back(Pair("confirmations", 0));
entry.push_back(Pair("spent", details));
} else {
entry.push_back(Pair("status", "unspent"));
const CScript& pk = tx.vout[outpoint.n].scriptPubKey;
entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end())));
}
}
Value validateoutputs(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"validateoutputs [{\"txid\":txid,\"vout\":n},...]\n"
"Return information about outputs (whether they exist, and whether they have been spent).");
Array inputs = params[0].get_array();
CTxDB txdb("r");
CTxIndex txindex;
Array ret;
BOOST_FOREACH(Value& input, inputs)
{
const Object& o = input.get_obj();
const Value& txid_v = find_value(o, "txid");
if (txid_v.type() != str_type)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing txid key");
string txid = txid_v.get_str();
if (!IsHex(txid))
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
const Value& vout_v = find_value(o, "vout");
if (vout_v.type() != int_type)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
int nOutput = vout_v.get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
Object entry;
entry.push_back(Pair("txid", txid));
entry.push_back(Pair("vout", nOutput));
CTransaction tx;
uint256 hashBlock = 0;
CTxIndex txindex;
COutPoint outpoint(uint256(txid), nOutput);
// find the output
if (!GetTransaction(uint256(txid), tx, hashBlock, txindex)) {
entry.push_back(Pair("status", "txid not found"));
ret.push_back(entry);
continue;
}
// check that the output number is in range
if ((unsigned)nOutput >= tx.vout.size()) {
entry.push_back(Pair("status", "vout too high"));
entry.push_back(Pair("outputs", tx.vout.size()));
ret.push_back(entry);
continue;
}
entry.push_back(Pair("amount", ValueFromAmount(tx.vout[nOutput].nValue)));
// get the address and account
CTxDestination address;
if (ExtractDestination(tx.vout[nOutput].scriptPubKey, address))
{
entry.push_back(Pair("address", CBitcoinAddress(address).ToString()));
if (pwalletMain->mapAddressBook.count(address))
entry.push_back(Pair("account", pwalletMain->mapAddressBook[address]));
}
// is the output confirmed?
if (hashBlock == 0) {
entry.push_back(Pair("confirmations", 0));
validateoutputs_check_unconfirmed_spend(outpoint, tx, entry);
ret.push_back(entry);
continue;
}
// find the block containing the output
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second)
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain()) {
entry.push_back(Pair("height", pindex->nHeight));
entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight));
} else {
LogPrintf("can't find block with hash %s\n", hashBlock.GetHex().c_str());
entry.push_back(Pair("confirmations", 0));
}
}
// check whether any confirmed transaction spends this output
if (txindex.vSpent[nOutput].IsNull()) {
// if not, check for an unconfirmed spend
validateoutputs_check_unconfirmed_spend(outpoint, tx, entry);
ret.push_back(entry);
continue;
}
entry.push_back(Pair("status", "spent"));
Object details;
CTransaction spending_tx;
// load the transaction that spends this output
spending_tx.ReadFromDisk(txindex.vSpent[nOutput]);
details.push_back(Pair("txid", spending_tx.GetHash().GetHex()));
// find this output's input number in the spending transaction
int n = 0;
BOOST_FOREACH(CTxIn input, spending_tx.vin) {
if (input.prevout == outpoint) {
details.push_back(Pair("vin", n));
break;
}
n++;
}
// get the spending transaction
if (GetTransaction(uint256(spending_tx.GetHash()), tx, hashBlock, txindex) && hashBlock != 0) {
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second)
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain()) {
details.push_back(Pair("height", pindex->nHeight));
details.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight));
} else {
LogPrintf("can't find block with hash %s\n", hashBlock.GetHex().c_str());
details.push_back(Pair("confirmations", 0));
}
}
}
entry.push_back(Pair("spent", details));
ret.push_back(entry);
}
return ret;
}
Value validatepubkey(const Array& params, bool fHelp)
{
if (fHelp || !params.size() || params.size() > 2)
throw runtime_error(
"validatepubkey <Clampubkey>\n"
"Return information about <Clampubkey>.");
std::vector<unsigned char> vchPubKey = ParseHex(params[0].get_str());
CPubKey pubKey(vchPubKey);
bool isValid = pubKey.IsValid();
bool isCompressed = pubKey.IsCompressed();
CKeyID keyID = pubKey.GetID();
CBitcoinAddress address;
address.Set(keyID);
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
ret.push_back(Pair("iscompressed", isCompressed));
#ifdef ENABLE_WALLET
bool fMine = pwalletMain ? IsMine(*pwalletMain, dest) : false;
ret.push_back(Pair("ismine", fMine));
if (fMine) {
Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain && pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest]));
#endif
}
return ret;
}
Value verifymessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 3)
throw runtime_error(
"verifymessage <Clamaddress> <signature> <message>\n"
"Verify a signed message");
string strAddress = params[0].get_str();
string strSign = params[1].get_str();
string strMessage = params[2].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
bool fInvalid = false;
vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
if (fInvalid)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
CPubKey pubkey;
if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))
return false;
return (pubkey.GetID() == keyID);
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string.h>
#include <istream>
#include <cstring>
#include <unistd.h>
using namespace std;
#include <cstdio>
#include <cstring>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
#include <errno.h>
#include <cstdlib>
#include <vector>
//Counts number of arguments
int count_args( const string & input ) {
if (input.size() == 0 )
{
return 0;
}
int count = 1;
for(unsigned i = 0; i < input.size(); ++i)
{
if ( input.at(i) == '&' || input.at(i) == '|' )
{
i+=1; // first '&' or '|' will be followed by another
count +=1;
}
if ( input.at(i) == ';' && i+1 != input.size() )//can have command: pwd;
{
count +=1;
//BUG: will give greater size than should be when have input: "ls ; pwd; "
//will count white space unfortunately.....
//will say extra argument than there is..
}
}
return count;
}
vector<int> con_pos( const string & input ) {
vector<int> x;
if (input.size() == 0 )
{
return x;
}
//int count = 1;
for(unsigned i = 0; i < input.size(); ++i)
{
if ( input.at(i) == '&' || input.at(i) == '|' )
{
x.push_back(i);
x.push_back(i+1);
i+=1; // first '&' or '|' will be followed by another
//count +=1;
}
if ( input.at(i) == ';' && i+1 != input.size() )//can have command: pwd;
{
x.push_back(i);
//BUG: will give greater size than should be when have input: "ls ; pwd; "
//will count white space unfortunately.....
//will say extra argument than there is..
}
}
return x;
}
int main()
{
string input;
//taking input as a c++ string; will convert to c_str later
cout << "$ "; //command prompt
getline (cin,input);
cout << endl << "outputting input: " << endl << input << endl;
cout << "input.size() (raw): " << input.size() << endl;
// trying to see if space adds size
// Answer: IT DOES -_____-
//these will be the arguments to my shell after parsing
unsigned arg_count = count_args(input);
vector <char**> argv;
argv.resize( arg_count );
char * tmp; //cstring to not deal with memory management for now
char delims[] = " "; // connectors we are looking out for.
//FIXME: may not be exactly what we want since may have
//to be arguments too
int inp_sz = input.size()+1;
char* input2 = new char[inp_sz]; //will take copy of input from std::string input
strcpy(input2, input.c_str() );
cout << "input2 done. no seg fault here. " << endl;
vector <int> pos = con_pos( input ); //contains positions of delimiters
//printing elements in pos
if(pos.size() != 0 ){
for(unsigned i = 0; i < pos.size(); ++i){
cout << pos.at(i) << " ";
}
cout << endl;
}
//
for(unsigned i = 0; i < arg_count; ++i)
{
int argc = 0 ; // no arguments (yet)
tmp = strtok(input2,delims) ;
cout << "strtok, i = " << i << endl;
argv.at(i) = new char* [999];
argv.at(i)[argc] = new char[strlen(tmp) +1];
strcpy( (argv.at(i)[argc] ) , tmp ); //copying first token
cout << "strcpy, i = " << i << endl;
while (tmp != NULL)
{
argc +=1; // argument count increases.
printf ("%s\n",tmp) ;
tmp = strtok (NULL,delims);
argv.at(i)[argc] = tmp; // copying tokens into argv one at a time
}
cout << "first while, i = " << i << endl;
}
/* cerr << "copying tmp into argv..." << endl;
strcpy(*argv,tmp );
cout << "strcpy successful!! (maybe LOL)" << endl;
*/
//checking everything was read in
//cout << "argc: " << argc << " " << endl;
//cout << " argv:" << endl;
for(unsigned i = 0; argv[i]!='\0'; ++i){
cout << i << ": " << argv[i] << endl;
}
//need to figure out a way to read in commands with ';' in between
//and white space in between
//checking how execvp works (dummy variables)
char * aargv[4];
aargv[0] = new char[4];
aargv[1] = new char[4];
aargv[2] = new char[4];
strcpy( aargv[0] , "pwd"); //copying first token
cout << "first copy. \n" << endl;
strcpy( aargv[1] , " ; " );
cout << "about tho start third..." << endl;
strcpy( aargv[2] , "ls");
cout << "done copying... " << endl;
//beginning fork, execpv processes
//may need to creat multiple forks to run input with connectors
//will now make major changes
//execute multiple commands through for loop (similar to lab02)
int pid=fork();
if(pid == -1)
{
perror("There was an error with fork(). " );
exit(1);
}
//child process
if (pid==0) {
cout << "i'm a child" << endl;
/*
if(-1 == execvp(*argv.at(0)[0] , *argv.at(0) )
{
perror("Error: execvp didn't run as expected. Commands may not exist.");
exit(1); //avoid zombies
}*/
}
//pid now > 0 so we are in parent process.
else{
if( wait(NULL) == -1 ){
perror("Error: wait() did not wait!! :o ");
}
cout << "I'm a parent." << endl;
exit(1);
}
return 0;
}
<commit_msg>now need to make fork for loop work.<commit_after>#include <iostream>
#include <string.h>
#include <istream>
#include <cstring>
#include <unistd.h>
using namespace std;
#include <cstdio>
#include <cstring>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
#include <errno.h>
#include <cstdlib>
#include <vector>
//Counts number of arguments
int count_args( const string & input ) {
if (input.size() == 0 )
{
return 0;
}
int count = 1;
for(unsigned i = 0; i < input.size(); ++i)
{
if ( input.at(i) == '&' || input.at(i) == '|' )
{
i+=1; // first '&' or '|' will be followed by another
count +=1;
}
if ( input.at(i) == ';' && i+1 != input.size() )//can have command: pwd;
{
count +=1;
//BUG: will give greater size than should be when have input: "ls ; pwd; "
//will count white space unfortunately.....
//will say extra argument than there is..
}
}
return count;
}
vector<unsigned> con_pos( const string & input ) {
vector<unsigned> x;
if (input.size() == 0 )
{
return x;
}
//int count = 1;
for(unsigned i = 0; i < input.size(); ++i)
{
if ( input.at(i) == '&' || input.at(i) == '|' )
{
x.push_back(i);
x.push_back(i+1);
i+=1; // first '&' or '|' will be followed by another
//count +=1;
}
if ( input.at(i) == ';' && i+1 != input.size() )//can have command: pwd;
{
x.push_back(i);
//BUG: will give greater size than should be when have input: "ls ; pwd; "
//will count white space unfortunately.....
//will say extra argument than there is..
}
}
return x;
}
int main()
{
string input;
//taking input as a c++ string; will convert to c_str later
cout << "$ "; //command prompt
getline (cin,input);
cout << endl << "outputting input: " << endl << input << endl;
cout << "input.size() (raw): " << input.size() << endl;
// trying to see if space adds size
// Answer: IT DOES -_____-
//these will be the arguments to my shell after parsing
unsigned arg_count = count_args(input);
vector <char**> argv;
argv.resize( arg_count );
char * tmp; //cstring to not deal with memory management for now
int inp_sz = input.size()+1;
char* input2 = new char[inp_sz]; //will take copy of input from std::string input
strcpy(input2, input.c_str() );
cout << "input2 done. no seg fault here. " << endl;
vector <unsigned> pos;
if(con_pos(input).size() != 0 )
{
vector <unsigned> pos = con_pos( input ); //contains positions of delimiters
}
cout << "printing elements in pos " << endl;
if(pos.size() != 0 ){
for(unsigned i = 0; i < pos.size(); ++i){
cout << pos.at(i) << " ";
}
cout << endl;
}
vector <char*> inp;
inp.resize(arg_count+1);
//loop to get substrings of input with "&&||;" as delimiters
int argc = 0 ; // no arguments (yet)
tmp = strtok(input2,"&&||;");
if(tmp != NULL)
{
inp.at(0) = new char[strlen(tmp) +1];
strcpy( inp.at(0) , tmp ); //copying first token
}
cout << "arg_count " << arg_count << endl;
while (tmp != NULL)
{
argc +=1; // argument count increases.
printf ("%s\n",tmp) ;
tmp = strtok (NULL,"&&||;");
cout << "before new char, argc: " << argc << endl;
if(tmp != NULL){
inp.at(argc) = new char[strlen(tmp) +1];
cout << "before ...." << endl;
inp.at(argc) = tmp; // copying tokens into argv one at a time
cout << "after .... " << endl;
}
}
cout << "outta the loop; " << endl;
//unsigned i_pos = 0;
//unsigned i_inp2 = 0;
for(unsigned i = 0; i < arg_count; ++i)
{
int argc = 0 ; // no arguments (yet)
tmp = strtok(inp.at(i)," ") ;
cout << "strtok, i = " << i << endl;
if(tmp != NULL){
argv.at(i) = new char* [ strlen(inp.at(i) ) + 3 ];
argv.at(i)[argc] = new char[strlen(tmp) +1];
strcpy( (argv.at(i)[argc] ) , tmp ); //copying first token
cout << "strcpy, i = " << i << endl;
}
while (tmp != NULL)
{
if(tmp != NULL){
argc +=1; // argument count increases.
printf ("%s\n",tmp) ;
tmp = strtok (NULL," ");
argv.at(i)[argc] = tmp; // copying tokens into argv one at a time
}
}
cout << "first while, i = " << i << endl;
}
cout << "skipped for loop...." << endl;
//FIXME
//SEGMENTATION FAULT SOMEWHERE AFTER HERE!!!! CASE: PRESSING ENTER , input.size() == 0
/* cerr << "copying tmp into argv..." << endl;
strcpy(*argv,tmp );
cout << "strcpy successful!! (maybe LOL)" << endl;
*/
//checking everything was read in
//cout << "argc: " << argc << " " << endl;
//cout << " argv:" << endl;
// for(unsigned i = 0; argv[i]!='\0'; ++i){
// cout << i << ": " << argv[i] << endl;
// }
//need to figure out a way to read in commands with ';' in between
//and white space in between
//checking how execvp works (dummy variables)
char * aargv[4];
aargv[0] = new char[4];
aargv[1] = new char[4];
aargv[2] = new char[4];
strcpy( aargv[0] , "pwd"); //copying first token
cout << "first copy. \n" << endl;
strcpy( aargv[1] , " ; " );
cout << "about tho start third..." << endl;
strcpy( aargv[2] , "ls");
cout << "done copying... " << endl;
//beginning fork, execpv processes
//may need to creat multiple forks to run input with connectors
//will now make changes
//execute multiple commands through for loop (similar to lab02)
int pid=fork();
if(pid == -1)
{
perror("There was an error with fork(). " );
exit(1);
}
//child process
if (pid==0) {
cout << "i'm a child" << endl;
/*
if(-1 == execvp(*argv.at(0)[0] , *argv.at(0) )
{
perror("Error: execvp didn't run as expected. Commands may not exist.");
exit(1); //avoid zombies
}*/
}
//pid now > 0 so we are in parent process.
else{
if( wait(NULL) == -1 ){
perror("Error: wait() did not wait!! :o ");
}
cout << "I'm a parent." << endl;
exit(1);
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
+----------------------------------------------------------------------+
| PHP-OpenCV |
+----------------------------------------------------------------------+
| This source file is subject to version 2.0 of the Apache license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.apache.org/licenses/LICENSE-2.0.html |
| If you did not receive a copy of the Apache2.0 license and are unable|
| to obtain it through the world-wide-web, please send a note to |
| hihozhou@gmail.com so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: HaiHao Zhou <hihozhou@gmail.com> |
+----------------------------------------------------------------------+
*/
#include "../../../php_opencv.h"
#include "opencv_facerec.h"
#ifdef HAVE_OPENCV_FACE
#include "../opencv_face.h"
#include "../core/opencv_mat.h"
#include "../../../opencv_exception.h"
#include <opencv2/face.hpp>
using namespace cv::face;
#define Z_PHP_LBPH_FACE_RECOGNIZER_OBJ_P(zv) get_lbph_face_recognizer_obj(Z_OBJ_P(zv))
typedef struct _opencv_lbph_face_recognizer_object{
zend_object std;
Ptr<LBPHFaceRecognizer> faceRecognizer;
}opencv_lbph_face_recognizer_object;
/**
* @param obj
* @return
*/
static inline opencv_lbph_face_recognizer_object* get_lbph_face_recognizer_obj(zend_object *obj) {
return (opencv_lbph_face_recognizer_object*)((char*)(obj) - XtOffsetOf(opencv_lbph_face_recognizer_object, std));
}
zend_object_handlers opencv_lbph_face_recognizer_object_handlers;
zend_class_entry *opencv_lbph_face_recognizer_ce;
zend_class_entry *opencv_base_face_recognizer_ce;
PHP_METHOD(opencv_lbph_face_recognizer, create)
{
zval instance;
object_init_ex(&instance, opencv_lbph_face_recognizer_ce);
opencv_lbph_face_recognizer_object *obj = Z_PHP_LBPH_FACE_RECOGNIZER_OBJ_P(&instance);
obj->faceRecognizer = LBPHFaceRecognizer::create();
RETURN_ZVAL(&instance,0,0);
}
PHP_METHOD(opencv_lbph_face_recognizer, train)
{
zval *src_zval, *labels_zval;
zend_ulong _h;
zval *array_val_zval;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "aa", &src_zval, &labels_zval) == FAILURE) {
RETURN_NULL();
}
std::vector<Mat> src;
std::vector<int> labels;
//check
opencv_lbph_face_recognizer_object *obj = Z_PHP_LBPH_FACE_RECOGNIZER_OBJ_P(getThis());
unsigned long src_count = zend_hash_num_elements(Z_ARRVAL_P(src_zval));
src.reserve(src_count);//指定长度
opencv_mat_object *mat_obj;
ZEND_HASH_FOREACH_NUM_KEY_VAL(Z_ARRVAL_P(src_zval),_h,array_val_zval){
//check array_val_zval is Mat object
again1:
if(Z_TYPE_P(array_val_zval) == IS_OBJECT && Z_OBJCE_P(array_val_zval)==opencv_mat_ce){
mat_obj = Z_PHP_MAT_OBJ_P(array_val_zval);
src.push_back(*mat_obj->mat);
}else if(Z_TYPE_P(array_val_zval) == IS_REFERENCE){
array_val_zval = Z_REFVAL_P(array_val_zval);
goto again1;
} else {
opencv_throw_exception("array value just Mat object.");
RETURN_NULL();
}
}ZEND_HASH_FOREACH_END();
ZEND_HASH_FOREACH_NUM_KEY_VAL(Z_ARRVAL_P(labels_zval),_h,array_val_zval){
again2:
if(Z_TYPE_P(array_val_zval) == IS_LONG){
labels.push_back((int)zval_get_long(array_val_zval));
}else if(Z_TYPE_P(array_val_zval) == IS_REFERENCE){
array_val_zval = Z_REFVAL_P(array_val_zval);
goto again2;
} else {
opencv_throw_exception("array value just number.");
RETURN_NULL();
}
}ZEND_HASH_FOREACH_END();
obj->faceRecognizer->train(src,labels);
RETURN_NULL();
}
PHP_METHOD(opencv_lbph_face_recognizer, predict)
{
zval *src_zval;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "o", &src_zval, opencv_mat_ce) == FAILURE) {
RETURN_NULL();
}
opencv_lbph_face_recognizer_object *obj = Z_PHP_LBPH_FACE_RECOGNIZER_OBJ_P(getThis());
opencv_mat_object *src_object = Z_PHP_MAT_OBJ_P(src_zval);
int predict_label = obj->faceRecognizer->predict(*src_object->mat);
RETURN_LONG(predict_label);
}
PHP_METHOD(opencv_lbph_face_recognizer, predictConfidence)
{
zval *src_zval;
int label = 0;
double confidence = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "o", &src_zval, opencv_mat_ce) == FAILURE) {
RETURN_NULL();
}
opencv_lbph_face_recognizer_object *obj = Z_PHP_LBPH_FACE_RECOGNIZER_OBJ_P(getThis());
opencv_mat_object *src_object = Z_PHP_MAT_OBJ_P(src_zval);
obj->faceRecognizer->predict(*src_object->mat, label, confidence);
RETURN_DOUBLE(confidence);
}
PHP_METHOD(opencv_lbph_face_recognizer, read)
{
char *filename;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &filename) == FAILURE) {
RETURN_NULL();
}
opencv_lbph_face_recognizer_object *obj = Z_PHP_LBPH_FACE_RECOGNIZER_OBJ_P(getThis());
obj->faceRecognizer->read(filename);
RETURN_NULL();
}
PHP_METHOD(opencv_lbph_face_recognizer, write)
{
char *filename;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &filename) == FAILURE) {
RETURN_NULL();
}
opencv_lbph_face_recognizer_object *obj = Z_PHP_LBPH_FACE_RECOGNIZER_OBJ_P(getThis());
obj->faceRecognizer->write(filename);
RETURN_NULL();
}
/**
* opencv_lbph_face_recognizer_methods[]
*/
const zend_function_entry opencv_lbph_face_recognizer_methods[] = {
PHP_ME(opencv_lbph_face_recognizer, create, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
PHP_ME(opencv_lbph_face_recognizer, train, NULL, ZEND_ACC_PUBLIC)
PHP_ME(opencv_lbph_face_recognizer, predict, NULL, ZEND_ACC_PUBLIC)
PHP_ME(opencv_lbph_face_recognizer, predictConfidence, NULL, ZEND_ACC_PUBLIC)
PHP_ME(opencv_lbph_face_recognizer, read, NULL, ZEND_ACC_PUBLIC)
PHP_ME(opencv_lbph_face_recognizer, write, NULL, ZEND_ACC_PUBLIC)
PHP_FE_END
};
/* }}} */
/**
* @param type
* @return
*/
zend_object* opencv_lbph_face_recognizer_handler(zend_class_entry *type)
{
size_t size = sizeof(opencv_lbph_face_recognizer_object);
opencv_lbph_face_recognizer_object *obj = (opencv_lbph_face_recognizer_object *)ecalloc(1,size);
memset(obj, 0, sizeof(opencv_lbph_face_recognizer_object));
zend_object_std_init(&obj->std, type);
object_properties_init(&obj->std, type);
obj->std.ce = type;
obj->std.handlers = &opencv_lbph_face_recognizer_object_handlers;
return &obj->std;
}
void opencv_lbph_face_recognizer_free_obj(zend_object *object)
{
opencv_lbph_face_recognizer_object *obj;
obj = get_lbph_face_recognizer_obj(object);
delete obj->faceRecognizer;
zend_object_std_dtor(object);
}
void opencv_lbph_face_recognizer_init(int module_number){
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce,OPENCV_FACE_NS, "LBPHFaceRecognizer", opencv_lbph_face_recognizer_methods);
opencv_lbph_face_recognizer_ce = zend_register_internal_class_ex(&ce, opencv_face_recognizer_ce);
opencv_lbph_face_recognizer_ce->create_object = opencv_lbph_face_recognizer_handler;
memcpy(&opencv_lbph_face_recognizer_object_handlers,
zend_get_std_object_handlers(), sizeof(zend_object_handlers));
opencv_lbph_face_recognizer_object_handlers.clone_obj = NULL;
opencv_lbph_face_recognizer_object_handlers.free_obj = opencv_lbph_face_recognizer_free_obj;
}
/**
* -----------------------------------【CV\BaseFaceRecognizer】--------------------------------------
*
* -------------------------------------------------------------------------------------
*/
/**
* opencv_lbph_face_recognizer_methods[]
*/
const zend_function_entry opencv_base_face_recognizer_methods[] = {
PHP_FE_END
};
/* }}} */
void opencv_base_face_recognizer_init(int module_number){
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce,OPENCV_FACE_NS, "BaseFaceRecognizer", opencv_base_face_recognizer_methods);
opencv_base_face_recognizer_ce = zend_register_internal_class_ex(&ce, opencv_face_recognizer_ce);
}
#else
void opencv_lbph_face_recognizer_init(int module_number){
}
void opencv_base_face_recognizer_init(int module_number){
}
#endif
<commit_msg>Update opencv_facerec.cc<commit_after>/*
+----------------------------------------------------------------------+
| PHP-OpenCV |
+----------------------------------------------------------------------+
| This source file is subject to version 2.0 of the Apache license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.apache.org/licenses/LICENSE-2.0.html |
| If you did not receive a copy of the Apache2.0 license and are unable|
| to obtain it through the world-wide-web, please send a note to |
| hihozhou@gmail.com so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: HaiHao Zhou <hihozhou@gmail.com> |
+----------------------------------------------------------------------+
*/
#include "../../../php_opencv.h"
#include "opencv_facerec.h"
#ifdef HAVE_OPENCV_FACE
#include "../opencv_face.h"
#include "../core/opencv_mat.h"
#include "../../../opencv_exception.h"
#include <opencv2/face.hpp>
using namespace cv::face;
#define Z_PHP_LBPH_FACE_RECOGNIZER_OBJ_P(zv) get_lbph_face_recognizer_obj(Z_OBJ_P(zv))
typedef struct _opencv_lbph_face_recognizer_object{
zend_object std;
Ptr<LBPHFaceRecognizer> faceRecognizer;
}opencv_lbph_face_recognizer_object;
/**
* @param obj
* @return
*/
static inline opencv_lbph_face_recognizer_object* get_lbph_face_recognizer_obj(zend_object *obj) {
return (opencv_lbph_face_recognizer_object*)((char*)(obj) - XtOffsetOf(opencv_lbph_face_recognizer_object, std));
}
zend_object_handlers opencv_lbph_face_recognizer_object_handlers;
zend_class_entry *opencv_lbph_face_recognizer_ce;
zend_class_entry *opencv_base_face_recognizer_ce;
PHP_METHOD(opencv_lbph_face_recognizer, create)
{
zval instance;
object_init_ex(&instance, opencv_lbph_face_recognizer_ce);
opencv_lbph_face_recognizer_object *obj = Z_PHP_LBPH_FACE_RECOGNIZER_OBJ_P(&instance);
obj->faceRecognizer = LBPHFaceRecognizer::create();
RETURN_ZVAL(&instance,0,0);
}
PHP_METHOD(opencv_lbph_face_recognizer, train)
{
zval *src_zval, *labels_zval;
zend_ulong _h;
zval *array_val_zval;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "aa", &src_zval, &labels_zval) == FAILURE) {
RETURN_NULL();
}
std::vector<Mat> src;
std::vector<int> labels;
//check
opencv_lbph_face_recognizer_object *obj = Z_PHP_LBPH_FACE_RECOGNIZER_OBJ_P(getThis());
unsigned long src_count = zend_hash_num_elements(Z_ARRVAL_P(src_zval));
src.reserve(src_count);//指定长度
opencv_mat_object *mat_obj;
ZEND_HASH_FOREACH_NUM_KEY_VAL(Z_ARRVAL_P(src_zval),_h,array_val_zval){
//check array_val_zval is Mat object
again1:
if(Z_TYPE_P(array_val_zval) == IS_OBJECT && Z_OBJCE_P(array_val_zval)==opencv_mat_ce){
mat_obj = Z_PHP_MAT_OBJ_P(array_val_zval);
src.push_back(*mat_obj->mat);
}else if(Z_TYPE_P(array_val_zval) == IS_REFERENCE){
array_val_zval = Z_REFVAL_P(array_val_zval);
goto again1;
} else {
opencv_throw_exception("array value just Mat object.");
RETURN_NULL();
}
}ZEND_HASH_FOREACH_END();
ZEND_HASH_FOREACH_NUM_KEY_VAL(Z_ARRVAL_P(labels_zval),_h,array_val_zval){
again2:
if(Z_TYPE_P(array_val_zval) == IS_LONG){
labels.push_back((int)zval_get_long(array_val_zval));
}else if(Z_TYPE_P(array_val_zval) == IS_REFERENCE){
array_val_zval = Z_REFVAL_P(array_val_zval);
goto again2;
} else {
opencv_throw_exception("array value just number.");
RETURN_NULL();
}
}ZEND_HASH_FOREACH_END();
obj->faceRecognizer->train(src,labels);
RETURN_NULL();
}
PHP_METHOD(opencv_lbph_face_recognizer, predict)
{
zval *src_zval;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "o", &src_zval, opencv_mat_ce) == FAILURE) {
RETURN_NULL();
}
opencv_lbph_face_recognizer_object *obj = Z_PHP_LBPH_FACE_RECOGNIZER_OBJ_P(getThis());
opencv_mat_object *src_object = Z_PHP_MAT_OBJ_P(src_zval);
int predict_label = obj->faceRecognizer->predict(*src_object->mat);
RETURN_LONG(predict_label);
}
PHP_METHOD(opencv_lbph_face_recognizer, predictConfidence)
{
zval *src_zval;
int label = 0;
double confidence = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "o", &src_zval, opencv_mat_ce) == FAILURE) {
RETURN_NULL();
}
opencv_lbph_face_recognizer_object *obj = Z_PHP_LBPH_FACE_RECOGNIZER_OBJ_P(getThis());
opencv_mat_object *src_object = Z_PHP_MAT_OBJ_P(src_zval);
obj->faceRecognizer->predict(*src_object->mat, label, confidence);
RETURN_DOUBLE(confidence);
}
PHP_METHOD(opencv_lbph_face_recognizer, read)
{
char *filename;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &filename) == FAILURE) {
RETURN_NULL();
}
opencv_lbph_face_recognizer_object *obj = Z_PHP_LBPH_FACE_RECOGNIZER_OBJ_P(getThis());
obj->faceRecognizer->read(filename);
RETURN_NULL();
}
PHP_METHOD(opencv_lbph_face_recognizer, write)
{
char *filename;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &filename) == FAILURE) {
RETURN_NULL();
}
opencv_lbph_face_recognizer_object *obj = Z_PHP_LBPH_FACE_RECOGNIZER_OBJ_P(getThis());
obj->faceRecognizer->write(filename);
RETURN_NULL();
}
/**
* opencv_lbph_face_recognizer_methods[]
*/
const zend_function_entry opencv_lbph_face_recognizer_methods[] = {
PHP_ME(opencv_lbph_face_recognizer, create, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
PHP_ME(opencv_lbph_face_recognizer, train, NULL, ZEND_ACC_PUBLIC)
PHP_ME(opencv_lbph_face_recognizer, predict, NULL, ZEND_ACC_PUBLIC)
// todo
PHP_ME(opencv_lbph_face_recognizer, predictConfidence, NULL, ZEND_ACC_PUBLIC)
PHP_ME(opencv_lbph_face_recognizer, read, NULL, ZEND_ACC_PUBLIC)
PHP_ME(opencv_lbph_face_recognizer, write, NULL, ZEND_ACC_PUBLIC)
PHP_FE_END
};
/* }}} */
/**
* @param type
* @return
*/
zend_object* opencv_lbph_face_recognizer_handler(zend_class_entry *type)
{
size_t size = sizeof(opencv_lbph_face_recognizer_object);
opencv_lbph_face_recognizer_object *obj = (opencv_lbph_face_recognizer_object *)ecalloc(1,size);
memset(obj, 0, sizeof(opencv_lbph_face_recognizer_object));
zend_object_std_init(&obj->std, type);
object_properties_init(&obj->std, type);
obj->std.ce = type;
obj->std.handlers = &opencv_lbph_face_recognizer_object_handlers;
return &obj->std;
}
void opencv_lbph_face_recognizer_free_obj(zend_object *object)
{
opencv_lbph_face_recognizer_object *obj;
obj = get_lbph_face_recognizer_obj(object);
delete obj->faceRecognizer;
zend_object_std_dtor(object);
}
void opencv_lbph_face_recognizer_init(int module_number){
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce,OPENCV_FACE_NS, "LBPHFaceRecognizer", opencv_lbph_face_recognizer_methods);
opencv_lbph_face_recognizer_ce = zend_register_internal_class_ex(&ce, opencv_face_recognizer_ce);
opencv_lbph_face_recognizer_ce->create_object = opencv_lbph_face_recognizer_handler;
memcpy(&opencv_lbph_face_recognizer_object_handlers,
zend_get_std_object_handlers(), sizeof(zend_object_handlers));
opencv_lbph_face_recognizer_object_handlers.clone_obj = NULL;
opencv_lbph_face_recognizer_object_handlers.free_obj = opencv_lbph_face_recognizer_free_obj;
}
/**
* -----------------------------------【CV\BaseFaceRecognizer】--------------------------------------
*
* -------------------------------------------------------------------------------------
*/
/**
* opencv_lbph_face_recognizer_methods[]
*/
const zend_function_entry opencv_base_face_recognizer_methods[] = {
PHP_FE_END
};
/* }}} */
void opencv_base_face_recognizer_init(int module_number){
zend_class_entry ce;
INIT_NS_CLASS_ENTRY(ce,OPENCV_FACE_NS, "BaseFaceRecognizer", opencv_base_face_recognizer_methods);
opencv_base_face_recognizer_ce = zend_register_internal_class_ex(&ce, opencv_face_recognizer_ce);
}
#else
void opencv_lbph_face_recognizer_init(int module_number){
}
void opencv_base_face_recognizer_init(int module_number){
}
#endif
<|endoftext|>
|
<commit_before>#include <string.h>
#include <iostream>
#include <vector>
#include <map>
#include "expat.h"
using namespace std;
class XMLObj;
class XMLObjIter {
map<string, XMLObj *>::iterator cur;
map<string, XMLObj *>::iterator end;
public:
XMLObjIter() {}
void set(map<string, XMLObj *>::iterator& _cur, map<string, XMLObj *>::iterator& _end) { cur = _cur; end = _end; }
XMLObj *get_next() {
XMLObj *obj = NULL;
if (cur != end) {
obj = cur->second;
++cur;
}
return obj;
};
};
class XMLObj
{
XMLObj *parent;
const char *el_type;
map<string, string> attr_map;
string data;
protected:
multimap<string, XMLObj *> children;
public:
XMLObj() {}
virtual ~XMLObj() {}
void xml_start(XMLObj *parent, const char *el, const char **attr) {
this->parent = parent;
el_type = el;
for (int i = 0; attr[i]; i += 2) {
attr_map[attr[i]] = string(attr[i + 1]);
}
}
virtual void xml_end(const char *el) {}
virtual void xml_handle_data(const char *s, int len) { data = string(s, len); }
string& get_data() { return data; }
XMLObj *get_parent() { return parent; }
void add_child(string el, XMLObj *obj) {
children.insert(pair<string, XMLObj *>(el, obj));
}
XMLObjIter find(string name) {
XMLObjIter iter;
map<string, XMLObj *>::iterator first;
map<string, XMLObj *>::iterator last;
first = children.find(name);
last = children.upper_bound(name);
iter.set(first, last);
return iter;
}
};
class ACLOwner : public XMLObj
{
public:
ACLOwner() {}
~ACLOwner() {}
};
class ACLGrant : public XMLObj
{
public:
ACLGrant() {}
~ACLGrant() {}
};
class ACLGrantee : public XMLObj
{
public:
ACLGrantee() {}
~ACLGrantee() {}
};
class ACLDisplayName : public XMLObj
{
public:
ACLDisplayName() {}
~ACLDisplayName() {}
};
class ACLPermission : public XMLObj
{
public:
ACLPermission() {}
~ACLPermission() {}
};
class ACLID : public XMLObj
{
public:
ACLID() {}
~ACLID() {}
};
class ACLURI : public XMLObj
{
public:
ACLURI() {}
~ACLURI() {}
};
class AccessControlPolicy : public XMLObj
{
public:
AccessControlPolicy() {}
~AccessControlPolicy() {}
};
class S3XMLParser : public XMLObj
{
XML_Parser p;
const char *buf;
XMLObj *cur_obj;
int pos;
public:
S3XMLParser() {}
bool init();
void xml_start(const char *el, const char **attr);
void xml_end(const char *el);
void handle_data(const char *s, int len);
bool parse(const char *buf, int len, int done);
};
void xml_start(void *data, const char *el, const char **attr) {
S3XMLParser *handler = (S3XMLParser *)data;
handler->xml_start(el, attr);
}
void S3XMLParser::xml_start(const char *el, const char **attr) {
XMLObj * obj;
if (strcmp(el, "AccessControlPolicy") == 0) {
obj = new AccessControlPolicy();
} else if (strcmp(el, "ID") == 0) {
obj = new ACLID();
} else if (strcmp(el, "DisplayName") == 0) {
obj = new ACLDisplayName();
} else if (strcmp(el, "Grant") == 0) {
obj = new ACLGrant();
} else if (strcmp(el, "Grantee") == 0) {
obj = new ACLGrantee();
} else if (strcmp(el, "Permission") == 0) {
obj = new ACLPermission();
} else if (strcmp(el, "URI") == 0) {
obj = new ACLURI();
} else {
obj = new XMLObj();
}
obj->xml_start(cur_obj, el, attr);
if (cur_obj) {
cur_obj->add_child(el, obj);
} else {
children.insert(pair<string, XMLObj *>(el, obj));
}
cur_obj = obj;
}
void xml_end(void *data, const char *el) {
S3XMLParser *handler = (S3XMLParser *)data;
handler->xml_end(el);
}
void S3XMLParser::xml_end(const char *el) {
XMLObj *parent_obj = cur_obj->get_parent();
cur_obj->xml_end(el);
cur_obj = parent_obj;
}
void handle_data(void *data, const char *s, int len)
{
S3XMLParser *handler = (S3XMLParser *)data;
handler->handle_data(s, len);
}
void S3XMLParser::handle_data(const char *s, int len)
{
printf(">%.*s\n", len, s);
}
bool S3XMLParser::init()
{
pos = -1;
p = XML_ParserCreate(NULL);
if (!p) {
cerr << "S3XMLParser::init(): ERROR allocating memory" << std::endl;
return false;
}
XML_SetElementHandler(p, ::xml_start, ::xml_end);
XML_SetCharacterDataHandler(p, ::handle_data);
XML_SetUserData(p, (void *)this);
return true;
}
bool S3XMLParser::parse(const char *_buf, int len, int done)
{
buf = _buf;
if (!XML_Parse(p, buf, len, done)) {
fprintf(stderr, "Parse error at line %d:\n%s\n",
XML_GetCurrentLineNumber(p),
XML_ErrorString(XML_GetErrorCode(p)));
return false;
}
return true;
}
#if 0
int main(int argc, char **argv) {
S3XMLParser s3acl;
if (!s3acl.init())
exit(1);
char buf[2048];
for (;;) {
int done;
int len;
len = fread(buf, 1, 2048, stdin);
if (ferror(stdin)) {
fprintf(stderr, "Read error\n");
exit(-1);
}
done = feof(stdin);
s3acl.parse(buf, len, done);
if (done)
break;
}
XMLObjIter iter = s3acl.find("AccessControlPolicy");
AccessControlPolicy *acp = (AccessControlPolicy *)iter.get_next();
cout << (void *)acp << std::endl;
exit(0);
}
#endif
<commit_msg>s3gw: some more acl implementation<commit_after>#include <string.h>
#include <iostream>
#include <vector>
#include <map>
#include "expat.h"
using namespace std;
#define S3_PERM_READ 0x01
#define S3_PERM_WRITE 0x02
#define S3_PERM_READ_ACP 0x04
#define S3_PERM_WRITE_ACP 0x08
#define S3_PERM_FULL_CONTROL ( S3_PERM_READ | S3_PERM_WRITE | \
S3_PERM_READ_ACP | S3_PERM_WRITE_ACP )
class XMLObj;
class XMLObjIter {
map<string, XMLObj *>::iterator cur;
map<string, XMLObj *>::iterator end;
public:
XMLObjIter() {}
void set(map<string, XMLObj *>::iterator& _cur, map<string, XMLObj *>::iterator& _end) { cur = _cur; end = _end; }
XMLObj *get_next() {
XMLObj *obj = NULL;
if (cur != end) {
obj = cur->second;
++cur;
}
return obj;
};
};
class XMLObj
{
XMLObj *parent;
string type;
map<string, string> attr_map;
protected:
string data;
multimap<string, XMLObj *> children;
public:
XMLObj() {}
virtual ~XMLObj() {
multimap<string, XMLObj *>::iterator iter;
for (iter = children.begin(); iter != children.end(); ++iter) {
delete iter->second;
}
}
void xml_start(XMLObj *parent, const char *el, const char **attr) {
this->parent = parent;
type = el;
for (int i = 0; attr[i]; i += 2) {
attr_map[attr[i]] = string(attr[i + 1]);
}
}
virtual void xml_end(const char *el) {}
virtual void xml_handle_data(const char *s, int len) { data = string(s, len); }
string& get_data() { return data; }
XMLObj *get_parent() { return parent; }
void add_child(string el, XMLObj *obj) {
children.insert(pair<string, XMLObj *>(el, obj));
}
XMLObjIter find(string name) {
XMLObjIter iter;
map<string, XMLObj *>::iterator first;
map<string, XMLObj *>::iterator last;
first = children.find(name);
last = children.upper_bound(name);
iter.set(first, last);
return iter;
}
XMLObj *find_first(string name) {
XMLObjIter iter;
map<string, XMLObj *>::iterator first;
first = children.find(name);
if (first != children.end())
return first->second;
return NULL;
}
friend ostream& operator<<(ostream& out, XMLObj& obj);
};
ostream& operator<<(ostream& out, XMLObj& obj) {
out << obj.type << ": " << obj.data;
return out;
}
class ACLOwner : public XMLObj
{
public:
ACLOwner() {}
~ACLOwner() {}
};
class ACLGrantee : public XMLObj
{
public:
ACLGrantee() {}
~ACLGrantee() {}
};
class ACLPermission : public XMLObj
{
int flags;
public:
ACLPermission() : flags(0) {}
~ACLPermission() {}
void xml_end(const char *el) {
const char *s = data.c_str();
if (strcasecmp(s, "READ") == 0) {
flags |= S3_PERM_READ;
} else if (strcasecmp(s, "WRITE") == 0) {
flags |= S3_PERM_WRITE;
} else if (strcasecmp(s, "READ_ACP") == 0) {
flags |= S3_PERM_READ_ACP;
} else if (strcasecmp(s, "WRITE_ACP") == 0) {
flags |= S3_PERM_WRITE_ACP;
} else if (strcasecmp(s, "FULL_CONTROL") == 0) {
flags |= S3_PERM_FULL_CONTROL;
}
}
int get_permissions() { return flags; }
};
class ACLID : public XMLObj
{
public:
ACLID() {}
~ACLID() {}
};
class ACLURI : public XMLObj
{
public:
ACLURI() {}
~ACLURI() {}
};
class ACLDisplayName : public XMLObj
{
public:
ACLDisplayName() {}
~ACLDisplayName() {}
};
class ACLGrant : public XMLObj
{
ACLGrantee *grantee;
ACLID *id;
ACLURI *uri;
ACLPermission *permission;
ACLDisplayName *name;
public:
ACLGrant() : grantee(NULL), id(NULL), uri(NULL), permission(NULL) {}
~ACLGrant() {}
void xml_end(const char *el) {
grantee = (ACLGrantee *)find_first("Grantee");
if (!grantee)
return;
permission = (ACLPermission *)find_first("Permission");
if (!permission)
return;
name = (ACLDisplayName *)grantee->find_first("DisplayName");
id = (ACLID *)grantee->find_first("ID");
if (id) {
cout << "[" << *grantee << ", " << *permission << ", " << *id << ", " << "]" << std::endl;
} else {
uri = (ACLURI *)grantee->find_first("URI");
if (uri)
cout << "[" << *grantee << ", " << *permission << ", " << *uri << "]" << std::endl;
}
}
ACLID *get_id() { return id; }
};
class AccessControlList : public XMLObj
{
multimap<string, ACLGrant *> acl_user_map;
public:
AccessControlList() {}
~AccessControlList() {}
void xml_end(const char *el) {
XMLObjIter iter = find("Grant");
ACLGrant *grant = (ACLGrant *)iter.get_next();
while (grant) {
ACLID *id = (ACLID *)grant->get_id();
if (id) {
acl_user_map.insert(pair<string, ACLGrant *>(id->get_data(), grant));
}
grant = (ACLGrant *)iter.get_next();
}
}
int get_perm(string& id, int perm_mask) {
/* FIXME */
return 0;
}
};
class AccessControlPolicy : public XMLObj
{
AccessControlList *acl;
public:
AccessControlPolicy() : acl(NULL) {}
~AccessControlPolicy() {}
void xml_end(const char *el) {
acl = (AccessControlList *)find_first("AccessControlList");
}
int get_perm(string& id, int perm_mask) {
if (acl)
return acl->get_perm(id, perm_mask);
return 0;
}
};
class S3XMLParser : public XMLObj
{
XML_Parser p;
const char *buf;
XMLObj *cur_obj;
int pos;
public:
S3XMLParser() {}
bool init();
void xml_start(const char *el, const char **attr);
void xml_end(const char *el);
void handle_data(const char *s, int len);
bool parse(const char *buf, int len, int done);
};
void xml_start(void *data, const char *el, const char **attr) {
S3XMLParser *handler = (S3XMLParser *)data;
handler->xml_start(el, attr);
}
void S3XMLParser::xml_start(const char *el, const char **attr) {
XMLObj * obj;
if (strcmp(el, "AccessControlPolicy") == 0) {
obj = new AccessControlPolicy();
} else if (strcmp(el, "ID") == 0) {
obj = new ACLID();
} else if (strcmp(el, "DisplayName") == 0) {
obj = new ACLDisplayName();
} else if (strcmp(el, "Grant") == 0) {
obj = new ACLGrant();
} else if (strcmp(el, "Grantee") == 0) {
obj = new ACLGrantee();
} else if (strcmp(el, "Permission") == 0) {
obj = new ACLPermission();
} else if (strcmp(el, "URI") == 0) {
obj = new ACLURI();
} else {
obj = new XMLObj();
}
obj->xml_start(cur_obj, el, attr);
if (cur_obj) {
cur_obj->add_child(el, obj);
} else {
children.insert(pair<string, XMLObj *>(el, obj));
}
cur_obj = obj;
}
void xml_end(void *data, const char *el) {
S3XMLParser *handler = (S3XMLParser *)data;
handler->xml_end(el);
}
void S3XMLParser::xml_end(const char *el) {
XMLObj *parent_obj = cur_obj->get_parent();
cur_obj->xml_end(el);
cur_obj = parent_obj;
}
void handle_data(void *data, const char *s, int len)
{
S3XMLParser *handler = (S3XMLParser *)data;
handler->handle_data(s, len);
}
void S3XMLParser::handle_data(const char *s, int len)
{
cur_obj->xml_handle_data(s, len);
}
bool S3XMLParser::init()
{
pos = -1;
p = XML_ParserCreate(NULL);
if (!p) {
cerr << "S3XMLParser::init(): ERROR allocating memory" << std::endl;
return false;
}
XML_SetElementHandler(p, ::xml_start, ::xml_end);
XML_SetCharacterDataHandler(p, ::handle_data);
XML_SetUserData(p, (void *)this);
return true;
}
bool S3XMLParser::parse(const char *_buf, int len, int done)
{
buf = _buf;
if (!XML_Parse(p, buf, len, done)) {
fprintf(stderr, "Parse error at line %d:\n%s\n",
XML_GetCurrentLineNumber(p),
XML_ErrorString(XML_GetErrorCode(p)));
return false;
}
return true;
}
#if 0
int main(int argc, char **argv) {
S3XMLParser s3acl;
if (!s3acl.init())
exit(1);
char buf[2048];
for (;;) {
int done;
int len;
len = fread(buf, 1, 2048, stdin);
if (ferror(stdin)) {
fprintf(stderr, "Read error\n");
exit(-1);
}
done = feof(stdin);
s3acl.parse(buf, len, done);
if (done)
break;
}
XMLObjIter iter = s3acl.find("AccessControlPolicy");
AccessControlPolicy *acp = (AccessControlPolicy *)iter.get_next();
while (acp) {
cout << (void *)acp << std::endl;
acp = (AccessControlPolicy *)iter.get_next();
}
exit(0);
}
#endif
<|endoftext|>
|
<commit_before>/*!
\file order_book.cpp
\brief Order book implementation
\author Ivan Shynkarenka
\date 02.08.2017
\copyright MIT License
*/
#include "trader/matching/order_book.h"
namespace CppTrader {
namespace Matching {
OrderBook::~OrderBook()
{
// Release bid price levels
for (auto& bid : _bids)
_level_pool.Release(&bid);
_bids.clear();
// Release ask price levels
for (auto& ask : _asks)
_level_pool.Release(&ask);
_asks.clear();
// Release buy stop orders levels
for (auto& buy_stop : _buy_stop)
_level_pool.Release(&buy_stop);
_buy_stop.clear();
// Release sell stop orders levels
for (auto& sell_stop : _sell_stop)
_level_pool.Release(&sell_stop);
_sell_stop.clear();
}
LevelNode* OrderBook::AddLevel(OrderNode* order_ptr)
{
LevelNode* level_ptr = nullptr;
if (order_ptr->IsBuy())
{
// Create a new price level
level_ptr = _level_pool.Create(LevelType::BID, order_ptr->Price);
// Insert the price level into the bid collection
_bids.insert(*level_ptr);
// Update best bid price level
if ((_best_bid == nullptr) || (level_ptr->Price > _best_bid->Price))
_best_bid = level_ptr;
}
else
{
// Create a new price level
level_ptr = _level_pool.Create(LevelType::ASK, order_ptr->Price);
// Insert the price level into the ask collection
_asks.insert(*level_ptr);
// Update best ask price level
if ((_best_ask == nullptr) || (level_ptr->Price < _best_ask->Price))
_best_ask = level_ptr;
}
return level_ptr;
}
LevelNode* OrderBook::DeleteLevel(OrderNode* order_ptr)
{
// Find the price level for the order
LevelNode* level_ptr = order_ptr->Level;
if (order_ptr->IsBuy())
{
// Update best bid price level
if (level_ptr == _best_bid)
_best_bid = (_best_bid->left != nullptr) ? _best_bid->left : _best_bid->parent;
// Erase the price level from the bid collection
_bids.erase(Levels::iterator(&_bids, level_ptr));
}
else
{
// Update best ask price level
if (level_ptr == _best_ask)
_best_ask = (_best_ask->right != nullptr) ? _best_ask->right : _best_ask->parent;
// Erase the price level from the ask collection
_asks.erase(Levels::iterator(&_asks, level_ptr));
}
// Release the price level
_level_pool.Release(level_ptr);
return nullptr;
}
LevelUpdate OrderBook::AddOrder(OrderNode* order_ptr)
{
// Find the price level for the order
LevelNode* level_ptr = order_ptr->IsBuy() ? (LevelNode*)GetBid(order_ptr->Price) : (LevelNode*)GetAsk(order_ptr->Price);
// Create a new price level if no one found
UpdateType update = UpdateType::UPDATE;
if (level_ptr == nullptr)
{
level_ptr = AddLevel(order_ptr);
update = UpdateType::ADD;
}
// Update the price level volume
level_ptr->TotalVolume += order_ptr->Quantity;
level_ptr->HiddenVolume += order_ptr->HiddenQuantity();
level_ptr->VisibleVolume += order_ptr->VisibleQuantity();
// Link the new order to the orders list of the price level
level_ptr->OrderList.push_back(*order_ptr);
++level_ptr->Orders;
// Cache the price level in the given order
order_ptr->Level = level_ptr;
// Price level was changed. Return top of the book modification flag.
return LevelUpdate(update, *order_ptr->Level, (order_ptr->Level == (order_ptr->IsBuy() ? _best_bid : _best_ask)));
}
LevelUpdate OrderBook::ReduceOrder(OrderNode* order_ptr, uint64_t quantity, uint64_t hidden, uint64_t visible)
{
// Find the price level for the order
LevelNode* level_ptr = order_ptr->Level;
// Update the price level volume
level_ptr->TotalVolume -= quantity;
level_ptr->HiddenVolume -= hidden;
level_ptr->VisibleVolume -= visible;
// Unlink the empty order from the orders list of the price level
if (order_ptr->Quantity == 0)
{
level_ptr->OrderList.pop_current(*order_ptr);
--level_ptr->Orders;
}
Level level(*level_ptr);
// Delete the empty price level
UpdateType update = UpdateType::UPDATE;
if (level_ptr->TotalVolume == 0)
{
// Clear the price level cache in the given order
order_ptr->Level = DeleteLevel(order_ptr);
update = UpdateType::DELETE;
}
// Price level was changed. Return top of the book modification flag.
return LevelUpdate(update, level, (order_ptr->Level == (order_ptr->IsBuy() ? _best_bid : _best_ask)));
}
LevelUpdate OrderBook::DeleteOrder(OrderNode* order_ptr)
{
// Find the price level for the order
LevelNode* level_ptr = order_ptr->Level;
// Update the price level volume
level_ptr->TotalVolume -= order_ptr->Quantity;
level_ptr->HiddenVolume -= order_ptr->HiddenQuantity();
level_ptr->VisibleVolume -= order_ptr->VisibleQuantity();
// Unlink the empty order from the orders list of the price level
level_ptr->OrderList.pop_current(*order_ptr);
--level_ptr->Orders;
Level level(*level_ptr);
// Delete the empty price level
UpdateType update = UpdateType::UPDATE;
if (level_ptr->TotalVolume == 0)
{
// Clear the price level cache in the given order
order_ptr->Level = DeleteLevel(order_ptr);
update = UpdateType::DELETE;
}
// Price level was changed. Return top of the book modification flag.
return LevelUpdate(update, level, (order_ptr->Level == (order_ptr->IsBuy() ? _best_bid : _best_ask)));
}
LevelNode* OrderBook::AddStopLevel(OrderNode* order_ptr)
{
LevelNode* level_ptr = nullptr;
if (order_ptr->IsBuy())
{
// Create a new price level
level_ptr = _level_pool.Create(LevelType::ASK, order_ptr->Price);
// Insert the price level into the buy stop orders collection
_buy_stop.insert(*level_ptr);
}
else
{
// Create a new price level
level_ptr = _level_pool.Create(LevelType::BID, order_ptr->Price);
// Insert the price level into the sell stop orders collection
_sell_stop.insert(*level_ptr);
}
return level_ptr;
}
LevelNode* OrderBook::DeleteStopLevel(OrderNode* order_ptr)
{
// Find the price level for the order
LevelNode* level_ptr = order_ptr->Level;
if (order_ptr->IsBuy())
{
// Erase the price level from the buy stop orders collection
_buy_stop.erase(Levels::iterator(&_buy_stop, level_ptr));
}
else
{
// Erase the price level from the sell stop orders collection
_sell_stop.erase(Levels::iterator(&_sell_stop, level_ptr));
}
// Release the price level
_level_pool.Release(level_ptr);
return nullptr;
}
void OrderBook::AddStopOrder(OrderNode* order_ptr)
{
// Find the price level for the order
LevelNode* level_ptr = order_ptr->IsBuy() ? (LevelNode*)GetBuyStopLevel(order_ptr->Price) : (LevelNode*)GetSellStopLevel(order_ptr->Price);
// Create a new price level if no one found
if (level_ptr == nullptr)
level_ptr = AddLevel(order_ptr);
// Update the price level volume
level_ptr->TotalVolume += order_ptr->Quantity;
level_ptr->HiddenVolume += order_ptr->HiddenQuantity();
level_ptr->VisibleVolume += order_ptr->VisibleQuantity();
// Link the new order to the orders list of the price level
level_ptr->OrderList.push_back(*order_ptr);
++level_ptr->Orders;
// Cache the price level in the given order
order_ptr->Level = level_ptr;
}
void OrderBook::ReduceStopOrder(OrderNode* order_ptr, uint64_t quantity, uint64_t hidden, uint64_t visible)
{
// Find the price level for the order
LevelNode* level_ptr = order_ptr->Level;
// Update the price level volume
level_ptr->TotalVolume -= quantity;
level_ptr->HiddenVolume -= hidden;
level_ptr->VisibleVolume -= visible;
// Unlink the empty order from the orders list of the price level
if (order_ptr->Quantity == 0)
{
level_ptr->OrderList.pop_current(*order_ptr);
--level_ptr->Orders;
}
Level level(*level_ptr);
// Delete the empty price level
if (level_ptr->TotalVolume == 0)
{
// Clear the price level cache in the given order
order_ptr->Level = DeleteLevel(order_ptr);
}
}
void OrderBook::DeleteStopOrder(OrderNode* order_ptr)
{
// Find the price level for the order
LevelNode* level_ptr = order_ptr->Level;
// Update the price level volume
level_ptr->TotalVolume -= order_ptr->Quantity;
level_ptr->HiddenVolume -= order_ptr->HiddenQuantity();
level_ptr->VisibleVolume -= order_ptr->VisibleQuantity();
// Unlink the empty order from the orders list of the price level
level_ptr->OrderList.pop_current(*order_ptr);
--level_ptr->Orders;
Level level(*level_ptr);
// Delete the empty price level
if (level_ptr->TotalVolume == 0)
{
// Clear the price level cache in the given order
order_ptr->Level = DeleteLevel(order_ptr);
}
}
} // namespace Matching
} // namespace CppTrader
<commit_msg>fixes<commit_after>/*!
\file order_book.cpp
\brief Order book implementation
\author Ivan Shynkarenka
\date 02.08.2017
\copyright MIT License
*/
#include "trader/matching/order_book.h"
namespace CppTrader {
namespace Matching {
OrderBook::~OrderBook()
{
// Release bid price levels
for (auto& bid : _bids)
_level_pool.Release(&bid);
_bids.clear();
// Release ask price levels
for (auto& ask : _asks)
_level_pool.Release(&ask);
_asks.clear();
// Release buy stop orders levels
for (auto& buy_stop : _buy_stop)
_level_pool.Release(&buy_stop);
_buy_stop.clear();
// Release sell stop orders levels
for (auto& sell_stop : _sell_stop)
_level_pool.Release(&sell_stop);
_sell_stop.clear();
}
LevelNode* OrderBook::AddLevel(OrderNode* order_ptr)
{
LevelNode* level_ptr = nullptr;
if (order_ptr->IsBuy())
{
// Create a new price level
level_ptr = _level_pool.Create(LevelType::BID, order_ptr->Price);
// Insert the price level into the bid collection
_bids.insert(*level_ptr);
// Update best bid price level
if ((_best_bid == nullptr) || (level_ptr->Price > _best_bid->Price))
_best_bid = level_ptr;
}
else
{
// Create a new price level
level_ptr = _level_pool.Create(LevelType::ASK, order_ptr->Price);
// Insert the price level into the ask collection
_asks.insert(*level_ptr);
// Update best ask price level
if ((_best_ask == nullptr) || (level_ptr->Price < _best_ask->Price))
_best_ask = level_ptr;
}
return level_ptr;
}
LevelNode* OrderBook::DeleteLevel(OrderNode* order_ptr)
{
// Find the price level for the order
LevelNode* level_ptr = order_ptr->Level;
if (order_ptr->IsBuy())
{
// Update best bid price level
if (level_ptr == _best_bid)
_best_bid = (_best_bid->left != nullptr) ? _best_bid->left : _best_bid->parent;
// Erase the price level from the bid collection
_bids.erase(Levels::iterator(&_bids, level_ptr));
}
else
{
// Update best ask price level
if (level_ptr == _best_ask)
_best_ask = (_best_ask->right != nullptr) ? _best_ask->right : _best_ask->parent;
// Erase the price level from the ask collection
_asks.erase(Levels::iterator(&_asks, level_ptr));
}
// Release the price level
_level_pool.Release(level_ptr);
return nullptr;
}
LevelUpdate OrderBook::AddOrder(OrderNode* order_ptr)
{
// Find the price level for the order
LevelNode* level_ptr = order_ptr->IsBuy() ? (LevelNode*)GetBid(order_ptr->Price) : (LevelNode*)GetAsk(order_ptr->Price);
// Create a new price level if no one found
UpdateType update = UpdateType::UPDATE;
if (level_ptr == nullptr)
{
level_ptr = AddLevel(order_ptr);
update = UpdateType::ADD;
}
// Update the price level volume
level_ptr->TotalVolume += order_ptr->Quantity;
level_ptr->HiddenVolume += order_ptr->HiddenQuantity();
level_ptr->VisibleVolume += order_ptr->VisibleQuantity();
// Link the new order to the orders list of the price level
level_ptr->OrderList.push_back(*order_ptr);
++level_ptr->Orders;
// Cache the price level in the given order
order_ptr->Level = level_ptr;
// Price level was changed. Return top of the book modification flag.
return LevelUpdate(update, *order_ptr->Level, (order_ptr->Level == (order_ptr->IsBuy() ? _best_bid : _best_ask)));
}
LevelUpdate OrderBook::ReduceOrder(OrderNode* order_ptr, uint64_t quantity, uint64_t hidden, uint64_t visible)
{
// Find the price level for the order
LevelNode* level_ptr = order_ptr->Level;
// Update the price level volume
level_ptr->TotalVolume -= quantity;
level_ptr->HiddenVolume -= hidden;
level_ptr->VisibleVolume -= visible;
// Unlink the empty order from the orders list of the price level
if (order_ptr->Quantity == 0)
{
level_ptr->OrderList.pop_current(*order_ptr);
--level_ptr->Orders;
}
Level level(*level_ptr);
// Delete the empty price level
UpdateType update = UpdateType::UPDATE;
if (level_ptr->TotalVolume == 0)
{
// Clear the price level cache in the given order
order_ptr->Level = DeleteLevel(order_ptr);
update = UpdateType::DELETE;
}
// Price level was changed. Return top of the book modification flag.
return LevelUpdate(update, level, (order_ptr->Level == (order_ptr->IsBuy() ? _best_bid : _best_ask)));
}
LevelUpdate OrderBook::DeleteOrder(OrderNode* order_ptr)
{
// Find the price level for the order
LevelNode* level_ptr = order_ptr->Level;
// Update the price level volume
level_ptr->TotalVolume -= order_ptr->Quantity;
level_ptr->HiddenVolume -= order_ptr->HiddenQuantity();
level_ptr->VisibleVolume -= order_ptr->VisibleQuantity();
// Unlink the empty order from the orders list of the price level
level_ptr->OrderList.pop_current(*order_ptr);
--level_ptr->Orders;
Level level(*level_ptr);
// Delete the empty price level
UpdateType update = UpdateType::UPDATE;
if (level_ptr->TotalVolume == 0)
{
// Clear the price level cache in the given order
order_ptr->Level = DeleteLevel(order_ptr);
update = UpdateType::DELETE;
}
// Price level was changed. Return top of the book modification flag.
return LevelUpdate(update, level, (order_ptr->Level == (order_ptr->IsBuy() ? _best_bid : _best_ask)));
}
LevelNode* OrderBook::AddStopLevel(OrderNode* order_ptr)
{
LevelNode* level_ptr = nullptr;
if (order_ptr->IsBuy())
{
// Create a new price level
level_ptr = _level_pool.Create(LevelType::ASK, order_ptr->Price);
// Insert the price level into the buy stop orders collection
_buy_stop.insert(*level_ptr);
}
else
{
// Create a new price level
level_ptr = _level_pool.Create(LevelType::BID, order_ptr->Price);
// Insert the price level into the sell stop orders collection
_sell_stop.insert(*level_ptr);
}
return level_ptr;
}
LevelNode* OrderBook::DeleteStopLevel(OrderNode* order_ptr)
{
// Find the price level for the order
LevelNode* level_ptr = order_ptr->Level;
if (order_ptr->IsBuy())
{
// Erase the price level from the buy stop orders collection
_buy_stop.erase(Levels::iterator(&_buy_stop, level_ptr));
}
else
{
// Erase the price level from the sell stop orders collection
_sell_stop.erase(Levels::iterator(&_sell_stop, level_ptr));
}
// Release the price level
_level_pool.Release(level_ptr);
return nullptr;
}
void OrderBook::AddStopOrder(OrderNode* order_ptr)
{
// Find the price level for the order
LevelNode* level_ptr = order_ptr->IsBuy() ? (LevelNode*)GetBuyStopLevel(order_ptr->Price) : (LevelNode*)GetSellStopLevel(order_ptr->Price);
// Create a new price level if no one found
if (level_ptr == nullptr)
level_ptr = AddLevel(order_ptr);
// Update the price level volume
level_ptr->TotalVolume += order_ptr->Quantity;
level_ptr->HiddenVolume += order_ptr->HiddenQuantity();
level_ptr->VisibleVolume += order_ptr->VisibleQuantity();
// Link the new order to the orders list of the price level
level_ptr->OrderList.push_back(*order_ptr);
++level_ptr->Orders;
// Cache the price level in the given order
order_ptr->Level = level_ptr;
}
void OrderBook::ReduceStopOrder(OrderNode* order_ptr, uint64_t quantity, uint64_t hidden, uint64_t visible)
{
// Find the price level for the order
LevelNode* level_ptr = order_ptr->Level;
// Update the price level volume
level_ptr->TotalVolume -= quantity;
level_ptr->HiddenVolume -= hidden;
level_ptr->VisibleVolume -= visible;
// Unlink the empty order from the orders list of the price level
if (order_ptr->Quantity == 0)
{
level_ptr->OrderList.pop_current(*order_ptr);
--level_ptr->Orders;
}
// Delete the empty price level
if (level_ptr->TotalVolume == 0)
{
// Clear the price level cache in the given order
order_ptr->Level = DeleteLevel(order_ptr);
}
}
void OrderBook::DeleteStopOrder(OrderNode* order_ptr)
{
// Find the price level for the order
LevelNode* level_ptr = order_ptr->Level;
// Update the price level volume
level_ptr->TotalVolume -= order_ptr->Quantity;
level_ptr->HiddenVolume -= order_ptr->HiddenQuantity();
level_ptr->VisibleVolume -= order_ptr->VisibleQuantity();
// Unlink the empty order from the orders list of the price level
level_ptr->OrderList.pop_current(*order_ptr);
--level_ptr->Orders;
// Delete the empty price level
if (level_ptr->TotalVolume == 0)
{
// Clear the price level cache in the given order
order_ptr->Level = DeleteLevel(order_ptr);
}
}
} // namespace Matching
} // namespace CppTrader
<|endoftext|>
|
<commit_before>#include "CodeGen_X86.h"
#include "IROperator.h"
#include <iostream>
#include "buffer_t.h"
#include "IRPrinter.h"
#include "IRMatch.h"
#include "Log.h"
#include "Util.h"
#include "Var.h"
#include "Param.h"
#include "integer_division_table.h"
// No msvc warnings from llvm headers please
#ifdef _WIN32
#pragma warning(push, 0)
#endif
#include <llvm/Config/config.h>
// Temporary affordance to compile with both llvm 3.2 and 3.3.
// Protected as at least one installation of llvm elides version macros.
#if defined(LLVM_VERSION_MINOR) && LLVM_VERSION_MINOR < 3
#include <llvm/Value.h>
#include <llvm/Module.h>
#include <llvm/Function.h>
#include <llvm/TargetTransformInfo.h>
#include <llvm/DataLayout.h>
#include <llvm/IRBuilder.h>
#include <llvm/Attributes.h>
#include <llvm/Support/IRReader.h>
// They renamed this type in 3.3
typedef llvm::Attributes Attribute;
typedef llvm::Attributes::AttrVal AttrKind;
#include <llvm/Support/IRReader.h>
#else
#include <llvm/IR/Value.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Function.h>
#include <llvm/Analysis/TargetTransformInfo.h>
#include <llvm/IR/DataLayout.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/Attributes.h>
#include <llvm/Bitcode/ReaderWriter.h>
typedef llvm::Attribute::AttrKind AttrKind;
#endif
#include <llvm/Support/MemoryBuffer.h>
// No msvc warnings from llvm headers please
#ifdef _WIN32
#pragma warning(pop)
#endif
namespace Halide {
namespace Internal {
using std::vector;
using std::string;
using namespace llvm;
class LLVMAPIAttributeAdapter {
LLVMContext &llvm_context;
AttrKind kind;
public:
LLVMAPIAttributeAdapter(LLVMContext &context, AttrKind kind_arg) :
llvm_context(context), kind(kind_arg)
{
}
operator AttrKind() { return kind; }
operator Attribute() { return Attribute::get(llvm_context, kind); }
};
CodeGen_Posix::CodeGen_Posix() : CodeGen() {
i8x8 = VectorType::get(i8, 8);
i8x16 = VectorType::get(i8, 16);
i8x32 = VectorType::get(i8, 32);
i16x4 = VectorType::get(i16, 4);
i16x8 = VectorType::get(i16, 8);
i16x16 = VectorType::get(i16, 16);
i32x2 = VectorType::get(i32, 2);
i32x4 = VectorType::get(i32, 4);
i32x8 = VectorType::get(i32, 8);
i64x2 = VectorType::get(i64, 2);
i64x4 = VectorType::get(i64, 4);
f32x2 = VectorType::get(f32, 2);
f32x4 = VectorType::get(f32, 4);
f32x8 = VectorType::get(f32, 8);
f64x2 = VectorType::get(f64, 2);
f64x4 = VectorType::get(f64, 4);
wild_i8x8 = new Variable(Int(8, 8), "*");
wild_i8x16 = new Variable(Int(8, 16), "*");
wild_i8x32 = new Variable(Int(8, 32), "*");
wild_u8x8 = new Variable(UInt(8, 8), "*");
wild_u8x16 = new Variable(UInt(8, 16), "*");
wild_u8x32 = new Variable(UInt(8, 32), "*");
wild_i16x4 = new Variable(Int(16, 4), "*");
wild_i16x8 = new Variable(Int(16, 8), "*");
wild_i16x16 = new Variable(Int(16, 16), "*");
wild_u16x4 = new Variable(UInt(16, 4), "*");
wild_u16x8 = new Variable(UInt(16, 8), "*");
wild_u16x16 = new Variable(UInt(16, 16), "*");
wild_i32x2 = new Variable(Int(32, 2), "*");
wild_i32x4 = new Variable(Int(32, 4), "*");
wild_i32x8 = new Variable(Int(32, 8), "*");
wild_u32x2 = new Variable(UInt(32, 2), "*");
wild_u32x4 = new Variable(UInt(32, 4), "*");
wild_u32x8 = new Variable(UInt(32, 8), "*");
wild_u64x2 = new Variable(UInt(64, 2), "*");
wild_i64x2 = new Variable(Int(64, 2), "*");
wild_u64x4 = new Variable(UInt(64, 4), "*");
wild_i64x4 = new Variable(Int(64, 4), "*");
wild_f32x2 = new Variable(Float(32, 2), "*");
wild_f32x4 = new Variable(Float(32, 4), "*");
wild_f32x8 = new Variable(Float(32, 8), "*");
wild_f64x2 = new Variable(Float(64, 2), "*");
wild_f64x4 = new Variable(Float(64, 4), "*");
max_i8 = Int(8).max();
min_i8 = Int(8).min();
max_i16 = Int(16).max();
min_i16 = Int(16).min();
max_i32 = Int(32).max();
min_i32 = Int(32).min();
max_i64 = Int(64).max();
min_i64 = Int(64).min();
max_u8 = UInt(8).max();
max_u16 = UInt(16).max();
max_u32 = UInt(32).max();
max_u64 = UInt(64).max();
max_f32 = Float(32).max();
min_f32 = Float(32).min();
max_f64 = Float(64).max();
min_f64 = Float(64).min();
}
void CodeGen_Posix::visit(const Allocate *alloc) {
// Allocate anything less than 32k on the stack
int bytes_per_element = alloc->type.bits / 8;
int stack_size = 0;
bool on_stack = false;
if (const IntImm *size = alloc->size.as<IntImm>()) {
stack_size = size->value;
on_stack = stack_size < 32*1024;
}
Value *size = codegen(alloc->size * bytes_per_element);
llvm::Type *llvm_type = llvm_type_of(alloc->type);
Value *ptr;
Value *saved_stack = NULL;
// In the future, we may want to construct an entire buffer_t here
string allocation_name = alloc->name + ".host";
log(3) << "Pushing allocation called " << allocation_name << " onto the symbol table\n";
if (on_stack) {
// TODO: Optimize to do only one stack pointer save per loop scope.
llvm::Function *stacksave =
llvm::Intrinsic::getDeclaration(module, llvm::Intrinsic::stacksave,
ArrayRef<llvm::Type*>());
saved_stack = builder->CreateCall(stacksave);
// Do a 32-byte aligned alloca
int total_bytes = stack_size * bytes_per_element;
int chunks = (total_bytes + 31)/32;
ptr = builder->CreateAlloca(i32x8, ConstantInt::get(i32, chunks));
ptr = builder->CreatePointerCast(ptr, llvm_type->getPointerTo());
} else {
// call malloc
llvm::Function *malloc_fn = module->getFunction("halide_malloc");
// Make the return value as noalias
malloc_fn->setDoesNotAlias(0);
assert(malloc_fn && "Could not find halide_malloc in module");
Value *sz = builder->CreateIntCast(size, malloc_fn->arg_begin()->getType(), false);
log(4) << "Creating call to halide_malloc\n";
CallInst *call = builder->CreateCall(malloc_fn, sz);
mark_call_return_no_alias(call, context);
ptr = call;
heap_allocations.push_back(ptr);
}
sym_push(allocation_name, ptr);
codegen(alloc->body);
sym_pop(allocation_name);
if (!on_stack) {
heap_allocations.pop_back();
// call free
llvm::Function *free_fn = module->getFunction("halide_free");
assert(free_fn && "Could not find halide_free in module");
log(4) << "Creating call to halide_free\n";
CallInst *call = builder->CreateCall(free_fn, ptr);
mark_call_parameter_no_capture(call, 1, context);
} else {
llvm::Function *stackrestore =
llvm::Intrinsic::getDeclaration(module, llvm::Intrinsic::stackrestore,
ArrayRef<llvm::Type*>());
builder->CreateCall(stackrestore, saved_stack);
}
}
void CodeGen_Posix::prepare_for_early_exit() {
llvm::Function *free_fn = module->getFunction("halide_free");
assert(free_fn && "Could not find halide_free in module");
for (size_t i = 0; i < heap_allocations.size(); i++) {
// TODO: What if I'm inside a parallel for loop?
builder->CreateCall(free_fn, heap_allocations[i]);
}
}
}}
<commit_msg>include fix for llvm 3.2<commit_after>#include "CodeGen_X86.h"
#include "IROperator.h"
#include <iostream>
#include "buffer_t.h"
#include "IRPrinter.h"
#include "IRMatch.h"
#include "Log.h"
#include "Util.h"
#include "Var.h"
#include "Param.h"
#include "integer_division_table.h"
// No msvc warnings from llvm headers please
#ifdef _WIN32
#pragma warning(push, 0)
#endif
#include <llvm/Config/config.h>
// Temporary affordance to compile with both llvm 3.2 and 3.3.
// Protected as at least one installation of llvm elides version macros.
#if defined(LLVM_VERSION_MINOR) && LLVM_VERSION_MINOR < 3
#include <llvm/Value.h>
#include <llvm/Module.h>
#include <llvm/Function.h>
#include <llvm/TargetTransformInfo.h>
#include <llvm/DataLayout.h>
#include <llvm/IRBuilder.h>
#include <llvm/Attributes.h>
#include <llvm/Support/IRReader.h>
#include <llvm/Support/IRReader.h>
#include <llvm/Intrinsics.h>
// They renamed this type in 3.3
typedef llvm::Attributes Attribute;
typedef llvm::Attributes::AttrVal AttrKind;
#else
#include <llvm/IR/Value.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Function.h>
#include <llvm/Analysis/TargetTransformInfo.h>
#include <llvm/IR/DataLayout.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/Attributes.h>
#include <llvm/Bitcode/ReaderWriter.h>
#include <llvm/IR/Intrinsics.h>
typedef llvm::Attribute::AttrKind AttrKind;
#endif
#include <llvm/Support/MemoryBuffer.h>
// No msvc warnings from llvm headers please
#ifdef _WIN32
#pragma warning(pop)
#endif
namespace Halide {
namespace Internal {
using std::vector;
using std::string;
using namespace llvm;
class LLVMAPIAttributeAdapter {
LLVMContext &llvm_context;
AttrKind kind;
public:
LLVMAPIAttributeAdapter(LLVMContext &context, AttrKind kind_arg) :
llvm_context(context), kind(kind_arg)
{
}
operator AttrKind() { return kind; }
operator Attribute() { return Attribute::get(llvm_context, kind); }
};
CodeGen_Posix::CodeGen_Posix() : CodeGen() {
i8x8 = VectorType::get(i8, 8);
i8x16 = VectorType::get(i8, 16);
i8x32 = VectorType::get(i8, 32);
i16x4 = VectorType::get(i16, 4);
i16x8 = VectorType::get(i16, 8);
i16x16 = VectorType::get(i16, 16);
i32x2 = VectorType::get(i32, 2);
i32x4 = VectorType::get(i32, 4);
i32x8 = VectorType::get(i32, 8);
i64x2 = VectorType::get(i64, 2);
i64x4 = VectorType::get(i64, 4);
f32x2 = VectorType::get(f32, 2);
f32x4 = VectorType::get(f32, 4);
f32x8 = VectorType::get(f32, 8);
f64x2 = VectorType::get(f64, 2);
f64x4 = VectorType::get(f64, 4);
wild_i8x8 = new Variable(Int(8, 8), "*");
wild_i8x16 = new Variable(Int(8, 16), "*");
wild_i8x32 = new Variable(Int(8, 32), "*");
wild_u8x8 = new Variable(UInt(8, 8), "*");
wild_u8x16 = new Variable(UInt(8, 16), "*");
wild_u8x32 = new Variable(UInt(8, 32), "*");
wild_i16x4 = new Variable(Int(16, 4), "*");
wild_i16x8 = new Variable(Int(16, 8), "*");
wild_i16x16 = new Variable(Int(16, 16), "*");
wild_u16x4 = new Variable(UInt(16, 4), "*");
wild_u16x8 = new Variable(UInt(16, 8), "*");
wild_u16x16 = new Variable(UInt(16, 16), "*");
wild_i32x2 = new Variable(Int(32, 2), "*");
wild_i32x4 = new Variable(Int(32, 4), "*");
wild_i32x8 = new Variable(Int(32, 8), "*");
wild_u32x2 = new Variable(UInt(32, 2), "*");
wild_u32x4 = new Variable(UInt(32, 4), "*");
wild_u32x8 = new Variable(UInt(32, 8), "*");
wild_u64x2 = new Variable(UInt(64, 2), "*");
wild_i64x2 = new Variable(Int(64, 2), "*");
wild_u64x4 = new Variable(UInt(64, 4), "*");
wild_i64x4 = new Variable(Int(64, 4), "*");
wild_f32x2 = new Variable(Float(32, 2), "*");
wild_f32x4 = new Variable(Float(32, 4), "*");
wild_f32x8 = new Variable(Float(32, 8), "*");
wild_f64x2 = new Variable(Float(64, 2), "*");
wild_f64x4 = new Variable(Float(64, 4), "*");
max_i8 = Int(8).max();
min_i8 = Int(8).min();
max_i16 = Int(16).max();
min_i16 = Int(16).min();
max_i32 = Int(32).max();
min_i32 = Int(32).min();
max_i64 = Int(64).max();
min_i64 = Int(64).min();
max_u8 = UInt(8).max();
max_u16 = UInt(16).max();
max_u32 = UInt(32).max();
max_u64 = UInt(64).max();
max_f32 = Float(32).max();
min_f32 = Float(32).min();
max_f64 = Float(64).max();
min_f64 = Float(64).min();
}
void CodeGen_Posix::visit(const Allocate *alloc) {
// Allocate anything less than 32k on the stack
int bytes_per_element = alloc->type.bits / 8;
int stack_size = 0;
bool on_stack = false;
if (const IntImm *size = alloc->size.as<IntImm>()) {
stack_size = size->value;
on_stack = stack_size < 32*1024;
}
Value *size = codegen(alloc->size * bytes_per_element);
llvm::Type *llvm_type = llvm_type_of(alloc->type);
Value *ptr;
Value *saved_stack = NULL;
// In the future, we may want to construct an entire buffer_t here
string allocation_name = alloc->name + ".host";
log(3) << "Pushing allocation called " << allocation_name << " onto the symbol table\n";
if (on_stack) {
// TODO: Optimize to do only one stack pointer save per loop scope.
llvm::Function *stacksave =
llvm::Intrinsic::getDeclaration(module, llvm::Intrinsic::stacksave,
ArrayRef<llvm::Type*>());
saved_stack = builder->CreateCall(stacksave);
// Do a 32-byte aligned alloca
int total_bytes = stack_size * bytes_per_element;
int chunks = (total_bytes + 31)/32;
ptr = builder->CreateAlloca(i32x8, ConstantInt::get(i32, chunks));
ptr = builder->CreatePointerCast(ptr, llvm_type->getPointerTo());
} else {
// call malloc
llvm::Function *malloc_fn = module->getFunction("halide_malloc");
// Make the return value as noalias
malloc_fn->setDoesNotAlias(0);
assert(malloc_fn && "Could not find halide_malloc in module");
Value *sz = builder->CreateIntCast(size, malloc_fn->arg_begin()->getType(), false);
log(4) << "Creating call to halide_malloc\n";
CallInst *call = builder->CreateCall(malloc_fn, sz);
mark_call_return_no_alias(call, context);
ptr = call;
heap_allocations.push_back(ptr);
}
sym_push(allocation_name, ptr);
codegen(alloc->body);
sym_pop(allocation_name);
if (!on_stack) {
heap_allocations.pop_back();
// call free
llvm::Function *free_fn = module->getFunction("halide_free");
assert(free_fn && "Could not find halide_free in module");
log(4) << "Creating call to halide_free\n";
CallInst *call = builder->CreateCall(free_fn, ptr);
mark_call_parameter_no_capture(call, 1, context);
} else {
llvm::Function *stackrestore =
llvm::Intrinsic::getDeclaration(module, llvm::Intrinsic::stackrestore,
ArrayRef<llvm::Type*>());
builder->CreateCall(stackrestore, saved_stack);
}
}
void CodeGen_Posix::prepare_for_early_exit() {
llvm::Function *free_fn = module->getFunction("halide_free");
assert(free_fn && "Could not find halide_free in module");
for (size_t i = 0; i < heap_allocations.size(); i++) {
// TODO: What if I'm inside a parallel for loop?
builder->CreateCall(free_fn, heap_allocations[i]);
}
}
}}
<|endoftext|>
|
<commit_before>/*
Copyright 2011-2017 Frederic Langlet
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 <iostream>
#include <fstream>
#include <ctime>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include "../types.hpp"
#include "../transform/MTFT.hpp"
using namespace std;
using namespace kanzi;
void testMTFTCorrectness()
{
// Test behavior
cout << "MTFT Correctness test" << endl;
srand((uint)time(nullptr));
for (int ii = 0; ii < 20; ii++) {
byte val[32];
int size = 32;
if (ii == 0) {
byte val2[] = { 5, 2, 4, 7, 0, 0, 7, 1, 7 };
size = 32;
memcpy(val, &val2[0], size);
}
else {
for (int i = 0; i < 32; i++)
val[i] = (byte)(65 + (rand() % (5 * ii)));
}
MTFT mtft;
byte* input = &val[0];
byte* transform = new byte[size + 20];
byte* reverse = new byte[size];
cout << endl
<< "Test " << (ii + 1);
cout << endl
<< "Input : ";
for (int i = 0; i < size; i++)
cout << (input[i] & 0xFF) << " ";
int start = (ii & 1) * ii;
SliceArray<byte> ia1(input, size, 0);
SliceArray<byte> ia2(transform, size + 20, start);
mtft.forward(ia1, ia2, size);
cout << endl
<< "Transform : ";
for (int i = start; i < start + size; i++)
cout << (transform[i] & 0xFF) << " ";
SliceArray<byte> ia3(reverse, size, 0);
ia2._index = start;
mtft.inverse(ia2, ia3, size);
bool ok = true;
cout << endl
<< "Reverse : ";
for (int i = 0; i < size; i++)
cout << (reverse[i] & 0xFF) << " ";
for (int j = 0; j < size; j++) {
if (input[j] != reverse[j]) {
ok = false;
break;
}
}
cout << endl;
cout << ((ok) ? "Identical" : "Different") << endl;
delete[] transform;
delete[] reverse;
}
}
int testMTFTSpeed()
{
// Test speed
int iter = 20000;
int size = 10000;
cout << endl
<< endl
<< "MTFT Speed test" << endl;
cout << "Iterations: " << iter << endl;
srand((uint)time(nullptr));
for (int jj = 0; jj < 4; jj++) {
byte input[20000];
byte output[20000];
byte reverse[20000];
MTFT mtft;
double delta1 = 0, delta2 = 0;
if (jj == 0) {
cout << endl
<< endl
<< "Purely random input" << endl;
}
if (jj == 2) {
cout << endl
<< endl
<< "Semi random input" << endl;
}
for (int ii = 0; ii < iter; ii++) {
for (int i = 0; i < size; i++) {
int n = 128;
if (jj < 2) {
// Pure random
input[i] = byte(rand() % 256);
}
else {
// Semi random (a bit more realistic input)
int rng = 5;
if ((i & 7) == 0) {
rng = 128;
}
int p = ((rand() % rng) - rng / 2 + n) & 0xFF;
input[i] = (byte)p;
n = p;
}
}
SliceArray<byte> ia1(input, size, 0);
SliceArray<byte> ia2(output, size, 0);
SliceArray<byte> ia3(reverse, size, 0);
clock_t before1 = clock();
mtft.forward(ia1, ia2, size);
clock_t after1 = clock();
delta1 += (after1 - before1);
clock_t before2 = clock();
ia2._index = 0;
mtft.inverse(ia2, ia3, size);
clock_t after2 = clock();
delta2 += (after2 - before2);
// Sanity check
int idx = -1;
for (int i = 0; i < size; i++) {
if (input[i] != reverse[i]) {
idx = i;
break;
}
if (idx >= 0) {
cout << "Failure at index " << i << " (" << (int)input[i] << "<->" << (int)reverse[i] << ")" << endl;
break;
}
}
}
double prod = (double)iter * (double)size;
double b2KB = (double)1 / (double)1024;
double d1_sec = (double)delta1 / CLOCKS_PER_SEC;
double d2_sec = (double)delta2 / CLOCKS_PER_SEC;
cout << "MTFT Forward transform [ms]: " << (int)(d1_sec * 1000) << endl;
cout << "Throughput [KB/s] : " << (int)(prod * b2KB / d1_sec) << endl;
cout << "MTFT Reverse transform [ms]: " << (int)(d2_sec * 1000) << endl;
cout << "Throughput [KB/s] : " << (int)(prod * b2KB / d2_sec) << endl;
cout << endl;
}
return 0;
}
#ifdef __GNUG__
int main(int, const char**)
#else
int TestMTFT_main(int, const char**)
#endif
{
testMTFTCorrectness();
testMTFTSpeed();
return 0;
}
<commit_msg>Fix data init in correctness test.<commit_after>/*
Copyright 2011-2017 Frederic Langlet
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 <iostream>
#include <fstream>
#include <ctime>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include "../types.hpp"
#include "../transform/MTFT.hpp"
using namespace std;
using namespace kanzi;
void testMTFTCorrectness()
{
// Test behavior
cout << "MTFT Correctness test" << endl;
srand(uint(time(nullptr)));
for (int ii = 0; ii < 20; ii++) {
byte val[32];
int size = 32;
if (ii == 0) {
byte val2[] = { 5, 2, 4, 7, 0, 0, 7, 1, 7 };
size = 32;
memset(&val[0], 0, size);
memcpy(&val[0], &val2[0], 9);
}
else {
for (int i = 0; i < 32; i++)
val[i] = byte(65 + (rand() % (5 * ii)));
}
MTFT mtft;
byte* input = &val[0];
byte* transform = new byte[size + 20];
byte* reverse = new byte[size];
cout << endl
<< "Test " << (ii + 1);
cout << endl
<< "Input : ";
for (int i = 0; i < size; i++)
cout << (input[i] & 0xFF) << " ";
int start = (ii & 1) * ii;
SliceArray<byte> ia1(input, size, 0);
SliceArray<byte> ia2(transform, size + 20, start);
mtft.forward(ia1, ia2, size);
cout << endl
<< "Transform : ";
for (int i = start; i < start + size; i++)
cout << (transform[i] & 0xFF) << " ";
SliceArray<byte> ia3(reverse, size, 0);
ia2._index = start;
mtft.inverse(ia2, ia3, size);
bool ok = true;
cout << endl
<< "Reverse : ";
for (int i = 0; i < size; i++)
cout << (reverse[i] & 0xFF) << " ";
for (int j = 0; j < size; j++) {
if (input[j] != reverse[j]) {
ok = false;
break;
}
}
cout << endl;
cout << ((ok) ? "Identical" : "Different") << endl;
delete[] transform;
delete[] reverse;
}
}
int testMTFTSpeed()
{
// Test speed
int iter = 20000;
int size = 10000;
cout << endl
<< endl
<< "MTFT Speed test" << endl;
cout << "Iterations: " << iter << endl;
srand(uint(time(nullptr)));
for (int jj = 0; jj < 4; jj++) {
byte input[20000];
byte output[20000];
byte reverse[20000];
MTFT mtft;
double delta1 = 0, delta2 = 0;
if (jj == 0) {
cout << endl
<< endl
<< "Purely random input" << endl;
}
if (jj == 2) {
cout << endl
<< endl
<< "Semi random input" << endl;
}
for (int ii = 0; ii < iter; ii++) {
for (int i = 0; i < size; i++) {
int n = 128;
if (jj < 2) {
// Pure random
input[i] = byte(rand() % 256);
}
else {
// Semi random (a bit more realistic input)
int rng = 5;
if ((i & 7) == 0) {
rng = 128;
}
int p = ((rand() % rng) - rng / 2 + n) & 0xFF;
input[i] = (byte)p;
n = p;
}
}
SliceArray<byte> ia1(input, size, 0);
SliceArray<byte> ia2(output, size, 0);
SliceArray<byte> ia3(reverse, size, 0);
clock_t before1 = clock();
mtft.forward(ia1, ia2, size);
clock_t after1 = clock();
delta1 += (after1 - before1);
clock_t before2 = clock();
ia2._index = 0;
mtft.inverse(ia2, ia3, size);
clock_t after2 = clock();
delta2 += (after2 - before2);
// Sanity check
int idx = -1;
for (int i = 0; i < size; i++) {
if (input[i] != reverse[i]) {
idx = i;
break;
}
if (idx >= 0) {
cout << "Failure at index " << i << " (" << (int)input[i] << "<->" << (int)reverse[i] << ")" << endl;
break;
}
}
}
double prod = double(iter) * double(size);
double b2KB = double(1) / double(1024);
double d1_sec = double(delta1) / CLOCKS_PER_SEC;
double d2_sec = double(delta2) / CLOCKS_PER_SEC;
cout << "MTFT Forward transform [ms]: " << int(d1_sec * 1000) << endl;
cout << "Throughput [KB/s] : " << int(prod * b2KB / d1_sec) << endl;
cout << "MTFT Reverse transform [ms]: " << int(d2_sec * 1000) << endl;
cout << "Throughput [KB/s] : " << int(prod * b2KB / d2_sec) << endl;
cout << endl;
}
return 0;
}
#ifdef __GNUG__
int main(int, const char**)
#else
int TestMTFT_main(int, const char**)
#endif
{
testMTFTCorrectness();
testMTFTSpeed();
return 0;
}
<|endoftext|>
|
<commit_before>/* $Id$ */
# ifndef CPPAD_HASH_CODE_INCLUDED
# define CPPAD_HASH_CODE_INCLUDED
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-09 Bradley M. Bell
CppAD is distributed under multiple licenses. This distribution is under
the terms of the
Common Public License Version 1.0.
A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */
/*!
file hash_code.cpp
A General Purpose hashing utility.
*/
/*!
\def CPPAD_HASH_TABLE_SIZE
the codes retruned by hash_code are between zero and CPPAD_HASH_TABLE_SIZE
minus one.
*/
# define CPPAD_HASH_TABLE_SIZE 65536
CPPAD_BEGIN_NAMESPACE
/*!
Returns a hash code for an arbitrary value.
\tparam Value
is the type of the argument being hash coded.
It should be a plain old data class; i.e.,
the values included in the equality operator in the object and
not pointed to by the object.
\param value
the value that we are generating a hash code for.
\return
is a hash code that is between zero and CPPAD_HASH_TABLE_SIZE - 1.
\par Restrictions
It is assumed (and checked when NDEBUG is not defined) that the
$codei%sizeof(%Value%)%$$ is even and that
$code sizeof(unsigned short)$$ is equal to two.
*/
template <class Value>
unsigned short hash_code(const Value& value)
{ CPPAD_ASSERT_UNKNOWN( sizeof(unsigned short) == 2 );
static unsigned short n = sizeof(value) / 2;
CPPAD_ASSERT_UNKNOWN( sizeof(value) == 2 * n );
const unsigned short* v;
size_t i;
unsigned short code;
v = reinterpret_cast<const unsigned short*>(& value);
i = n;
code = v[i];
while(i--)
code += v[i];
return code;
}
CPPAD_END_NAMESPACE
# endif
<commit_msg>trunk: Fix bug in hash code function.<commit_after>/* $Id$ */
# ifndef CPPAD_HASH_CODE_INCLUDED
# define CPPAD_HASH_CODE_INCLUDED
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-09 Bradley M. Bell
CppAD is distributed under multiple licenses. This distribution is under
the terms of the
Common Public License Version 1.0.
A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */
/*!
file hash_code.cpp
A General Purpose hashing utility.
*/
/*!
\def CPPAD_HASH_TABLE_SIZE
the codes retruned by hash_code are between zero and CPPAD_HASH_TABLE_SIZE
minus one.
*/
# define CPPAD_HASH_TABLE_SIZE 65536
CPPAD_BEGIN_NAMESPACE
/*!
Returns a hash code for an arbitrary value.
\tparam Value
is the type of the argument being hash coded.
It should be a plain old data class; i.e.,
the values included in the equality operator in the object and
not pointed to by the object.
\param value
the value that we are generating a hash code for.
\return
is a hash code that is between zero and CPPAD_HASH_TABLE_SIZE - 1.
\par Restrictions
It is assumed (and checked when NDEBUG is not defined) that the
$codei%sizeof(%Value%)%$$ is even and that
$code sizeof(unsigned short)$$ is equal to two.
*/
template <class Value>
unsigned short hash_code(const Value& value)
{ CPPAD_ASSERT_UNKNOWN( sizeof(unsigned short) == 2 );
static unsigned short n = sizeof(value) / 2;
CPPAD_ASSERT_UNKNOWN( sizeof(value) == 2 * n );
const unsigned short* v;
size_t i;
unsigned short code;
v = reinterpret_cast<const unsigned short*>(& value);
i = n - 1;
code = v[i];
while(i--)
code += v[i];
return code;
}
CPPAD_END_NAMESPACE
# endif
<|endoftext|>
|
<commit_before>/*********************************************************************************************
This file is part of the PSOPT library, a software tool for computational optimal control
Copyright (C) 2009-2020 Victor M. Becerra
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 Street, Fifth Floor, Boston, MA 02110-1301 USA,
or visit http://www.gnu.org/licenses/
Author: Professor Victor M. Becerra
Address: University of Portsmouth
School of Energy and Electronic Engineering
Portsmouth PO1 3DJ
United Kingdom
e-mail: v.m.becerra@ieee.org
**********************************************************************************************/
#include "psopt.h"
void determine_scaling_factors_for_variables(Sol& solution, Prob& problem, Alg& algorithm)
{
// Scaling factors for variables computed automatically given the bound information
// supplied by the user, such that the scaled variables are mostly in the interval [-1,1].
// If, however, any of the variable bounds is 'inf' in magnitude, then the scaled range
// will be [-1, inf], [-inf,1], or [-1, 1]
int i;
for(i=0; i<problem.nphases; i++)
{
int norder = problem.phase[i].current_number_of_intervals;
int ncontrols = problem.phase[i].ncontrols;
int npath = problem.phase[i].npath;
int nstates = problem.phase[i].nstates;
int nevents = problem.phase[i].nevents;
int nparam = problem.phase[i].nparameters;
DMatrix& control_scaling = problem.phase[i].scale.controls;
DMatrix& state_scaling = problem.phase[i].scale.states;
DMatrix& param_scaling = problem.phase[i].scale.parameters;
DMatrix PathJac(npath, nstates+ncontrols);
DMatrix h1(npath,norder+1);
DMatrix h2(npath,norder+1);
DMatrix e1(nevents,1);
DMatrix e2(nevents,2);
DMatrix EventJac1(nevents, nstates+ncontrols);
DMatrix EventJac2(nevents, nstates+ncontrols);
double zlower;
double zupper;
int ii;
// Control scaling:
if ( algorithm.scaling=="automatic" || algorithm.scaling!="user" )
{
control_scaling = ones(ncontrols,1);
for(ii=1;ii<=ncontrols;ii++)
{
zlower = (problem.phase[i].bounds.lower.controls)(ii);
zupper = (problem.phase[i].bounds.upper.controls)(ii);
if ( zlower!=-INF && zupper!= INF ) {
if (zlower !=0.0 || zupper!=0.0)
control_scaling(ii) = 1.0/MAX( fabs(zlower), fabs(zupper));
}
else if (zlower==-INF && zupper!=INF && zupper!=0.0)
control_scaling(ii) = 1.0/fabs(zupper);
else if (zupper==INF && zlower!=-INF && zlower!=0.0)
control_scaling(ii) = 1.0/fabs(zlower);
}
}
// State scaling:
if ( algorithm.scaling=="automatic" || algorithm.scaling!="user" )
{
state_scaling = ones(nstates,1);
for(ii=1;ii<=nstates;ii++)
{
zlower = (problem.phase[i].bounds.lower.states)(ii);
zupper = (problem.phase[i].bounds.upper.states)(ii);
if ( zlower!=-INF && zupper!= INF ) {
if (zlower !=0.0 || zupper!=0.0)
state_scaling(ii) = 1.0/MAX( fabs(zlower), fabs(zupper));
}
else if (zlower==-INF && zupper!=INF && zupper!=0.0)
state_scaling(ii) = 1.0/fabs(zupper);
else if (zupper==INF && zlower!=-INF && zlower!=0.0)
state_scaling(ii) = 1.0/fabs(zlower);
}
}
// Parameter scaling
if ( algorithm.scaling=="automatic" || algorithm.scaling!="user" )
{
param_scaling = ones(nparam,1);
for(ii=1;ii<=nparam;ii++)
{
zlower = (problem.phase[i].bounds.lower.parameters)(ii);
zupper = (problem.phase[i].bounds.upper.parameters)(ii);
if ( zlower!=-INF && zupper!= INF ) {
if (zlower !=0.0 || zupper!=0.0)
param_scaling(ii) = 1.0/MAX( fabs(zlower), fabs(zupper));
}
else if (zlower==-INF && zupper!=INF && zupper!=0.0)
param_scaling(ii) = 1.0/fabs(zupper);
else if (zupper==INF && zlower!=-INF && zlower!=0.0)
param_scaling(ii) = 1.0/fabs(zlower);
}
}
// Time scaling
if ( algorithm.scaling=="automatic" || algorithm.scaling!="user" )
{
problem.phase[i].scale.time = 1.0;
zlower = (problem.phase[i].bounds.lower.StartTime);
zupper = (problem.phase[i].bounds.upper.EndTime);
if ( zlower!=-INF && zupper!= INF ) {
if (zlower !=0.0 || zupper!=0.0)
problem.phase[i].scale.time = 1.0/MAX( fabs(zlower), fabs(zupper));
}
else if (zlower==-INF && zupper!=INF && zupper!=0.0)
problem.phase[i].scale.time = 1.0/fabs(zupper);
else if (zupper==INF && zlower!=-INF && zlower!=0.0)
problem.phase[i].scale.time = 1.0/fabs(zlower);
}
}
}
void determine_objective_scaling(DMatrix& X,Sol& solution, Prob& problem, Alg& algorithm, Workspace* workspace )
{
// The scaling factor for the objective function is computed such that the
// scaled gradient at the initial guess has an Euclidean norm of 1.0.
double nrm_g;
DMatrix& GF = *workspace->GFip;
GF.Resize(get_number_nlp_vars(problem, workspace), 1);
if ( algorithm.scaling=="automatic" || algorithm.scaling!="user" )
{
if ( (algorithm.derivatives=="automatic") ) {
int n = length(X);
int i, itag=workspace->tag_f;
double yp = 0.0;
adouble *xad = workspace->xad;
adouble yad;
DMatrix& GF = *workspace->GFip;
problem.scale.objective = -1.0;
trace_on(itag);
for(i=0;i<n;i++) {
xad[i] <<= (X.GetPr())[i];
}
yad = ff_ad(xad, workspace);
yad >>= yp;
trace_off();
gradient(itag,n,X.GetPr(),GF.GetPr());
}
else {
problem.scale.objective = -1.0;
ScalarGradient( ff_num, X, &GF , workspace->grw, workspace );
}
nrm_g = enorm(GF);
if ( nrm_g != 0.0 && nrm_g < INF)
problem.scale.objective = 1/nrm_g;
else
problem.scale.objective = 1.0;
}
}
void determine_constraint_scaling_factors(DMatrix & X, Sol& solution, Prob& problem, Alg& algorithm, Workspace* workspace)
{
// For the differential defect constraints there are two options: The default is to use the
// same scaling factors as those used for the corresponding state. Alternatively, the user
// may specify that the scaling factors for the differential defect constraints be calculated
// based on the Jacobian (see below).
// For all other constraints, the scaling factors are computed such that the corresponding row of
// the scaled Jacobian matrix of the constraints has an Euclidean norm of 1.0.
if ( algorithm.scaling=="automatic" || algorithm.scaling!="user" )
{
int i, j, l, k;
int nvars = get_number_nlp_vars(problem, workspace);
int ncons = get_number_nlp_constraints(problem, workspace);
DMatrix& JacCol1 = *workspace->JacCol1;
DMatrix& xlb = *workspace->xlb;
DMatrix& xub = *workspace->xub;
DMatrix& xp = *workspace->xp;
DMatrix& jac_row_norm = *workspace->JacCol2;
DMatrix jtemp;
workspace->use_constraint_scaling = 0;
jac_row_norm.Resize(ncons,1);
xp = X;
// clip_vector_given_bounds( xp, xlb, xub);
if ( useAutomaticDifferentiation(algorithm) && algorithm.constraint_scaling=="automatic") {
// NOTE, THIS OPTION HAD BEEN DESACTIVATED AS MATTEO CERIOTTI REPORTED A PROBLEM WITH A CASE
// WITH RELEASE 2.
// ACTIVATED AGAIN ON 27.11.2012
// EXTRA PARAMETER .constraint_scaling ADDED TO ALGORITHM STRUCTURE 27.11.2012.
jac_row_norm.FillWithZeros();
unsigned int *jac_rind = NULL;
unsigned int *jac_cind = NULL;
double *jac_values = NULL;
int nnz;
adouble *xad = workspace->xad;
adouble *gad = workspace->gad;
double *g = workspace->fg;
double *x = xp.GetPr();
/* Tracing of function gg() */
trace_on(workspace->tag_gc);
for(i=0;i<nvars;i++)
xad[i] <<= x[i];
gg_ad(xad, gad, workspace);
for(i=0;i<ncons;i++)
gad[i] >>= g[i];
trace_off();
#ifdef ADOLC_VERSION_1
sparse_jac(workspace->tag_gc, ncons, nvars, 0, x, &nnz, &jac_rind, &jac_cind, &jac_values);
#endif
#ifdef ADOLC_VERSION_2
int options[4];
options[0]=0; options[1]=0; options[2]=0;options[3]=0;
sparse_jac(workspace->tag_gc, ncons, nvars, 0, x, &nnz, &jac_rind, &jac_cind, &jac_values, options);
#endif
for (i=0;i<nnz;i++) {
jac_row_norm( jac_rind[i] + 1 ) += pow( jac_values[i], 2.0);
}
}
else {
jac_row_norm.FillWithZeros();
DMatrix& xlb = *(workspace->xlb);
DMatrix& xub = *(workspace->xub);
for(j=1;j<=nvars;j++) {
JacobianColumn( gg_num, xp, xlb, xub,j, &JacCol1, workspace->grw, workspace);
jac_row_norm+= (JacCol1^2);
}
} // end if-else
jac_row_norm = Sqrt(jac_row_norm);
for (i=1;i<=ncons;i++)
{
double sqeps = sqrt(DMatrix::GetEPS());
// if (jac_row_norm(i) != 0.0 && jac_row_norm(i) < 1.e7 ) {
if ( jac_row_norm(i) < 1.e7 ) {
// (*workspace->constraint_scaling)(i) = 1.0/jac_row_norm(i);
(*workspace->constraint_scaling)(i) = 1.0/(jac_row_norm(i)+sqeps);
}
else {
// fprintf(stderr,"\n>>>>> jac_row_norm(%i)=%e", i, jac_row_norm(i) );
if ( jac_row_norm(i) > 1.e7 ) {
(*workspace->constraint_scaling)(i) = 1.0/1.e7;
}
// if ( jac_row_norm(i) == 0.0 ) {
// (*workspace->constraint_scaling)(i) = 1.0;
// }
}
}
//////////////////////////////////////////////////////////
// RELEASE 1 CODE BELOW
// for (i=1;i<=ncons;i++)
// {
// if (jac_row_norm(i) != 0.0) {
// (*workspace->constraint_scaling)(i) = 1.0/jac_row_norm(i);
// }
// else {
// (*workspace->constraint_scaling)(i) = 1.0;
// }
// }
//////////////////////////////////////////////////////
workspace->use_constraint_scaling = 1;
if ( algorithm.defect_scaling == "jacobian-based" )
return;
// By default, use the state scaling factors for the differential defects. See Betts (2001).
int offset = 0;
for(i=0; i< problem.nphases; i++) {
DMatrix& state_scaling = (problem.phase[i].scale.states);
int norder = problem.phase[i].current_number_of_intervals;
int nstates = problem.phase[i].nstates;
int nevents = problem.phase[i].nevents;
int npath = problem.phase[i].npath;
int ncons_phase_i = get_ncons_phase_i(problem,i, workspace);
for (k=1;k<=norder+1;k++) {
for( j=1;j<=nstates;j++) {
l = offset + (k-1)*nstates+j;
(*workspace->constraint_scaling)(l) = state_scaling(j);
}
}
offset += ncons_phase_i;
}
}
}
<commit_msg>Update scaling.cxx<commit_after>/*********************************************************************************************
This file is part of the PSOPT library, a software tool for computational optimal control
Copyright (C) 2009-2020 Victor M. Becerra
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 Street, Fifth Floor, Boston, MA 02110-1301 USA,
or visit http://www.gnu.org/licenses/
Author: Professor Victor M. Becerra
Address: University of Portsmouth
School of Energy and Electronic Engineering
Portsmouth PO1 3DJ
United Kingdom
e-mail: v.m.becerra@ieee.org
**********************************************************************************************/
#include "psopt.h"
using namespace Eigen;
void determine_scaling_factors_for_variables(Sol& solution, Prob& problem, Alg& algorithm)
{
// Scaling factors for variables computed automatically given the bound information
// supplied by the user, such that the scaled variables are mostly in the interval [-1,1].
// If, however, any of the variable bounds is 'inf' in magnitude, then the scaled range
// will be [-1, inf], [-inf,1], or [-1, 1]
int i;
for(i=0; i<problem.nphases; i++)
{
int norder = problem.phase[i].current_number_of_intervals;
int ncontrols = problem.phase[i].ncontrols;
int npath = problem.phase[i].npath;
int nstates = problem.phase[i].nstates;
int nevents = problem.phase[i].nevents;
int nparam = problem.phase[i].nparameters;
MatrixXd& control_scaling = problem.phase[i].scale.controls;
MatrixXd& state_scaling = problem.phase[i].scale.states;
MatrixXd& param_scaling = problem.phase[i].scale.parameters;
MatrixXd PathJac(npath, nstates+ncontrols);
MatrixXd h1(npath,norder+1);
MatrixXd h2(npath,norder+1);
MatrixXd e1(nevents,1);
MatrixXd e2(nevents,2);
MatrixXd EventJac1(nevents, nstates+ncontrols);
MatrixXd EventJac2(nevents, nstates+ncontrols);
double zlower;
double zupper;
int ii;
// Control scaling:
if ( algorithm.scaling=="automatic" || algorithm.scaling!="user" )
{
control_scaling = ones(ncontrols,1); // EIGEN_UPDATE
for(ii=0;ii<ncontrols;ii++)
{
zlower = (problem.phase[i].bounds.lower.controls)(ii);
zupper = (problem.phase[i].bounds.upper.controls)(ii);
if ( zlower!=-INF && zupper!= INF ) {
if (zlower !=0.0 || zupper!=0.0)
control_scaling(ii) = 1.0/MAX( fabs(zlower), fabs(zupper));
}
else if (zlower==-INF && zupper!=INF && zupper!=0.0)
control_scaling(ii) = 1.0/fabs(zupper);
else if (zupper==INF && zlower!=-INF && zlower!=0.0)
control_scaling(ii) = 1.0/fabs(zlower);
}
}
// State scaling:
if ( algorithm.scaling=="automatic" || algorithm.scaling!="user" )
{
state_scaling = ones(nstates,1);
for(ii=0;ii<nstates;ii++) // EIGEN_UPDATE
{
zlower = (problem.phase[i].bounds.lower.states)(ii);
zupper = (problem.phase[i].bounds.upper.states)(ii);
if ( zlower!=-INF && zupper!= INF ) {
if (zlower !=0.0 || zupper!=0.0)
state_scaling(ii) = 1.0/MAX( fabs(zlower), fabs(zupper));
}
else if (zlower==-INF && zupper!=INF && zupper!=0.0)
state_scaling(ii) = 1.0/fabs(zupper);
else if (zupper==INF && zlower!=-INF && zlower!=0.0)
state_scaling(ii) = 1.0/fabs(zlower);
}
}
// Parameter scaling
if ( algorithm.scaling=="automatic" || algorithm.scaling!="user" )
{
param_scaling = ones(nparam,1);
for(ii=0;ii<nparam;ii++) // EIGEN_UPDATE
{
zlower = (problem.phase[i].bounds.lower.parameters)(ii);
zupper = (problem.phase[i].bounds.upper.parameters)(ii);
if ( zlower!=-INF && zupper!= INF ) {
if (zlower !=0.0 || zupper!=0.0)
param_scaling(ii) = 1.0/MAX( fabs(zlower), fabs(zupper));
}
else if (zlower==-INF && zupper!=INF && zupper!=0.0)
param_scaling(ii) = 1.0/fabs(zupper);
else if (zupper==INF && zlower!=-INF && zlower!=0.0)
param_scaling(ii) = 1.0/fabs(zlower);
}
}
// Time scaling
if ( algorithm.scaling=="automatic" || algorithm.scaling!="user" )
{
problem.phase[i].scale.time = 1.0;
zlower = (problem.phase[i].bounds.lower.StartTime);
zupper = (problem.phase[i].bounds.upper.EndTime);
if ( zlower!=-INF && zupper!= INF ) {
if (zlower !=0.0 || zupper!=0.0)
problem.phase[i].scale.time = 1.0/MAX( fabs(zlower), fabs(zupper));
}
else if (zlower==-INF && zupper!=INF && zupper!=0.0)
problem.phase[i].scale.time = 1.0/fabs(zupper);
else if (zupper==INF && zlower!=-INF && zlower!=0.0)
problem.phase[i].scale.time = 1.0/fabs(zlower);
}
}
}
void determine_objective_scaling(MatrixXd& X,Sol& solution, Prob& problem, Alg& algorithm, Workspace* workspace )
{
// The scaling factor for the objective function is computed such that the
// scaled gradient at the initial guess has an Euclidean norm of 1.0.
double nrm_g;
MatrixXd& GF = *workspace->GFip;
GF.resize(get_number_nlp_vars(problem, workspace), 1);
if ( algorithm.scaling=="automatic" || algorithm.scaling!="user" )
{
if ( (algorithm.derivatives=="automatic") ) {
long n = length(X);
int i, itag=workspace->tag_f;
double yp = 0.0;
adouble *xad = workspace->xad;
adouble yad;
MatrixXd& GF = *workspace->GFip;
problem.scale.objective = -1.0;
trace_on(itag);
for(i=0;i<n;i++) {
// xad[i] <<= (X.GetPr())[i];
xad[i] <<= (&X(0))[i];
}
yad = ff_ad(xad, workspace);
yad >>= yp;
trace_off();
// gradient(itag,n,X.GetPr(),GF.GetPr());
gradient(itag,n,&X(0),&GF(0));
}
else {
problem.scale.objective = -1.0;
ScalarGradient( ff_num, X, &GF , workspace->grw, workspace );
}
nrm_g = (GF).norm();
if ( nrm_g != 0.0 && nrm_g < INF)
problem.scale.objective = 1/nrm_g;
else
problem.scale.objective = 1.0;
}
}
void determine_constraint_scaling_factors(MatrixXd & X, Sol& solution, Prob& problem, Alg& algorithm, Workspace* workspace)
{
// For the differential defect constraints there are two options: The default is to use the
// same scaling factors as those used for the corresponding state. Alternatively, the user
// may specify that the scaling factors for the differential defect constraints be calculated
// based on the Jacobian (see below).
// For all other constraints, the scaling factors are computed such that the corresponding row of
// the scaled Jacobian matrix of the constraints has an Euclidean norm of 1.0.
if ( algorithm.scaling=="automatic" || algorithm.scaling!="user" )
{
int i, j, l, k;
int nvars = get_number_nlp_vars(problem, workspace);
int ncons = get_number_nlp_constraints(problem, workspace);
MatrixXd& JacCol1 = *workspace->JacCol1;
// MatrixXd& xlb = *workspace->xlb;
// MatrixXd& xub = *workspace->xub;
MatrixXd& xp = *workspace->xp;
MatrixXd& jac_row_norm = *workspace->JacCol2;
MatrixXd jtemp;
workspace->use_constraint_scaling = 0;
jac_row_norm.resize(ncons,1);
xp = X;
// clip_vector_given_bounds( xp, xlb, xub);
if ( useAutomaticDifferentiation(algorithm) && algorithm.constraint_scaling=="automatic") {
// EXTRA PARAMETER .constraint_scaling ADDED TO ALGORITHM STRUCTURE 27.11.2012.
// jac_row_norm.FillWithZeros();
jac_row_norm.setZero();
unsigned int *jac_rind = NULL;
unsigned int *jac_cind = NULL;
double *jac_values = NULL;
int nnz;
adouble *xad = workspace->xad;
adouble *gad = workspace->gad;
double *g = workspace->fg;
// double *x = xp.GetPr();
double *x = &xp(0);
/* Tracing of function gg() */
trace_on(workspace->tag_gc);
for(i=0;i<nvars;i++)
xad[i] <<= x[i];
gg_ad(xad, gad, workspace);
for(i=0;i<ncons;i++)
gad[i] >>= g[i];
trace_off();
int options[4];
options[0]=0; options[1]=0; options[2]=0;options[3]=0;
sparse_jac(workspace->tag_gc, ncons, nvars, 0, x, &nnz, &jac_rind, &jac_cind, &jac_values, options);
for (i=0;i<nnz;i++) {
// jac_row_norm( jac_rind[i] + 1 ) += pow( jac_values[i], 2.0);
jac_row_norm( jac_rind[i] ) += pow( jac_values[i], 2.0);
}
}
else {
jac_row_norm.setZero();
MatrixXd& xlb = *(workspace->xlb);
MatrixXd& xub = *(workspace->xub);
for(j=0;j<nvars;j++) { // EIGEN_UPDATE
JacobianColumn( gg_num, xp, xlb, xub,j, &JacCol1, workspace->grw, workspace);
jac_row_norm+= elemProduct(JacCol1, JacCol1);
}
} // end if-else
jac_row_norm = (jac_row_norm.cwiseSqrt());
for (i=0;i<ncons;i++) // EIGEN_UPDATE
{
double sqeps = sqrt(PSOPT_extras::GetEPS());
if ( jac_row_norm(i) < 1.e7 ) {
// (*workspace->constraint_scaling)(i) = 1.0/jac_row_norm(i);
(*workspace->constraint_scaling)(i) = 1.0/(jac_row_norm(i)+sqeps);
}
else {
if ( jac_row_norm(i) > 1.e7 ) {
(*workspace->constraint_scaling)(i) = 1.0/1.e7;
}
}
}
workspace->use_constraint_scaling = 1;
if ( algorithm.defect_scaling == "jacobian-based" )
return;
// By default, use the state scaling factors for the differential defects. See Betts (2001).
int offset = 0;
for(i=0; i< problem.nphases; i++) {
MatrixXd& state_scaling = (problem.phase[i].scale.states);
int norder = problem.phase[i].current_number_of_intervals;
int nstates = problem.phase[i].nstates;
int ncons_phase_i = get_ncons_phase_i(problem,i, workspace);
for (k=0;k<norder+1;k++) { // EIGEN_UPDATE
for( j=0;j<nstates;j++) { // EIGEN_UPDATE
l = offset + (k)*nstates+j;
(*workspace->constraint_scaling)(l) = state_scaling(j);
}
}
offset += ncons_phase_i;
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/engine_configurations.h"
#include "webrtc/modules/video_coding/main/source/encoded_frame.h"
#include "webrtc/modules/video_coding/main/source/generic_encoder.h"
#include "webrtc/modules/video_coding/main/source/media_optimization.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/logging.h"
namespace webrtc {
namespace {
// Map information from info into rtp. If no relevant information is found
// in info, rtp is set to NULL.
void CopyCodecSpecific(const CodecSpecificInfo* info, RTPVideoHeader** rtp) {
if (!info) {
*rtp = NULL;
return;
}
switch (info->codecType) {
case kVideoCodecVP8: {
(*rtp)->codec = kRtpVideoVp8;
(*rtp)->codecHeader.VP8.InitRTPVideoHeaderVP8();
(*rtp)->codecHeader.VP8.pictureId = info->codecSpecific.VP8.pictureId;
(*rtp)->codecHeader.VP8.nonReference =
info->codecSpecific.VP8.nonReference;
(*rtp)->codecHeader.VP8.temporalIdx = info->codecSpecific.VP8.temporalIdx;
(*rtp)->codecHeader.VP8.layerSync = info->codecSpecific.VP8.layerSync;
(*rtp)->codecHeader.VP8.tl0PicIdx = info->codecSpecific.VP8.tl0PicIdx;
(*rtp)->codecHeader.VP8.keyIdx = info->codecSpecific.VP8.keyIdx;
(*rtp)->simulcastIdx = info->codecSpecific.VP8.simulcastIdx;
return;
}
case kVideoCodecH264:
(*rtp)->codec = kRtpVideoH264;
return;
case kVideoCodecGeneric:
(*rtp)->codec = kRtpVideoGeneric;
(*rtp)->simulcastIdx = info->codecSpecific.generic.simulcast_idx;
return;
default:
// No codec specific info. Change RTP header pointer to NULL.
*rtp = NULL;
return;
}
}
} // namespace
//#define DEBUG_ENCODER_BIT_STREAM
VCMGenericEncoder::VCMGenericEncoder(VideoEncoder& encoder, bool internalSource /*= false*/)
:
_encoder(encoder),
_codecType(kVideoCodecUnknown),
_VCMencodedFrameCallback(NULL),
_bitRate(0),
_frameRate(0),
_internalSource(internalSource)
{
}
VCMGenericEncoder::~VCMGenericEncoder()
{
}
int32_t VCMGenericEncoder::Release()
{
_bitRate = 0;
_frameRate = 0;
_VCMencodedFrameCallback = NULL;
return _encoder.Release();
}
int32_t
VCMGenericEncoder::InitEncode(const VideoCodec* settings,
int32_t numberOfCores,
size_t maxPayloadSize)
{
_bitRate = settings->startBitrate * 1000;
_frameRate = settings->maxFramerate;
_codecType = settings->codecType;
if (_encoder.InitEncode(settings, numberOfCores, maxPayloadSize) != 0) {
LOG(LS_ERROR) << "Failed to initialize the encoder associated with "
"payload name: " << settings->plName;
return -1;
}
return 0;
}
int32_t
VCMGenericEncoder::Encode(const I420VideoFrame& inputFrame,
const CodecSpecificInfo* codecSpecificInfo,
const std::vector<FrameType>& frameTypes) {
std::vector<VideoFrameType> video_frame_types(frameTypes.size(),
kDeltaFrame);
VCMEncodedFrame::ConvertFrameTypes(frameTypes, &video_frame_types);
return _encoder.Encode(inputFrame, codecSpecificInfo, &video_frame_types);
}
int32_t
VCMGenericEncoder::SetChannelParameters(int32_t packetLoss, int64_t rtt)
{
return _encoder.SetChannelParameters(packetLoss, rtt);
}
int32_t
VCMGenericEncoder::SetRates(uint32_t newBitRate, uint32_t frameRate)
{
uint32_t target_bitrate_kbps = (newBitRate + 500) / 1000;
int32_t ret = _encoder.SetRates(target_bitrate_kbps, frameRate);
if (ret < 0)
{
return ret;
}
_bitRate = newBitRate;
_frameRate = frameRate;
return VCM_OK;
}
int32_t
VCMGenericEncoder::CodecConfigParameters(uint8_t* buffer, int32_t size)
{
int32_t ret = _encoder.CodecConfigParameters(buffer, size);
if (ret < 0)
{
return ret;
}
return ret;
}
uint32_t VCMGenericEncoder::BitRate() const
{
return _bitRate;
}
uint32_t VCMGenericEncoder::FrameRate() const
{
return _frameRate;
}
int32_t
VCMGenericEncoder::SetPeriodicKeyFrames(bool enable)
{
return _encoder.SetPeriodicKeyFrames(enable);
}
int32_t VCMGenericEncoder::RequestFrame(
const std::vector<FrameType>& frame_types) {
I420VideoFrame image;
std::vector<VideoFrameType> video_frame_types(frame_types.size(),
kDeltaFrame);
VCMEncodedFrame::ConvertFrameTypes(frame_types, &video_frame_types);
return _encoder.Encode(image, NULL, &video_frame_types);
}
int32_t
VCMGenericEncoder::RegisterEncodeCallback(VCMEncodedFrameCallback* VCMencodedFrameCallback)
{
_VCMencodedFrameCallback = VCMencodedFrameCallback;
_VCMencodedFrameCallback->SetInternalSource(_internalSource);
return _encoder.RegisterEncodeCompleteCallback(_VCMencodedFrameCallback);
}
bool
VCMGenericEncoder::InternalSource() const
{
return _internalSource;
}
/***************************
* Callback Implementation
***************************/
VCMEncodedFrameCallback::VCMEncodedFrameCallback(
EncodedImageCallback* post_encode_callback):
_sendCallback(),
_mediaOpt(NULL),
_payloadType(0),
_internalSource(false),
post_encode_callback_(post_encode_callback)
#ifdef DEBUG_ENCODER_BIT_STREAM
, _bitStreamAfterEncoder(NULL)
#endif
{
#ifdef DEBUG_ENCODER_BIT_STREAM
_bitStreamAfterEncoder = fopen("encoderBitStream.bit", "wb");
#endif
}
VCMEncodedFrameCallback::~VCMEncodedFrameCallback()
{
#ifdef DEBUG_ENCODER_BIT_STREAM
fclose(_bitStreamAfterEncoder);
#endif
}
int32_t
VCMEncodedFrameCallback::SetTransportCallback(VCMPacketizationCallback* transport)
{
_sendCallback = transport;
return VCM_OK;
}
int32_t VCMEncodedFrameCallback::Encoded(
const EncodedImage& encodedImage,
const CodecSpecificInfo* codecSpecificInfo,
const RTPFragmentationHeader* fragmentationHeader) {
post_encode_callback_->Encoded(encodedImage, NULL, NULL);
if (_sendCallback == NULL) {
return VCM_UNINITIALIZED;
}
#ifdef DEBUG_ENCODER_BIT_STREAM
if (_bitStreamAfterEncoder != NULL) {
fwrite(encodedImage._buffer, 1, encodedImage._length,
_bitStreamAfterEncoder);
}
#endif
RTPVideoHeader rtpVideoHeader;
RTPVideoHeader* rtpVideoHeaderPtr = &rtpVideoHeader;
CopyCodecSpecific(codecSpecificInfo, &rtpVideoHeaderPtr);
int32_t callbackReturn = _sendCallback->SendData(
_payloadType, encodedImage, *fragmentationHeader, rtpVideoHeaderPtr);
if (callbackReturn < 0) {
return callbackReturn;
}
if (_mediaOpt != NULL) {
_mediaOpt->UpdateWithEncodedData(encodedImage);
if (_internalSource)
return _mediaOpt->DropFrame(); // Signal to encoder to drop next frame.
}
return VCM_OK;
}
void
VCMEncodedFrameCallback::SetMediaOpt(
media_optimization::MediaOptimization *mediaOpt)
{
_mediaOpt = mediaOpt;
}
} // namespace webrtc
<commit_msg>Initialize RTPVideoHeader fields to correctly set simulcastIdx for non VP8 codecs.<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/engine_configurations.h"
#include "webrtc/modules/video_coding/main/source/encoded_frame.h"
#include "webrtc/modules/video_coding/main/source/generic_encoder.h"
#include "webrtc/modules/video_coding/main/source/media_optimization.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/logging.h"
namespace webrtc {
namespace {
// Map information from info into rtp. If no relevant information is found
// in info, rtp is set to NULL.
void CopyCodecSpecific(const CodecSpecificInfo* info, RTPVideoHeader** rtp) {
if (!info) {
*rtp = NULL;
return;
}
switch (info->codecType) {
case kVideoCodecVP8: {
(*rtp)->codec = kRtpVideoVp8;
(*rtp)->codecHeader.VP8.InitRTPVideoHeaderVP8();
(*rtp)->codecHeader.VP8.pictureId = info->codecSpecific.VP8.pictureId;
(*rtp)->codecHeader.VP8.nonReference =
info->codecSpecific.VP8.nonReference;
(*rtp)->codecHeader.VP8.temporalIdx = info->codecSpecific.VP8.temporalIdx;
(*rtp)->codecHeader.VP8.layerSync = info->codecSpecific.VP8.layerSync;
(*rtp)->codecHeader.VP8.tl0PicIdx = info->codecSpecific.VP8.tl0PicIdx;
(*rtp)->codecHeader.VP8.keyIdx = info->codecSpecific.VP8.keyIdx;
(*rtp)->simulcastIdx = info->codecSpecific.VP8.simulcastIdx;
return;
}
case kVideoCodecH264:
(*rtp)->codec = kRtpVideoH264;
return;
case kVideoCodecGeneric:
(*rtp)->codec = kRtpVideoGeneric;
(*rtp)->simulcastIdx = info->codecSpecific.generic.simulcast_idx;
return;
default:
// No codec specific info. Change RTP header pointer to NULL.
*rtp = NULL;
return;
}
}
} // namespace
//#define DEBUG_ENCODER_BIT_STREAM
VCMGenericEncoder::VCMGenericEncoder(VideoEncoder& encoder, bool internalSource /*= false*/)
:
_encoder(encoder),
_codecType(kVideoCodecUnknown),
_VCMencodedFrameCallback(NULL),
_bitRate(0),
_frameRate(0),
_internalSource(internalSource)
{
}
VCMGenericEncoder::~VCMGenericEncoder()
{
}
int32_t VCMGenericEncoder::Release()
{
_bitRate = 0;
_frameRate = 0;
_VCMencodedFrameCallback = NULL;
return _encoder.Release();
}
int32_t
VCMGenericEncoder::InitEncode(const VideoCodec* settings,
int32_t numberOfCores,
size_t maxPayloadSize)
{
_bitRate = settings->startBitrate * 1000;
_frameRate = settings->maxFramerate;
_codecType = settings->codecType;
if (_encoder.InitEncode(settings, numberOfCores, maxPayloadSize) != 0) {
LOG(LS_ERROR) << "Failed to initialize the encoder associated with "
"payload name: " << settings->plName;
return -1;
}
return 0;
}
int32_t
VCMGenericEncoder::Encode(const I420VideoFrame& inputFrame,
const CodecSpecificInfo* codecSpecificInfo,
const std::vector<FrameType>& frameTypes) {
std::vector<VideoFrameType> video_frame_types(frameTypes.size(),
kDeltaFrame);
VCMEncodedFrame::ConvertFrameTypes(frameTypes, &video_frame_types);
return _encoder.Encode(inputFrame, codecSpecificInfo, &video_frame_types);
}
int32_t
VCMGenericEncoder::SetChannelParameters(int32_t packetLoss, int64_t rtt)
{
return _encoder.SetChannelParameters(packetLoss, rtt);
}
int32_t
VCMGenericEncoder::SetRates(uint32_t newBitRate, uint32_t frameRate)
{
uint32_t target_bitrate_kbps = (newBitRate + 500) / 1000;
int32_t ret = _encoder.SetRates(target_bitrate_kbps, frameRate);
if (ret < 0)
{
return ret;
}
_bitRate = newBitRate;
_frameRate = frameRate;
return VCM_OK;
}
int32_t
VCMGenericEncoder::CodecConfigParameters(uint8_t* buffer, int32_t size)
{
int32_t ret = _encoder.CodecConfigParameters(buffer, size);
if (ret < 0)
{
return ret;
}
return ret;
}
uint32_t VCMGenericEncoder::BitRate() const
{
return _bitRate;
}
uint32_t VCMGenericEncoder::FrameRate() const
{
return _frameRate;
}
int32_t
VCMGenericEncoder::SetPeriodicKeyFrames(bool enable)
{
return _encoder.SetPeriodicKeyFrames(enable);
}
int32_t VCMGenericEncoder::RequestFrame(
const std::vector<FrameType>& frame_types) {
I420VideoFrame image;
std::vector<VideoFrameType> video_frame_types(frame_types.size(),
kDeltaFrame);
VCMEncodedFrame::ConvertFrameTypes(frame_types, &video_frame_types);
return _encoder.Encode(image, NULL, &video_frame_types);
}
int32_t
VCMGenericEncoder::RegisterEncodeCallback(VCMEncodedFrameCallback* VCMencodedFrameCallback)
{
_VCMencodedFrameCallback = VCMencodedFrameCallback;
_VCMencodedFrameCallback->SetInternalSource(_internalSource);
return _encoder.RegisterEncodeCompleteCallback(_VCMencodedFrameCallback);
}
bool
VCMGenericEncoder::InternalSource() const
{
return _internalSource;
}
/***************************
* Callback Implementation
***************************/
VCMEncodedFrameCallback::VCMEncodedFrameCallback(
EncodedImageCallback* post_encode_callback):
_sendCallback(),
_mediaOpt(NULL),
_payloadType(0),
_internalSource(false),
post_encode_callback_(post_encode_callback)
#ifdef DEBUG_ENCODER_BIT_STREAM
, _bitStreamAfterEncoder(NULL)
#endif
{
#ifdef DEBUG_ENCODER_BIT_STREAM
_bitStreamAfterEncoder = fopen("encoderBitStream.bit", "wb");
#endif
}
VCMEncodedFrameCallback::~VCMEncodedFrameCallback()
{
#ifdef DEBUG_ENCODER_BIT_STREAM
fclose(_bitStreamAfterEncoder);
#endif
}
int32_t
VCMEncodedFrameCallback::SetTransportCallback(VCMPacketizationCallback* transport)
{
_sendCallback = transport;
return VCM_OK;
}
int32_t VCMEncodedFrameCallback::Encoded(
const EncodedImage& encodedImage,
const CodecSpecificInfo* codecSpecificInfo,
const RTPFragmentationHeader* fragmentationHeader) {
post_encode_callback_->Encoded(encodedImage, NULL, NULL);
if (_sendCallback == NULL) {
return VCM_UNINITIALIZED;
}
#ifdef DEBUG_ENCODER_BIT_STREAM
if (_bitStreamAfterEncoder != NULL) {
fwrite(encodedImage._buffer, 1, encodedImage._length,
_bitStreamAfterEncoder);
}
#endif
RTPVideoHeader rtpVideoHeader;
memset(&rtpVideoHeader, 0, sizeof(RTPVideoHeader));
RTPVideoHeader* rtpVideoHeaderPtr = &rtpVideoHeader;
CopyCodecSpecific(codecSpecificInfo, &rtpVideoHeaderPtr);
int32_t callbackReturn = _sendCallback->SendData(
_payloadType, encodedImage, *fragmentationHeader, rtpVideoHeaderPtr);
if (callbackReturn < 0) {
return callbackReturn;
}
if (_mediaOpt != NULL) {
_mediaOpt->UpdateWithEncodedData(encodedImage);
if (_internalSource)
return _mediaOpt->DropFrame(); // Signal to encoder to drop next frame.
}
return VCM_OK;
}
void
VCMEncodedFrameCallback::SetMediaOpt(
media_optimization::MediaOptimization *mediaOpt)
{
_mediaOpt = mediaOpt;
}
} // namespace webrtc
<|endoftext|>
|
<commit_before><commit_msg>A little cleanup.<commit_after><|endoftext|>
|
<commit_before><commit_msg>Revert "calc69: #i118068# handle all-hidden case in ScDrawUtil::CalcScale"<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: notemark.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: kz $ $Date: 2006-07-21 15:02:41 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
// INCLUDE ---------------------------------------------------------------
#include <svx/svdoutl.hxx>
#include <svx/svdmodel.hxx>
#include <svx/svdobj.hxx>
#include <svx/xoutx.hxx>
#include <sfx2/printer.hxx>
#include <svtools/pathoptions.hxx>
#include <svtools/itempool.hxx>
#include <vcl/svapp.hxx>
#include "notemark.hxx"
#include "document.hxx"
#include "detfunc.hxx"
#define SC_NOTEMARK_TIME 800
#define SC_NOTEMARK_SHORT 70
// STATIC DATA -----------------------------------------------------------
// -----------------------------------------------------------------------
ScNoteMarker::ScNoteMarker( Window* pWin, Window* pRight, Window* pBottom, Window* pDiagonal,
ScDocument* pD, ScAddress aPos, const String& rUser,
const MapMode& rMap, BOOL bLeftEdge, BOOL bForce, BOOL bKeyboard ) :
pWindow( pWin ),
pRightWin( pRight ),
pBottomWin( pBottom ),
pDiagWin( pDiagonal ),
pDoc( pD ),
aDocPos( aPos ),
aUserText( rUser ),
aMapMode( rMap ),
bLeft( bLeftEdge ),
bByKeyboard( bKeyboard ),
bVisible( FALSE ),
pModel( NULL ),
pObject( NULL )
{
aTimer.SetTimeoutHdl( LINK( this, ScNoteMarker, TimeHdl ) );
aTimer.SetTimeout( bForce ? SC_NOTEMARK_SHORT : SC_NOTEMARK_TIME );
aTimer.Start();
}
ScNoteMarker::~ScNoteMarker()
{
InvalidateWin();
delete pModel;
}
IMPL_LINK( ScNoteMarker, TimeHdl, Timer*, pTimer )
{
if (!bVisible)
{
SvtPathOptions aPathOpt;
String aPath = aPathOpt.GetPalettePath();
pModel = new SdrModel(aPath);
pModel->SetScaleUnit(MAP_100TH_MM);
SfxItemPool& rPool = pModel->GetItemPool();
rPool.SetDefaultMetric(SFX_MAPUNIT_100TH_MM);
rPool.FreezeIdRanges();
Printer* pPrinter = pDoc->GetPrinter();
if (pPrinter)
{
// Am Outliner des Draw-Model ist auch der Drucker als RefDevice gesetzt,
// und es soll einheitlich aussehen.
Outliner& rOutliner = pModel->GetDrawOutliner();
rOutliner.SetRefDevice(pPrinter);
}
SdrPage* pPage = pModel->AllocPage(FALSE);
Size aSizePixel = pWindow->GetOutputSizePixel();
Rectangle aVisPixel( Point(0,0), aSizePixel );
Rectangle aVisible = pWindow->PixelToLogic( aVisPixel, aMapMode );
SCCOL nCol = aDocPos.Col();
SCROW nRow = aDocPos.Row();
SCTAB nTab = aDocPos.Tab();
pObject = ScDetectiveFunc( pDoc,nTab ).
ShowCommentUser( nCol, nRow, aUserText, aVisible, bLeft, FALSE, pPage );
if (pObject)
aRect = pObject->GetCurrentBoundRect();
// #39351# Page einfuegen damit das Model sie kennt und auch deleted
pModel->InsertPage( pPage );
bVisible = TRUE;
}
Draw();
return 0;
}
void lcl_DrawWin( SdrObject* pObject, Window* pWindow, const MapMode& rMap )
{
MapMode aOld = pWindow->GetMapMode();
pWindow->SetMapMode( rMap );
ULONG nOldDrawMode = pWindow->GetDrawMode();
if ( Application::GetSettings().GetStyleSettings().GetHighContrastMode() )
{
pWindow->SetDrawMode( nOldDrawMode | DRAWMODE_SETTINGSLINE | DRAWMODE_SETTINGSFILL |
DRAWMODE_SETTINGSTEXT | DRAWMODE_SETTINGSGRADIENT );
}
XOutputDevice* pXOut = new XOutputDevice( pWindow );
pXOut->SetOutDev( pWindow );
SdrPaintInfoRec aInfoRec;
pObject->SingleObjectPainter( *pXOut, aInfoRec ); // #110094#-17
delete pXOut;
pWindow->SetDrawMode( nOldDrawMode );
pWindow->SetMapMode( aOld );
}
MapMode lcl_MoveMapMode( const MapMode& rMap, const Size& rMove )
{
MapMode aNew = rMap;
Point aOrigin = aNew.GetOrigin();
aOrigin.X() -= rMove.Width();
aOrigin.Y() -= rMove.Height();
aNew.SetOrigin(aOrigin);
return aNew;
}
void ScNoteMarker::Draw()
{
if ( pObject && bVisible )
{
lcl_DrawWin( pObject, pWindow, aMapMode );
if ( pRightWin || pBottomWin )
{
Size aWinSize = pWindow->PixelToLogic( pWindow->GetOutputSizePixel(), aMapMode );
if ( pRightWin )
lcl_DrawWin( pObject, pRightWin,
lcl_MoveMapMode( aMapMode, Size( aWinSize.Width(), 0 ) ) );
if ( pBottomWin )
lcl_DrawWin( pObject, pBottomWin,
lcl_MoveMapMode( aMapMode, Size( 0, aWinSize.Height() ) ) );
if ( pDiagWin )
lcl_DrawWin( pObject, pDiagWin, lcl_MoveMapMode( aMapMode, aWinSize ) );
}
}
}
void ScNoteMarker::InvalidateWin()
{
if (bVisible)
{
pWindow->Invalidate( pWindow->LogicToLogic(aRect, aMapMode, pWindow->GetMapMode()) );
if ( pRightWin || pBottomWin )
{
Size aWinSize = pWindow->PixelToLogic( pWindow->GetOutputSizePixel(), aMapMode );
if ( pRightWin )
pRightWin->Invalidate( pRightWin->LogicToLogic(aRect,
lcl_MoveMapMode( aMapMode, Size( aWinSize.Width(), 0 ) ),
pRightWin->GetMapMode()) );
if ( pBottomWin )
pBottomWin->Invalidate( pBottomWin->LogicToLogic(aRect,
lcl_MoveMapMode( aMapMode, Size( 0, aWinSize.Height() ) ),
pBottomWin->GetMapMode()) );
if ( pDiagWin )
pDiagWin->Invalidate( pDiagWin->LogicToLogic(aRect,
lcl_MoveMapMode( aMapMode, aWinSize ),
pDiagWin->GetMapMode()) );
}
}
}
<commit_msg>INTEGRATION: CWS calcwarnings (1.9.110); FILE MERGED 2006/12/12 17:03:31 nn 1.9.110.2: #i69284# warning-free: ui, unxlngi6 2006/12/01 08:53:47 nn 1.9.110.1: #i69284# warning-free: ui, wntmsci10<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: notemark.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: vg $ $Date: 2007-02-27 13:53:28 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
// INCLUDE ---------------------------------------------------------------
#include <svx/svdoutl.hxx>
#include <svx/svdmodel.hxx>
#include <svx/svdobj.hxx>
#include <svx/xoutx.hxx>
#include <sfx2/printer.hxx>
#include <svtools/pathoptions.hxx>
#include <svtools/itempool.hxx>
#include <vcl/svapp.hxx>
#include "notemark.hxx"
#include "document.hxx"
#include "detfunc.hxx"
#define SC_NOTEMARK_TIME 800
#define SC_NOTEMARK_SHORT 70
// STATIC DATA -----------------------------------------------------------
// -----------------------------------------------------------------------
ScNoteMarker::ScNoteMarker( Window* pWin, Window* pRight, Window* pBottom, Window* pDiagonal,
ScDocument* pD, ScAddress aPos, const String& rUser,
const MapMode& rMap, BOOL bLeftEdge, BOOL bForce, BOOL bKeyboard ) :
pWindow( pWin ),
pRightWin( pRight ),
pBottomWin( pBottom ),
pDiagWin( pDiagonal ),
pDoc( pD ),
aDocPos( aPos ),
aUserText( rUser ),
aMapMode( rMap ),
bLeft( bLeftEdge ),
bByKeyboard( bKeyboard ),
pModel( NULL ),
pObject( NULL ),
bVisible( FALSE )
{
aTimer.SetTimeoutHdl( LINK( this, ScNoteMarker, TimeHdl ) );
aTimer.SetTimeout( bForce ? SC_NOTEMARK_SHORT : SC_NOTEMARK_TIME );
aTimer.Start();
}
ScNoteMarker::~ScNoteMarker()
{
InvalidateWin();
delete pModel;
}
IMPL_LINK( ScNoteMarker, TimeHdl, Timer*, EMPTYARG )
{
if (!bVisible)
{
SvtPathOptions aPathOpt;
String aPath = aPathOpt.GetPalettePath();
pModel = new SdrModel(aPath);
pModel->SetScaleUnit(MAP_100TH_MM);
SfxItemPool& rPool = pModel->GetItemPool();
rPool.SetDefaultMetric(SFX_MAPUNIT_100TH_MM);
rPool.FreezeIdRanges();
Printer* pPrinter = pDoc->GetPrinter();
if (pPrinter)
{
// Am Outliner des Draw-Model ist auch der Drucker als RefDevice gesetzt,
// und es soll einheitlich aussehen.
Outliner& rOutliner = pModel->GetDrawOutliner();
rOutliner.SetRefDevice(pPrinter);
}
SdrPage* pPage = pModel->AllocPage(FALSE);
Size aSizePixel = pWindow->GetOutputSizePixel();
Rectangle aVisPixel( Point(0,0), aSizePixel );
Rectangle aVisible = pWindow->PixelToLogic( aVisPixel, aMapMode );
SCCOL nCol = aDocPos.Col();
SCROW nRow = aDocPos.Row();
SCTAB nTab = aDocPos.Tab();
pObject = ScDetectiveFunc( pDoc,nTab ).
ShowCommentUser( nCol, nRow, aUserText, aVisible, bLeft, FALSE, pPage );
if (pObject)
aRect = pObject->GetCurrentBoundRect();
// #39351# Page einfuegen damit das Model sie kennt und auch deleted
pModel->InsertPage( pPage );
bVisible = TRUE;
}
Draw();
return 0;
}
void lcl_DrawWin( SdrObject* pObject, Window* pWindow, const MapMode& rMap )
{
MapMode aOld = pWindow->GetMapMode();
pWindow->SetMapMode( rMap );
ULONG nOldDrawMode = pWindow->GetDrawMode();
if ( Application::GetSettings().GetStyleSettings().GetHighContrastMode() )
{
pWindow->SetDrawMode( nOldDrawMode | DRAWMODE_SETTINGSLINE | DRAWMODE_SETTINGSFILL |
DRAWMODE_SETTINGSTEXT | DRAWMODE_SETTINGSGRADIENT );
}
XOutputDevice* pXOut = new XOutputDevice( pWindow );
pXOut->SetOutDev( pWindow );
SdrPaintInfoRec aInfoRec;
pObject->SingleObjectPainter( *pXOut, aInfoRec ); // #110094#-17
delete pXOut;
pWindow->SetDrawMode( nOldDrawMode );
pWindow->SetMapMode( aOld );
}
MapMode lcl_MoveMapMode( const MapMode& rMap, const Size& rMove )
{
MapMode aNew = rMap;
Point aOrigin = aNew.GetOrigin();
aOrigin.X() -= rMove.Width();
aOrigin.Y() -= rMove.Height();
aNew.SetOrigin(aOrigin);
return aNew;
}
void ScNoteMarker::Draw()
{
if ( pObject && bVisible )
{
lcl_DrawWin( pObject, pWindow, aMapMode );
if ( pRightWin || pBottomWin )
{
Size aWinSize = pWindow->PixelToLogic( pWindow->GetOutputSizePixel(), aMapMode );
if ( pRightWin )
lcl_DrawWin( pObject, pRightWin,
lcl_MoveMapMode( aMapMode, Size( aWinSize.Width(), 0 ) ) );
if ( pBottomWin )
lcl_DrawWin( pObject, pBottomWin,
lcl_MoveMapMode( aMapMode, Size( 0, aWinSize.Height() ) ) );
if ( pDiagWin )
lcl_DrawWin( pObject, pDiagWin, lcl_MoveMapMode( aMapMode, aWinSize ) );
}
}
}
void ScNoteMarker::InvalidateWin()
{
if (bVisible)
{
pWindow->Invalidate( pWindow->LogicToLogic(aRect, aMapMode, pWindow->GetMapMode()) );
if ( pRightWin || pBottomWin )
{
Size aWinSize = pWindow->PixelToLogic( pWindow->GetOutputSizePixel(), aMapMode );
if ( pRightWin )
pRightWin->Invalidate( pRightWin->LogicToLogic(aRect,
lcl_MoveMapMode( aMapMode, Size( aWinSize.Width(), 0 ) ),
pRightWin->GetMapMode()) );
if ( pBottomWin )
pBottomWin->Invalidate( pBottomWin->LogicToLogic(aRect,
lcl_MoveMapMode( aMapMode, Size( 0, aWinSize.Height() ) ),
pBottomWin->GetMapMode()) );
if ( pDiagWin )
pDiagWin->Invalidate( pDiagWin->LogicToLogic(aRect,
lcl_MoveMapMode( aMapMode, aWinSize ),
pDiagWin->GetMapMode()) );
}
}
}
<|endoftext|>
|
<commit_before>#include "session.h"
#include <iostream>
#include <fstream>
#include <tuple>
#include <cassert>
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/ASTMatchers/Dynamic/Parser.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Tooling/Tooling.h"
#include "clang/Tooling/JSONCompilationDatabase.h"
#include "clang/Tooling/ArgumentsAdjusters.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/TextDiagnosticBuffer.h"
#include "clang/Lex/Lexer.h"
using namespace clang;
using namespace tooling;
using namespace ast_matchers;
using namespace CppQuery;
namespace {
class ResourceDirSetter : public ArgumentsAdjuster {
public:
ResourceDirSetter(const std::string &s) : resourceDir(s) {}
CommandLineArguments Adjust(const CommandLineArguments &args) {
CommandLineArguments adjustedArgs(args);
adjustedArgs.push_back("-resource-dir=" + resourceDir);
return adjustedArgs;
}
private:
std::string resourceDir;
};
class ASTBuilderAction : public ToolAction {
public:
ASTBuilderAction(std::vector<ASTUnit *> &ASTlist,
const std::function<bool(const std::string &)> &onTUbegin,
const std::function<bool(const std::string &)> &onTUend)
: ASTlist(ASTlist), onTUbegin(onTUbegin), onTUend(onTUend) {
errorNum = 0;
}
bool runInvocation(CompilerInvocation *invocation, FileManager *files,
DiagnosticConsumer *diagConsumer) {
llvm::StringRef file = invocation->getFrontendOpts().Inputs[0].getFile();
/*std::string dir;
if (file.count('/') == 0 && file.count('\\') == 0) {
const FileEntry *f = files->getFile(file);
dir = f->getDir()->getName();
}*/
if (!onTUbegin(getAbsolutePath(file)))
return true;
TextDiagnosticBuffer diag;
ASTUnit *AST = ASTUnit::LoadFromCompilerInvocation(
invocation, CompilerInstance::createDiagnostics(
&invocation->getDiagnosticOpts(), &diag, false));
if (!AST)
return false;
if (onTUend(AST->getMainFileName().str())) {
ASTlist.push_back(AST);
SourceManager &srcMgr = AST->getSourceManager();
for (TextDiagnosticBuffer::DiagList::const_iterator it = diag.err_begin();
it != diag.err_end(); ++it) {
errors.push_back(
srcMgr.getFilename(it->first).str() + " line: " +
std::to_string(srcMgr.getSpellingLineNumber(it->first)) + ": " +
it->second + "\n");
}
} else {
AST->setUnsafeToFree(false);
delete AST;
}
return true;
}
std::vector<std::string>::const_iterator errBegin() { return errors.begin(); }
std::vector<std::string>::const_iterator errEnd() { return errors.end(); }
private:
unsigned errorNum;
std::vector<std::string> errors;
std::vector<ASTUnit *> &ASTlist;
const std::function<bool(const std::string &)> &onTUbegin;
const std::function<bool(const std::string &)> &onTUend;
};
}
bool CppQuery::operator<(const Match &lhs, const Match &rhs) {
return std::tie(lhs.fileName, lhs.id, lhs.startLine, lhs.startCol,
lhs.endLine,
lhs.endCol) < std::tie(rhs.fileName, rhs.id, rhs.startLine,
rhs.startCol, rhs.endLine, rhs.endCol);
}
std::ostream &CppQuery::operator<<(std::ostream &s, const Match &m) {
s << m.fileName << "(" << m.id << "):" << m.startLine << "," << m.startCol
<< ":" << m.endLine << "," << m.endCol << std::endl;
return s;
}
Session::Session(const std::string &databasePath,
const std::string &resourceDir) {
std::string error;
compilationDatabase = std::unique_ptr<JSONCompilationDatabase>(
JSONCompilationDatabase::loadFromFile(databasePath, error));
if (!error.empty())
throw DatabaseError(error);
files = compilationDatabase->getAllFiles();
tool = std::unique_ptr<clang::tooling::ClangTool>(
new ClangTool(*compilationDatabase, files));
tool->appendArgumentsAdjuster(new ResourceDirSetter(resourceDir));
}
Session::~Session() {
for (auto AST : ASTlist) {
AST->setUnsafeToFree(false);
delete AST;
}
tool->clearArgumentsAdjusters();
}
void
Session::parseFiles(const std::function<bool(const std::string &)> &onTUbegin,
const std::function<bool(const std::string &)> &onTUend) {
ASTBuilderAction action(ASTlist, onTUbegin, onTUend);
if (tool->run(&action) || action.errBegin() != action.errEnd()) {
std::string errors;
for (auto it = action.errBegin(); it != action.errEnd(); ++it) {
errors += *it;
}
throw ParseError(errors);
}
}
namespace {
struct CollectBoundNodes : MatchFinder::MatchCallback {
std::vector<BoundNodes> &bindings;
CollectBoundNodes(std::vector<BoundNodes> &bindings) : bindings(bindings) {}
void run(const MatchFinder::MatchResult &result) {
bindings.push_back(result.Nodes);
}
};
}
void Session::runQuery(const std::string &query) {
if (query.find(".bind") == std::string::npos)
throw QueryError("There is no such node that was bound to an ID.");
if (ASTlist.empty())
throw QueryError("There is no file that was succesfully parsed.");
dynamic::Diagnostics diag;
llvm::Optional<dynamic::DynTypedMatcher> matcher =
dynamic::Parser::parseMatcherExpression(query, &diag);
if (!matcher)
throw QueryError(diag.toString());
foundMatches.clear();
Match m;
for (auto ast : ASTlist) {
SourceManager &srcMgr = ast->getSourceManager();
MatchFinder finder;
std::vector<BoundNodes> boundNodes;
CollectBoundNodes collector(boundNodes);
if (!finder.addDynamicMatcher(*matcher, &collector))
throw QueryError("Invalid top level matcher.");
finder.matchAST(ast->getASTContext());
for (auto nodes : boundNodes) {
for (auto idToNode : nodes.getMap()) {
SourceRange range = idToNode.second.getSourceRange();
if (!range.isValid())
continue;
SourceLocation start = range.getBegin();
if (srcMgr.isInSystemHeader(start) ||
srcMgr.isInExternCSystemHeader(start))
continue;
// Get the last character of the last token
SourceLocation end = Lexer::getLocForEndOfToken(range.getEnd(), 1,
srcMgr, LangOptions());
llvm::StringRef fileName = srcMgr.getFilename(start);
if (fileName.empty())
continue;
m.fileName = fileName.str();
m.id = idToNode.first;
m.startCol = srcMgr.getSpellingColumnNumber(start);
m.startLine = srcMgr.getSpellingLineNumber(start);
m.endCol = srcMgr.getSpellingColumnNumber(end);
m.endLine = srcMgr.getSpellingLineNumber(end);
foundMatches.insert(std::move(m));
}
}
}
}
const std::set<Match> &Session::getMatches() const { return foundMatches; }
bool Session::exportMatches(const std::string &fileName) {
std::ofstream output(fileName);
if (!output)
return false;
for (const Match &m : foundMatches) {
output << m;
}
return true;
}
<commit_msg>Removed some redundant comments.<commit_after>#include "session.h"
#include <iostream>
#include <fstream>
#include <tuple>
#include <cassert>
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/ASTMatchers/Dynamic/Parser.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Tooling/Tooling.h"
#include "clang/Tooling/JSONCompilationDatabase.h"
#include "clang/Tooling/ArgumentsAdjusters.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/TextDiagnosticBuffer.h"
#include "clang/Lex/Lexer.h"
using namespace clang;
using namespace tooling;
using namespace ast_matchers;
using namespace CppQuery;
namespace {
class ResourceDirSetter : public ArgumentsAdjuster {
public:
ResourceDirSetter(const std::string &s) : resourceDir(s) {}
CommandLineArguments Adjust(const CommandLineArguments &args) {
CommandLineArguments adjustedArgs(args);
adjustedArgs.push_back("-resource-dir=" + resourceDir);
return adjustedArgs;
}
private:
std::string resourceDir;
};
class ASTBuilderAction : public ToolAction {
public:
ASTBuilderAction(std::vector<ASTUnit *> &ASTlist,
const std::function<bool(const std::string &)> &onTUbegin,
const std::function<bool(const std::string &)> &onTUend)
: ASTlist(ASTlist), onTUbegin(onTUbegin), onTUend(onTUend) {
errorNum = 0;
}
bool runInvocation(CompilerInvocation *invocation, FileManager *files,
DiagnosticConsumer *diagConsumer) {
llvm::StringRef file = invocation->getFrontendOpts().Inputs[0].getFile();
if (!onTUbegin(getAbsolutePath(file)))
return true;
TextDiagnosticBuffer diag;
ASTUnit *AST = ASTUnit::LoadFromCompilerInvocation(
invocation, CompilerInstance::createDiagnostics(
&invocation->getDiagnosticOpts(), &diag, false));
if (!AST)
return false;
if (onTUend(AST->getMainFileName().str())) {
ASTlist.push_back(AST);
SourceManager &srcMgr = AST->getSourceManager();
for (TextDiagnosticBuffer::DiagList::const_iterator it = diag.err_begin();
it != diag.err_end(); ++it) {
errors.push_back(
srcMgr.getFilename(it->first).str() + " line: " +
std::to_string(srcMgr.getSpellingLineNumber(it->first)) + ": " +
it->second + "\n");
}
} else {
AST->setUnsafeToFree(false);
delete AST;
}
return true;
}
std::vector<std::string>::const_iterator errBegin() { return errors.begin(); }
std::vector<std::string>::const_iterator errEnd() { return errors.end(); }
private:
unsigned errorNum;
std::vector<std::string> errors;
std::vector<ASTUnit *> &ASTlist;
const std::function<bool(const std::string &)> &onTUbegin;
const std::function<bool(const std::string &)> &onTUend;
};
}
bool CppQuery::operator<(const Match &lhs, const Match &rhs) {
return std::tie(lhs.fileName, lhs.id, lhs.startLine, lhs.startCol,
lhs.endLine,
lhs.endCol) < std::tie(rhs.fileName, rhs.id, rhs.startLine,
rhs.startCol, rhs.endLine, rhs.endCol);
}
std::ostream &CppQuery::operator<<(std::ostream &s, const Match &m) {
s << m.fileName << "(" << m.id << "):" << m.startLine << "," << m.startCol
<< ":" << m.endLine << "," << m.endCol << std::endl;
return s;
}
Session::Session(const std::string &databasePath,
const std::string &resourceDir) {
std::string error;
compilationDatabase = std::unique_ptr<JSONCompilationDatabase>(
JSONCompilationDatabase::loadFromFile(databasePath, error));
if (!error.empty())
throw DatabaseError(error);
files = compilationDatabase->getAllFiles();
tool = std::unique_ptr<clang::tooling::ClangTool>(
new ClangTool(*compilationDatabase, files));
tool->appendArgumentsAdjuster(new ResourceDirSetter(resourceDir));
}
Session::~Session() {
for (auto AST : ASTlist) {
AST->setUnsafeToFree(false);
delete AST;
}
tool->clearArgumentsAdjusters();
}
void
Session::parseFiles(const std::function<bool(const std::string &)> &onTUbegin,
const std::function<bool(const std::string &)> &onTUend) {
ASTBuilderAction action(ASTlist, onTUbegin, onTUend);
if (tool->run(&action) || action.errBegin() != action.errEnd()) {
std::string errors;
for (auto it = action.errBegin(); it != action.errEnd(); ++it) {
errors += *it;
}
throw ParseError(errors);
}
}
namespace {
struct CollectBoundNodes : MatchFinder::MatchCallback {
std::vector<BoundNodes> &bindings;
CollectBoundNodes(std::vector<BoundNodes> &bindings) : bindings(bindings) {}
void run(const MatchFinder::MatchResult &result) {
bindings.push_back(result.Nodes);
}
};
}
void Session::runQuery(const std::string &query) {
if (query.find(".bind") == std::string::npos)
throw QueryError("There is no such node that was bound to an ID.");
if (ASTlist.empty())
throw QueryError("There is no file that was succesfully parsed.");
dynamic::Diagnostics diag;
llvm::Optional<dynamic::DynTypedMatcher> matcher =
dynamic::Parser::parseMatcherExpression(query, &diag);
if (!matcher)
throw QueryError(diag.toString());
foundMatches.clear();
Match m;
for (auto ast : ASTlist) {
SourceManager &srcMgr = ast->getSourceManager();
MatchFinder finder;
std::vector<BoundNodes> boundNodes;
CollectBoundNodes collector(boundNodes);
if (!finder.addDynamicMatcher(*matcher, &collector))
throw QueryError("Invalid top level matcher.");
finder.matchAST(ast->getASTContext());
for (auto nodes : boundNodes) {
for (auto idToNode : nodes.getMap()) {
SourceRange range = idToNode.second.getSourceRange();
if (!range.isValid())
continue;
SourceLocation start = range.getBegin();
if (srcMgr.isInSystemHeader(start) ||
srcMgr.isInExternCSystemHeader(start))
continue;
// Get the last character of the last token
SourceLocation end = Lexer::getLocForEndOfToken(range.getEnd(), 1,
srcMgr, LangOptions());
llvm::StringRef fileName = srcMgr.getFilename(start);
if (fileName.empty())
continue;
m.fileName = fileName.str();
m.id = idToNode.first;
m.startCol = srcMgr.getSpellingColumnNumber(start);
m.startLine = srcMgr.getSpellingLineNumber(start);
m.endCol = srcMgr.getSpellingColumnNumber(end);
m.endLine = srcMgr.getSpellingLineNumber(end);
foundMatches.insert(std::move(m));
}
}
}
}
const std::set<Match> &Session::getMatches() const { return foundMatches; }
bool Session::exportMatches(const std::string &fileName) {
std::ofstream output(fileName);
if (!output)
return false;
for (const Match &m : foundMatches) {
output << m;
}
return true;
}
<|endoftext|>
|
<commit_before>/*
* This file is part of Poedit (http://poedit.net)
*
* Copyright (C) 2014 Vaclav Slavik
*
* 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.
*
*/
#include "sidebar.h"
#include "catalog.h"
#include "customcontrols.h"
#include "commentdlg.h"
#include <wx/button.h>
#include <wx/dcclient.h>
#include <wx/sizer.h>
#include <wx/stattext.h>
#define SIDEBAR_BACKGROUND wxColour("#EDF0F4")
#define GRAY_LINES_COLOR wxColour(220,220,220)
#define GRAY_LINES_COLOR_DARK wxColour(180,180,180)
class SidebarSeparator : public wxWindow
{
public:
SidebarSeparator(wxWindow *parent)
: wxWindow(parent, wxID_ANY),
m_sides(SIDEBAR_BACKGROUND),
m_center(GRAY_LINES_COLOR_DARK)
{
Bind(wxEVT_PAINT, &SidebarSeparator::OnPaint, this);
}
virtual wxSize DoGetBestSize() const
{
return wxSize(-1, 1);
}
private:
void OnPaint(wxPaintEvent&)
{
wxPaintDC dc(this);
auto w = dc.GetSize().x;
dc.GradientFillLinear(wxRect(0,0,15,1), m_sides, m_center);
dc.GradientFillLinear(wxRect(15,0,w,1), m_center, m_sides);
}
wxColour m_sides, m_center;
};
SidebarBlock::SidebarBlock(wxWindow *parent, const wxString& label)
{
m_sizer = new wxBoxSizer(wxVERTICAL);
m_sizer->AddSpacer(15);
if (!label.empty())
{
m_sizer->Add(new SidebarSeparator(parent),
wxSizerFlags().Expand().Border(wxBOTTOM|wxLEFT, 2));
m_sizer->Add(new HeadingLabel(parent, label),
wxSizerFlags().Expand().DoubleBorder(wxLEFT|wxRIGHT));
}
m_innerSizer = new wxBoxSizer(wxVERTICAL);
m_sizer->Add(m_innerSizer, wxSizerFlags(1).Expand().DoubleBorder(wxLEFT|wxRIGHT));
}
void SidebarBlock::Show(bool show)
{
m_sizer->ShowItems(show);
}
void SidebarBlock::SetItem(CatalogItem *item)
{
if (!item)
{
Show(false);
return;
}
bool use = ShouldShowForItem(item);
if (use)
Update(item);
Show(use);
}
class OldMsgidSidebarBlock : public SidebarBlock
{
public:
OldMsgidSidebarBlock(wxWindow *parent)
/// TRANSLATORS: "Previous" as in used in the past, now replaced with newer.
: SidebarBlock(parent, _("Previous source text:"))
{
m_innerSizer->AddSpacer(2);
m_innerSizer->Add(new ExplanationLabel(parent, _("The old source text (before it changed during an update) that the fuzzy translation corresponds to.")),
wxSizerFlags().Expand());
m_innerSizer->AddSpacer(5);
m_text = new AutoWrappingText(parent, "");
m_innerSizer->Add(m_text, wxSizerFlags().Expand());
}
virtual bool ShouldShowForItem(CatalogItem *item) const
{
return item->HasOldMsgid();
}
void Update(CatalogItem *item) override
{
auto txt = wxJoin(item->GetOldMsgid(), ' ', '\0');
m_text->SetAndWrapLabel(txt);
}
private:
AutoWrappingText *m_text;
};
class AutoCommentSidebarBlock : public SidebarBlock
{
public:
AutoCommentSidebarBlock(wxWindow *parent)
: SidebarBlock(parent, _("Notes for translators:"))
{
m_innerSizer->AddSpacer(5);
m_comment = new AutoWrappingText(parent, "");
m_innerSizer->Add(m_comment, wxSizerFlags().Expand());
}
virtual bool ShouldShowForItem(CatalogItem *item) const
{
return item->HasAutoComments();
}
void Update(CatalogItem *item) override
{
auto comment = wxJoin(item->GetAutoComments(), ' ', '\0');
if (comment.StartsWith("TRANSLATORS:") || comment.StartsWith("translators:"))
{
comment.Remove(0, 12);
if (!comment.empty() && comment[0] == ' ')
comment.Remove(0, 1);
}
m_comment->SetAndWrapLabel(comment);
}
private:
AutoWrappingText *m_comment;
};
class CommentSidebarBlock : public SidebarBlock
{
public:
CommentSidebarBlock(wxWindow *parent)
: SidebarBlock(parent, _("Comment:"))
{
m_innerSizer->AddSpacer(5);
m_comment = new AutoWrappingText(parent, "");
m_innerSizer->Add(m_comment, wxSizerFlags().Expand());
}
virtual bool ShouldShowForItem(CatalogItem *item) const
{
return item->HasComment();
}
void Update(CatalogItem *item) override
{
auto text = CommentDialog::RemoveStartHash(item->GetComment());
text.Trim();
m_comment->SetAndWrapLabel(text);
}
private:
AutoWrappingText *m_comment;
};
class AddCommentSidebarBlock : public SidebarBlock
{
public:
AddCommentSidebarBlock(wxWindow *parent) : SidebarBlock(parent, "")
{
#ifdef __WXMSW__
auto label = _("Add comment");
#else
auto label = _("Add Comment");
#endif
m_btn = new wxButton(parent, XRCID("menu_comment"), _("Add Comment"));
m_innerSizer->AddStretchSpacer();
m_innerSizer->Add(m_btn, wxSizerFlags().Right());
}
virtual bool IsGrowable() const { return true; }
virtual bool ShouldShowForItem(CatalogItem*) const { return true; }
void Update(CatalogItem *item) override
{
#ifdef __WXMSW__
auto add = _("Add comment");
auto edit = _("Edit comment");
#else
auto add = _("Add Comment");
auto edit = _("Edit Comment");
#endif
m_btn->SetLabel(item->HasComment() ? edit : add);
}
private:
wxButton *m_btn;
};
Sidebar::Sidebar(wxWindow *parent)
: wxPanel(parent, wxID_ANY),
m_selectedItem(nullptr)
{
SetBackgroundColour(SIDEBAR_BACKGROUND);
Bind(wxEVT_PAINT, &Sidebar::OnPaint, this);
#ifdef __WXOSX__
SetWindowVariant(wxWINDOW_VARIANT_SMALL);
#endif
auto *topSizer = new wxBoxSizer(wxVERTICAL);
topSizer->SetMinSize(wxSize(300, -1));
m_blocksSizer = new wxBoxSizer(wxVERTICAL);
topSizer->Add(m_blocksSizer, wxSizerFlags(1).Expand().DoubleBorder(wxTOP|wxBOTTOM));
m_topBlocksSizer = new wxBoxSizer(wxVERTICAL);
m_bottomBlocksSizer = new wxBoxSizer(wxVERTICAL);
m_blocksSizer->Add(m_topBlocksSizer, wxSizerFlags().Expand());
m_blocksSizer->AddStretchSpacer();
m_blocksSizer->Add(m_bottomBlocksSizer, wxSizerFlags().Expand());
AddBlock(new OldMsgidSidebarBlock(this), Bottom);
AddBlock(new AutoCommentSidebarBlock(this), Bottom);
AddBlock(new CommentSidebarBlock(this), Bottom);
AddBlock(new AddCommentSidebarBlock(this), Bottom);
SetSizerAndFit(topSizer);
SetSelectedItem(nullptr);
}
void Sidebar::AddBlock(SidebarBlock *block, BlockPos pos)
{
m_blocks.emplace_back(block);
auto sizer = (pos == Top) ? m_topBlocksSizer : m_bottomBlocksSizer;
auto grow = (block->IsGrowable()) ? 1 : 0;
sizer->Add(block->GetSizer(), wxSizerFlags(grow).Expand());
}
Sidebar::~Sidebar()
{
}
void Sidebar::SetSelectedItem(CatalogItem *item)
{
m_selectedItem = item;
RefreshContent();
}
void Sidebar::SetMultipleSelection()
{
SetSelectedItem(nullptr);
}
void Sidebar::RefreshContent()
{
for (auto& b: m_blocks)
b->SetItem(m_selectedItem);
Layout();
}
void Sidebar::SetUpperHeight(int size)
{
int pos = GetSize().y - size;
#ifdef __WXOSX__
pos += 4;
#else
pos += 6;
#endif
m_bottomBlocksSizer->SetMinSize(wxSize(-1, pos));
Layout();
}
void Sidebar::OnPaint(wxPaintEvent&)
{
wxPaintDC dc(this);
dc.SetPen(wxPen(GRAY_LINES_COLOR));
#ifndef __WXMSW__
dc.DrawLine(0, 0, 0, dc.GetSize().y-1);
#endif
#ifndef __WXOSX__
dc.DrawLine(0, 0, dc.GetSize().x - 1, 0);
#endif
}
<commit_msg>Consistently use C+11 'override' in sidebar.cpp<commit_after>/*
* This file is part of Poedit (http://poedit.net)
*
* Copyright (C) 2014 Vaclav Slavik
*
* 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.
*
*/
#include "sidebar.h"
#include "catalog.h"
#include "customcontrols.h"
#include "commentdlg.h"
#include <wx/button.h>
#include <wx/dcclient.h>
#include <wx/sizer.h>
#include <wx/stattext.h>
#define SIDEBAR_BACKGROUND wxColour("#EDF0F4")
#define GRAY_LINES_COLOR wxColour(220,220,220)
#define GRAY_LINES_COLOR_DARK wxColour(180,180,180)
class SidebarSeparator : public wxWindow
{
public:
SidebarSeparator(wxWindow *parent)
: wxWindow(parent, wxID_ANY),
m_sides(SIDEBAR_BACKGROUND),
m_center(GRAY_LINES_COLOR_DARK)
{
Bind(wxEVT_PAINT, &SidebarSeparator::OnPaint, this);
}
wxSize DoGetBestSize() const override
{
return wxSize(-1, 1);
}
private:
void OnPaint(wxPaintEvent&)
{
wxPaintDC dc(this);
auto w = dc.GetSize().x;
dc.GradientFillLinear(wxRect(0,0,15,1), m_sides, m_center);
dc.GradientFillLinear(wxRect(15,0,w,1), m_center, m_sides);
}
wxColour m_sides, m_center;
};
SidebarBlock::SidebarBlock(wxWindow *parent, const wxString& label)
{
m_sizer = new wxBoxSizer(wxVERTICAL);
m_sizer->AddSpacer(15);
if (!label.empty())
{
m_sizer->Add(new SidebarSeparator(parent),
wxSizerFlags().Expand().Border(wxBOTTOM|wxLEFT, 2));
m_sizer->Add(new HeadingLabel(parent, label),
wxSizerFlags().Expand().DoubleBorder(wxLEFT|wxRIGHT));
}
m_innerSizer = new wxBoxSizer(wxVERTICAL);
m_sizer->Add(m_innerSizer, wxSizerFlags(1).Expand().DoubleBorder(wxLEFT|wxRIGHT));
}
void SidebarBlock::Show(bool show)
{
m_sizer->ShowItems(show);
}
void SidebarBlock::SetItem(CatalogItem *item)
{
if (!item)
{
Show(false);
return;
}
bool use = ShouldShowForItem(item);
if (use)
Update(item);
Show(use);
}
class OldMsgidSidebarBlock : public SidebarBlock
{
public:
OldMsgidSidebarBlock(wxWindow *parent)
/// TRANSLATORS: "Previous" as in used in the past, now replaced with newer.
: SidebarBlock(parent, _("Previous source text:"))
{
m_innerSizer->AddSpacer(2);
m_innerSizer->Add(new ExplanationLabel(parent, _("The old source text (before it changed during an update) that the fuzzy translation corresponds to.")),
wxSizerFlags().Expand());
m_innerSizer->AddSpacer(5);
m_text = new AutoWrappingText(parent, "");
m_innerSizer->Add(m_text, wxSizerFlags().Expand());
}
bool ShouldShowForItem(CatalogItem *item) const override
{
return item->HasOldMsgid();
}
void Update(CatalogItem *item) override
{
auto txt = wxJoin(item->GetOldMsgid(), ' ', '\0');
m_text->SetAndWrapLabel(txt);
}
private:
AutoWrappingText *m_text;
};
class AutoCommentSidebarBlock : public SidebarBlock
{
public:
AutoCommentSidebarBlock(wxWindow *parent)
: SidebarBlock(parent, _("Notes for translators:"))
{
m_innerSizer->AddSpacer(5);
m_comment = new AutoWrappingText(parent, "");
m_innerSizer->Add(m_comment, wxSizerFlags().Expand());
}
bool ShouldShowForItem(CatalogItem *item) const override
{
return item->HasAutoComments();
}
void Update(CatalogItem *item) override
{
auto comment = wxJoin(item->GetAutoComments(), ' ', '\0');
if (comment.StartsWith("TRANSLATORS:") || comment.StartsWith("translators:"))
{
comment.Remove(0, 12);
if (!comment.empty() && comment[0] == ' ')
comment.Remove(0, 1);
}
m_comment->SetAndWrapLabel(comment);
}
private:
AutoWrappingText *m_comment;
};
class CommentSidebarBlock : public SidebarBlock
{
public:
CommentSidebarBlock(wxWindow *parent)
: SidebarBlock(parent, _("Comment:"))
{
m_innerSizer->AddSpacer(5);
m_comment = new AutoWrappingText(parent, "");
m_innerSizer->Add(m_comment, wxSizerFlags().Expand());
}
bool ShouldShowForItem(CatalogItem *item) const override
{
return item->HasComment();
}
void Update(CatalogItem *item) override
{
auto text = CommentDialog::RemoveStartHash(item->GetComment());
text.Trim();
m_comment->SetAndWrapLabel(text);
}
private:
AutoWrappingText *m_comment;
};
class AddCommentSidebarBlock : public SidebarBlock
{
public:
AddCommentSidebarBlock(wxWindow *parent) : SidebarBlock(parent, "")
{
#ifdef __WXMSW__
auto label = _("Add comment");
#else
auto label = _("Add Comment");
#endif
m_btn = new wxButton(parent, XRCID("menu_comment"), _("Add Comment"));
m_innerSizer->AddStretchSpacer();
m_innerSizer->Add(m_btn, wxSizerFlags().Right());
}
bool IsGrowable() const override { return true; }
bool ShouldShowForItem(CatalogItem*) const override { return true; }
void Update(CatalogItem *item) override
{
#ifdef __WXMSW__
auto add = _("Add comment");
auto edit = _("Edit comment");
#else
auto add = _("Add Comment");
auto edit = _("Edit Comment");
#endif
m_btn->SetLabel(item->HasComment() ? edit : add);
}
private:
wxButton *m_btn;
};
Sidebar::Sidebar(wxWindow *parent)
: wxPanel(parent, wxID_ANY),
m_selectedItem(nullptr)
{
SetBackgroundColour(SIDEBAR_BACKGROUND);
Bind(wxEVT_PAINT, &Sidebar::OnPaint, this);
#ifdef __WXOSX__
SetWindowVariant(wxWINDOW_VARIANT_SMALL);
#endif
auto *topSizer = new wxBoxSizer(wxVERTICAL);
topSizer->SetMinSize(wxSize(300, -1));
m_blocksSizer = new wxBoxSizer(wxVERTICAL);
topSizer->Add(m_blocksSizer, wxSizerFlags(1).Expand().DoubleBorder(wxTOP|wxBOTTOM));
m_topBlocksSizer = new wxBoxSizer(wxVERTICAL);
m_bottomBlocksSizer = new wxBoxSizer(wxVERTICAL);
m_blocksSizer->Add(m_topBlocksSizer, wxSizerFlags().Expand());
m_blocksSizer->AddStretchSpacer();
m_blocksSizer->Add(m_bottomBlocksSizer, wxSizerFlags().Expand());
AddBlock(new OldMsgidSidebarBlock(this), Bottom);
AddBlock(new AutoCommentSidebarBlock(this), Bottom);
AddBlock(new CommentSidebarBlock(this), Bottom);
AddBlock(new AddCommentSidebarBlock(this), Bottom);
SetSizerAndFit(topSizer);
SetSelectedItem(nullptr);
}
void Sidebar::AddBlock(SidebarBlock *block, BlockPos pos)
{
m_blocks.emplace_back(block);
auto sizer = (pos == Top) ? m_topBlocksSizer : m_bottomBlocksSizer;
auto grow = (block->IsGrowable()) ? 1 : 0;
sizer->Add(block->GetSizer(), wxSizerFlags(grow).Expand());
}
Sidebar::~Sidebar()
{
}
void Sidebar::SetSelectedItem(CatalogItem *item)
{
m_selectedItem = item;
RefreshContent();
}
void Sidebar::SetMultipleSelection()
{
SetSelectedItem(nullptr);
}
void Sidebar::RefreshContent()
{
for (auto& b: m_blocks)
b->SetItem(m_selectedItem);
Layout();
}
void Sidebar::SetUpperHeight(int size)
{
int pos = GetSize().y - size;
#ifdef __WXOSX__
pos += 4;
#else
pos += 6;
#endif
m_bottomBlocksSizer->SetMinSize(wxSize(-1, pos));
Layout();
}
void Sidebar::OnPaint(wxPaintEvent&)
{
wxPaintDC dc(this);
dc.SetPen(wxPen(GRAY_LINES_COLOR));
#ifndef __WXMSW__
dc.DrawLine(0, 0, 0, dc.GetSize().y-1);
#endif
#ifndef __WXOSX__
dc.DrawLine(0, 0, dc.GetSize().x - 1, 0);
#endif
}
<|endoftext|>
|
<commit_before>// Copyright 2012 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 "config.h"
#include "CCActiveAnimation.h"
#include "CCAnimationCurve.h"
#include "TraceEvent.h"
#ifdef LOG
#undef LOG
#endif
#include "base/string_util.h"
#include <cmath>
#include <wtf/Assertions.h>
#include <wtf/StdLibExtras.h>
namespace {
// This should match the RunState enum.
static const char* const s_runStateNames[] = {
"WaitingForNextTick",
"WaitingForTargetAvailability",
"WaitingForStartTime",
"WaitingForDeletion",
"Running",
"Paused",
"Finished",
"Aborted"
};
COMPILE_ASSERT(static_cast<int>(cc::CCActiveAnimation::RunStateEnumSize) == WTF_ARRAY_LENGTH(s_runStateNames), RunState_names_match_enum);
// This should match the TargetProperty enum.
static const char* const s_targetPropertyNames[] = {
"Transform",
"Opacity"
};
COMPILE_ASSERT(static_cast<int>(cc::CCActiveAnimation::TargetPropertyEnumSize) == WTF_ARRAY_LENGTH(s_targetPropertyNames), TargetProperty_names_match_enum);
} // namespace
namespace cc {
PassOwnPtr<CCActiveAnimation> CCActiveAnimation::create(PassOwnPtr<CCAnimationCurve> curve, int animationId, int groupId, TargetProperty targetProperty)
{
return adoptPtr(new CCActiveAnimation(curve, animationId, groupId, targetProperty));
}
CCActiveAnimation::CCActiveAnimation(PassOwnPtr<CCAnimationCurve> curve, int animationId, int groupId, TargetProperty targetProperty)
: m_curve(curve)
, m_id(animationId)
, m_group(groupId)
, m_targetProperty(targetProperty)
, m_runState(WaitingForTargetAvailability)
, m_iterations(1)
, m_startTime(0)
, m_alternatesDirection(false)
, m_timeOffset(0)
, m_needsSynchronizedStartTime(false)
, m_suspended(false)
, m_pauseTime(0)
, m_totalPausedTime(0)
, m_isControllingInstance(false)
{
}
CCActiveAnimation::~CCActiveAnimation()
{
if (m_runState == Running || m_runState == Paused)
setRunState(Aborted, 0);
}
void CCActiveAnimation::setRunState(RunState runState, double monotonicTime)
{
if (m_suspended)
return;
char nameBuffer[256];
base::snprintf(nameBuffer, sizeof(nameBuffer), "%s-%d%s", s_targetPropertyNames[m_targetProperty], m_group, m_isControllingInstance ? "(impl)" : "");
bool isWaitingToStart = m_runState == WaitingForNextTick
|| m_runState == WaitingForTargetAvailability
|| m_runState == WaitingForStartTime;
if (isWaitingToStart && runState == Running)
TRACE_EVENT_ASYNC_BEGIN1("cc", "CCActiveAnimation", this, "Name", TRACE_STR_COPY(nameBuffer));
bool wasFinished = isFinished();
const char* oldRunStateName = s_runStateNames[m_runState];
if (runState == Running && m_runState == Paused)
m_totalPausedTime += monotonicTime - m_pauseTime;
else if (runState == Paused)
m_pauseTime = monotonicTime;
m_runState = runState;
const char* newRunStateName = s_runStateNames[runState];
if (!wasFinished && isFinished())
TRACE_EVENT_ASYNC_END0("cc", "CCActiveAnimation", this);
char stateBuffer[256];
base::snprintf(stateBuffer, sizeof(stateBuffer), "%s->%s", oldRunStateName, newRunStateName);
TRACE_EVENT_INSTANT2("cc", "CCLayerAnimationController::setRunState", "Name", TRACE_STR_COPY(nameBuffer), "State", TRACE_STR_COPY(stateBuffer));
}
void CCActiveAnimation::suspend(double monotonicTime)
{
setRunState(Paused, monotonicTime);
m_suspended = true;
}
void CCActiveAnimation::resume(double monotonicTime)
{
m_suspended = false;
setRunState(Running, monotonicTime);
}
bool CCActiveAnimation::isFinishedAt(double monotonicTime) const
{
if (isFinished())
return true;
if (m_needsSynchronizedStartTime)
return false;
return m_runState == Running
&& m_iterations >= 0
&& m_iterations * m_curve->duration() <= monotonicTime - startTime() - m_totalPausedTime;
}
double CCActiveAnimation::trimTimeToCurrentIteration(double monotonicTime) const
{
double trimmed = monotonicTime + m_timeOffset;
// If we're paused, time is 'stuck' at the pause time.
if (m_runState == Paused)
trimmed = m_pauseTime;
// Returned time should always be relative to the start time and should subtract
// all time spent paused.
trimmed -= m_startTime + m_totalPausedTime;
// Zero is always the start of the animation.
if (trimmed <= 0)
return 0;
// Always return zero if we have no iterations.
if (!m_iterations)
return 0;
// Don't attempt to trim if we have no duration.
if (m_curve->duration() <= 0)
return 0;
// If less than an iteration duration, just return trimmed.
if (trimmed < m_curve->duration())
return trimmed;
// If greater than or equal to the total duration, return iteration duration.
if (m_iterations >= 0 && trimmed >= m_curve->duration() * m_iterations) {
if (m_alternatesDirection && !(m_iterations % 2))
return 0;
return m_curve->duration();
}
// We need to know the current iteration if we're alternating.
int iteration = static_cast<int>(trimmed / m_curve->duration());
// Calculate x where trimmed = x + n * m_curve->duration() for some positive integer n.
trimmed = fmod(trimmed, m_curve->duration());
// If we're alternating and on an odd iteration, reverse the direction.
if (m_alternatesDirection && iteration % 2 == 1)
return m_curve->duration() - trimmed;
return trimmed;
}
PassOwnPtr<CCActiveAnimation> CCActiveAnimation::clone(InstanceType instanceType) const
{
return cloneAndInitialize(instanceType, m_runState, m_startTime);
}
PassOwnPtr<CCActiveAnimation> CCActiveAnimation::cloneAndInitialize(InstanceType instanceType, RunState initialRunState, double startTime) const
{
OwnPtr<CCActiveAnimation> toReturn(adoptPtr(new CCActiveAnimation(m_curve->clone(), m_id, m_group, m_targetProperty)));
toReturn->m_runState = initialRunState;
toReturn->m_iterations = m_iterations;
toReturn->m_startTime = startTime;
toReturn->m_pauseTime = m_pauseTime;
toReturn->m_totalPausedTime = m_totalPausedTime;
toReturn->m_timeOffset = m_timeOffset;
toReturn->m_alternatesDirection = m_alternatesDirection;
toReturn->m_isControllingInstance = instanceType == ControllingInstance;
return toReturn.release();
}
void CCActiveAnimation::pushPropertiesTo(CCActiveAnimation* other) const
{
// Currently, we only push changes due to pausing and resuming animations on the main thread.
if (m_runState == CCActiveAnimation::Paused || other->m_runState == CCActiveAnimation::Paused) {
other->m_runState = m_runState;
other->m_pauseTime = m_pauseTime;
other->m_totalPausedTime = m_totalPausedTime;
}
}
} // namespace cc
<commit_msg>cc: Get rid of two more wtf header includes.<commit_after>// Copyright 2012 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 "config.h"
#include "CCActiveAnimation.h"
#include "CCAnimationCurve.h"
#include "TraceEvent.h"
#ifdef LOG
#undef LOG
#endif
#include "base/string_util.h"
#include <cmath>
namespace {
// This should match the RunState enum.
static const char* const s_runStateNames[] = {
"WaitingForNextTick",
"WaitingForTargetAvailability",
"WaitingForStartTime",
"WaitingForDeletion",
"Running",
"Paused",
"Finished",
"Aborted"
};
COMPILE_ASSERT(static_cast<int>(cc::CCActiveAnimation::RunStateEnumSize) == arraysize(s_runStateNames), RunState_names_match_enum);
// This should match the TargetProperty enum.
static const char* const s_targetPropertyNames[] = {
"Transform",
"Opacity"
};
COMPILE_ASSERT(static_cast<int>(cc::CCActiveAnimation::TargetPropertyEnumSize) == arraysize(s_targetPropertyNames), TargetProperty_names_match_enum);
} // namespace
namespace cc {
PassOwnPtr<CCActiveAnimation> CCActiveAnimation::create(PassOwnPtr<CCAnimationCurve> curve, int animationId, int groupId, TargetProperty targetProperty)
{
return adoptPtr(new CCActiveAnimation(curve, animationId, groupId, targetProperty));
}
CCActiveAnimation::CCActiveAnimation(PassOwnPtr<CCAnimationCurve> curve, int animationId, int groupId, TargetProperty targetProperty)
: m_curve(curve)
, m_id(animationId)
, m_group(groupId)
, m_targetProperty(targetProperty)
, m_runState(WaitingForTargetAvailability)
, m_iterations(1)
, m_startTime(0)
, m_alternatesDirection(false)
, m_timeOffset(0)
, m_needsSynchronizedStartTime(false)
, m_suspended(false)
, m_pauseTime(0)
, m_totalPausedTime(0)
, m_isControllingInstance(false)
{
}
CCActiveAnimation::~CCActiveAnimation()
{
if (m_runState == Running || m_runState == Paused)
setRunState(Aborted, 0);
}
void CCActiveAnimation::setRunState(RunState runState, double monotonicTime)
{
if (m_suspended)
return;
char nameBuffer[256];
base::snprintf(nameBuffer, sizeof(nameBuffer), "%s-%d%s", s_targetPropertyNames[m_targetProperty], m_group, m_isControllingInstance ? "(impl)" : "");
bool isWaitingToStart = m_runState == WaitingForNextTick
|| m_runState == WaitingForTargetAvailability
|| m_runState == WaitingForStartTime;
if (isWaitingToStart && runState == Running)
TRACE_EVENT_ASYNC_BEGIN1("cc", "CCActiveAnimation", this, "Name", TRACE_STR_COPY(nameBuffer));
bool wasFinished = isFinished();
const char* oldRunStateName = s_runStateNames[m_runState];
if (runState == Running && m_runState == Paused)
m_totalPausedTime += monotonicTime - m_pauseTime;
else if (runState == Paused)
m_pauseTime = monotonicTime;
m_runState = runState;
const char* newRunStateName = s_runStateNames[runState];
if (!wasFinished && isFinished())
TRACE_EVENT_ASYNC_END0("cc", "CCActiveAnimation", this);
char stateBuffer[256];
base::snprintf(stateBuffer, sizeof(stateBuffer), "%s->%s", oldRunStateName, newRunStateName);
TRACE_EVENT_INSTANT2("cc", "CCLayerAnimationController::setRunState", "Name", TRACE_STR_COPY(nameBuffer), "State", TRACE_STR_COPY(stateBuffer));
}
void CCActiveAnimation::suspend(double monotonicTime)
{
setRunState(Paused, monotonicTime);
m_suspended = true;
}
void CCActiveAnimation::resume(double monotonicTime)
{
m_suspended = false;
setRunState(Running, monotonicTime);
}
bool CCActiveAnimation::isFinishedAt(double monotonicTime) const
{
if (isFinished())
return true;
if (m_needsSynchronizedStartTime)
return false;
return m_runState == Running
&& m_iterations >= 0
&& m_iterations * m_curve->duration() <= monotonicTime - startTime() - m_totalPausedTime;
}
double CCActiveAnimation::trimTimeToCurrentIteration(double monotonicTime) const
{
double trimmed = monotonicTime + m_timeOffset;
// If we're paused, time is 'stuck' at the pause time.
if (m_runState == Paused)
trimmed = m_pauseTime;
// Returned time should always be relative to the start time and should subtract
// all time spent paused.
trimmed -= m_startTime + m_totalPausedTime;
// Zero is always the start of the animation.
if (trimmed <= 0)
return 0;
// Always return zero if we have no iterations.
if (!m_iterations)
return 0;
// Don't attempt to trim if we have no duration.
if (m_curve->duration() <= 0)
return 0;
// If less than an iteration duration, just return trimmed.
if (trimmed < m_curve->duration())
return trimmed;
// If greater than or equal to the total duration, return iteration duration.
if (m_iterations >= 0 && trimmed >= m_curve->duration() * m_iterations) {
if (m_alternatesDirection && !(m_iterations % 2))
return 0;
return m_curve->duration();
}
// We need to know the current iteration if we're alternating.
int iteration = static_cast<int>(trimmed / m_curve->duration());
// Calculate x where trimmed = x + n * m_curve->duration() for some positive integer n.
trimmed = fmod(trimmed, m_curve->duration());
// If we're alternating and on an odd iteration, reverse the direction.
if (m_alternatesDirection && iteration % 2 == 1)
return m_curve->duration() - trimmed;
return trimmed;
}
PassOwnPtr<CCActiveAnimation> CCActiveAnimation::clone(InstanceType instanceType) const
{
return cloneAndInitialize(instanceType, m_runState, m_startTime);
}
PassOwnPtr<CCActiveAnimation> CCActiveAnimation::cloneAndInitialize(InstanceType instanceType, RunState initialRunState, double startTime) const
{
OwnPtr<CCActiveAnimation> toReturn(adoptPtr(new CCActiveAnimation(m_curve->clone(), m_id, m_group, m_targetProperty)));
toReturn->m_runState = initialRunState;
toReturn->m_iterations = m_iterations;
toReturn->m_startTime = startTime;
toReturn->m_pauseTime = m_pauseTime;
toReturn->m_totalPausedTime = m_totalPausedTime;
toReturn->m_timeOffset = m_timeOffset;
toReturn->m_alternatesDirection = m_alternatesDirection;
toReturn->m_isControllingInstance = instanceType == ControllingInstance;
return toReturn.release();
}
void CCActiveAnimation::pushPropertiesTo(CCActiveAnimation* other) const
{
// Currently, we only push changes due to pausing and resuming animations on the main thread.
if (m_runState == CCActiveAnimation::Paused || other->m_runState == CCActiveAnimation::Paused) {
other->m_runState = m_runState;
other->m_pauseTime = m_pauseTime;
other->m_totalPausedTime = m_totalPausedTime;
}
}
} // namespace cc
<|endoftext|>
|
<commit_before>/*-------------------------------------------------------------------------
*
* FILE
* strconv.cxx
*
* DESCRIPTION
* implementation of string conversions
*
* Copyright (c) 2008-2012, 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-internal.hxx"
#include <cstring>
#ifdef PQXX_HAVE_LIMITS
#include <limits>
#endif
#ifdef PQXX_HAVE_LOCALE
#include <locale>
#endif
#include "pqxx/except"
#include "pqxx/strconv"
using namespace PGSTD;
using namespace pqxx::internal;
namespace
{
// It turns out that NaNs are pretty hard to do portably. If the appropriate
// C++ traits functions are not available, C99 defines a NAN macro (also widely
// supported in other dialects, I believe) and some functions that can do the
// same work. But if none of those are available, we need to resort to
// compile-time "0/0" expressions. Most compilers won't crash while compiling
// those anymore, but there may be unneeded warnings--which are almost as bad.
template<typename T> void set_to_NaN(T &);
#if defined(PQXX_HAVE_QUIET_NAN)
template<typename T> inline void set_to_NaN(T &t)
{ t = numeric_limits<T>::quiet_NaN(); }
#elif defined(PQXX_HAVE_C_NAN)
template<typename T> inline void set_to_NaN(T &t) { t = NAN; }
#elif defined(PQXX_HAVE_NAN)
template<> inline void set_to_NaN(float &t) { t = fnan(""); }
template<> inline void set_to_NaN(double &t) { t = nan(""); }
#ifdef PQXX_HAVE_LONG_DOUBLE
template<> inline void set_to_NaN(long double &t) { t = lnan(""); }
#endif
#else
const float nan_f(0.0/0.0);
template<> inline void set_to_NaN(float &t) { t = nan_f; }
const double nan_d(0.0/0.0);
template<> inline void set_to_NaN(double &t) { t = nan_d; }
#ifdef PQXX_HAVE_LONG_DOUBLE
const long double nan_ld(0.0/0.0);
template<> inline void set_to_NaN(long double &t) { t = nan_ld; }
#endif
#endif
// TODO: This may need tweaking for various compilers.
template<typename T> inline void set_to_Inf(T &t, int sign=1)
{
#ifdef PQXX_HAVE_LIMITS
T value = numeric_limits<T>::infinity();
#else
T value = INFINITY;
#endif
if (sign < 0) value = -value;
t = value;
}
void report_overflow()
{
throw pqxx::failure(
"Could not convert string to integer: value out of range.");
}
/** Helper to check for underflow before multiplying a number by 10.
*
* Needed just so the compiler doesn't get to complain about an "if (n < 0)"
* clause that's pointless for unsigned numbers.
*/
template<typename T, bool is_signed> struct underflow_check;
/* Specialization for signed types: check.
*/
template<typename T> struct underflow_check<T, true>
{
static void check_before_adding_digit(T n)
{
const T ten(10);
if (n < 0 && (numeric_limits<T>::min() / ten) > n) report_overflow();
}
};
/* Specialization for unsigned types: no check needed becaue negative
* numbers don't exist.
*/
template<typename T> struct underflow_check<T, false>
{
static void check_before_adding_digit(T) {}
};
/// Return 10*n, or throw exception if it overflows.
template<typename T> T safe_multiply_by_ten(T n)
{
const T ten(10);
if (n > 0 && (numeric_limits<T>::max() / n) < ten) report_overflow();
underflow_check<T, numeric_limits<T>::is_signed>::check_before_adding_digit(
n);
return T(n * ten);
}
/// Add a digit d to n, or throw exception if it overflows.
template<typename T> T safe_add_digit(T n, T d)
{
assert((n >= 0 && d >= 0) || (n <=0 && d <= 0));
if ((n > 0) && (n > (numeric_limits<T>::max() - d))) report_overflow();
if ((n < 0) && (n < (numeric_limits<T>::min() - d))) report_overflow();
return n + d;
}
/// For use in string parsing: add new numeric digit to intermediate value
template<typename L, typename R>
inline L absorb_digit(L value, R digit)
{
return L(safe_multiply_by_ten(value) + L(digit));
}
template<typename T> void from_string_signed(const char Str[], T &Obj)
{
int i = 0;
T result = 0;
if (!isdigit(Str[i]))
{
if (Str[i] != '-')
throw pqxx::failure("Could not convert string to integer: '" +
string(Str) + "'");
for (++i; isdigit(Str[i]); ++i)
result = absorb_digit(result, -digit_to_number(Str[i]));
}
else for (; isdigit(Str[i]); ++i)
result = absorb_digit(result, digit_to_number(Str[i]));
if (Str[i])
throw pqxx::failure("Unexpected text after integer: '" + string(Str) + "'");
Obj = result;
}
template<typename T> void from_string_unsigned(const char Str[], T &Obj)
{
int i = 0;
T result = 0;
if (!isdigit(Str[i]))
throw pqxx::failure("Could not convert string to unsigned integer: '" +
string(Str) + "'");
for (; isdigit(Str[i]); ++i)
result = absorb_digit(result, digit_to_number(Str[i]));
if (Str[i])
throw pqxx::failure("Unexpected text after integer: '" + string(Str) + "'");
Obj = result;
}
bool valid_infinity_string(const char str[])
{
// TODO: Also accept less sensible case variations.
return
strcmp("infinity", str) == 0 ||
strcmp("Infinity", str) == 0 ||
strcmp("INFINITY", str) == 0 ||
strcmp("inf", str) == 0;
}
/* These are hard. Sacrifice performance of specialized, nonflexible,
* non-localized code and lean on standard library. Some special-case code
* handles NaNs.
*/
template<typename T> inline void from_string_float(const char Str[], T &Obj)
{
bool ok = false;
T result;
switch (Str[0])
{
case 'N':
case 'n':
// Accept "NaN," "nan," etc.
ok = ((Str[1]=='A'||Str[1]=='a') && (Str[2]=='N'||Str[2]=='n') && !Str[3]);
set_to_NaN(result);
break;
case 'I':
case 'i':
ok = valid_infinity_string(Str);
set_to_Inf(result);
break;
default:
if (Str[0] == '-' && valid_infinity_string(&Str[1]))
{
ok = true;
set_to_Inf(result, -1);
}
else
{
stringstream S(Str);
#if defined(PQXX_HAVE_IMBUE)
S.imbue(locale("C"));
#endif
ok = static_cast<bool>(S >> result);
}
break;
}
if (!ok)
throw pqxx::failure("Could not convert string to numeric value: '" +
string(Str) + "'");
Obj = result;
}
template<typename T> inline string to_string_unsigned(T Obj)
{
if (!Obj) return "0";
// Every byte of width on T adds somewhere between 3 and 4 digits to the
// maximum length of our decimal string.
char buf[4*sizeof(T)+1];
char *p = &buf[sizeof(buf)];
*--p = '\0';
while (Obj > 0)
{
*--p = number_to_digit(int(Obj%10));
Obj /= 10;
}
return p;
}
template<typename T> inline string to_string_fallback(T Obj)
{
stringstream S;
#ifdef PQXX_HAVE_IMBUE
S.imbue(locale("C"));
#endif
// Provide enough precision.
#ifdef PQXX_HAVE_LIMITS
// Kirit reports getting two more digits of precision than
// numeric_limits::digits10 would give him, so we try not to make him lose
// those last few bits.
S.precision(numeric_limits<T>::digits10 + 2);
#else
// Guess: enough for an IEEE 754 double-precision value.
S.precision(16);
#endif
S << Obj;
return S.str();
}
template<typename T> inline bool is_NaN(T Obj)
{
return
#if defined(PQXX_HAVE_C_ISNAN)
isnan(Obj);
#elif defined(PQXX_HAVE_LIMITS)
!(Obj <= Obj+numeric_limits<T>::max());
#else
!(Obj <= Obj + 1000);
#endif
}
template<typename T> inline bool is_Inf(T Obj)
{
return
#if defined(PQXX_HAVE_C_ISINF)
isinf(Obj);
#else
Obj >= Obj+1 && Obj <= 2*Obj && Obj >= 2*Obj;
#endif
}
template<typename T> inline string to_string_float(T Obj)
{
// TODO: Omit this special case if NaN is output as "nan"/"NAN"/"NaN"
#ifndef PQXX_HAVE_NAN_OUTPUT
if (is_NaN(Obj)) return "nan";
#endif
// TODO: Omit this special case if infinity is output as "infinity"
#ifndef PQXX_HAVE_INF_OUTPUT
if (is_Inf(Obj)) return Obj > 0 ? "infinity" : "-infinity";
#endif
return to_string_fallback(Obj);
}
template<typename T> inline string to_string_signed(T Obj)
{
if (Obj < 0)
{
// Remember--the smallest negative number for a given two's-complement type
// cannot be negated.
#if PQXX_HAVE_LIMITS
const bool negatable = (Obj != numeric_limits<T>::min());
#else
T Neg(-Obj);
const bool negatable = Neg > 0;
#endif
if (negatable)
return '-' + to_string_unsigned(-Obj);
else
return to_string_fallback(Obj);
}
return to_string_unsigned(Obj);
}
} // namespace
namespace pqxx
{
namespace internal
{
void throw_null_conversion(const PGSTD::string &type)
{
throw conversion_error("Attempt to convert null to " + type);
}
} // namespace pqxx::internal
void string_traits<bool>::from_string(const char Str[], bool &Obj)
{
bool OK, result=false;
switch (Str[0])
{
case 0:
result = false;
OK = true;
break;
case 'f':
case 'F':
result = false;
OK = !(Str[1] &&
(strcmp(Str+1, "alse") != 0) &&
(strcmp(Str+1, "ALSE") != 0));
break;
case '0':
{
int I;
string_traits<int>::from_string(Str, I);
result = (I != 0);
OK = ((I == 0) || (I == 1));
}
break;
case '1':
result = true;
OK = !Str[1];
break;
case 't':
case 'T':
result = true;
OK = !(Str[1] &&
(strcmp(Str+1, "rue") != 0) &&
(strcmp(Str+1, "RUE") != 0));
break;
default:
OK = false;
}
if (!OK)
throw argument_error("Failed conversion to bool: '" + string(Str) + "'");
Obj = result;
}
string string_traits<bool>::to_string(bool Obj)
{
return Obj ? "true" : "false";
}
void string_traits<short>::from_string(const char Str[], short &Obj)
{
from_string_signed(Str, Obj);
}
string string_traits<short>::to_string(short Obj)
{
return to_string_signed(Obj);
}
void string_traits<unsigned short>::from_string(
const char Str[],
unsigned short &Obj)
{
from_string_unsigned(Str, Obj);
}
string string_traits<unsigned short>::to_string(unsigned short Obj)
{
return to_string_unsigned(Obj);
}
void string_traits<int>::from_string(const char Str[], int &Obj)
{
from_string_signed(Str, Obj);
}
string string_traits<int>::to_string(int Obj)
{
return to_string_signed(Obj);
}
void string_traits<unsigned int>::from_string(
const char Str[],
unsigned int &Obj)
{
from_string_unsigned(Str, Obj);
}
string string_traits<unsigned int>::to_string(unsigned int Obj)
{
return to_string_unsigned(Obj);
}
void string_traits<long>::from_string(const char Str[], long &Obj)
{
from_string_signed(Str, Obj);
}
string string_traits<long>::to_string(long Obj)
{
return to_string_signed(Obj);
}
void string_traits<unsigned long>::from_string(
const char Str[],
unsigned long &Obj)
{
from_string_unsigned(Str, Obj);
}
string string_traits<unsigned long>::to_string(unsigned long Obj)
{
return to_string_unsigned(Obj);
}
#ifdef PQXX_HAVE_LONG_LONG
void string_traits<long long>::from_string(const char Str[], long long &Obj)
{
from_string_signed(Str, Obj);
}
string string_traits<long long>::to_string(long long Obj)
{
return to_string_signed(Obj);
}
void string_traits<unsigned long long>::from_string(
const char Str[],
unsigned long long &Obj)
{
from_string_unsigned(Str, Obj);
}
string string_traits<unsigned long long>::to_string(unsigned long long Obj)
{
return to_string_unsigned(Obj);
}
#endif
void string_traits<float>::from_string(const char Str[], float &Obj)
{
from_string_float(Str, Obj);
}
string string_traits<float>::to_string(float Obj)
{
return to_string_float(Obj);
}
void string_traits<double>::from_string(const char Str[], double &Obj)
{
from_string_float(Str, Obj);
}
string string_traits<double>::to_string(double Obj)
{
return to_string_float(Obj);
}
#ifdef PQXX_HAVE_LONG_DOUBLE
void string_traits<long double>::from_string(const char Str[], long double &Obj)
{
from_string_float(Str, Obj);
}
string string_traits<long double>::to_string(long double Obj)
{
return to_string_float(Obj);
}
#endif
} // namespace pqxx
<commit_msg>Copyright update.<commit_after>/*-------------------------------------------------------------------------
*
* FILE
* strconv.cxx
*
* DESCRIPTION
* implementation of string conversions
*
* Copyright (c) 2008-2013, 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-internal.hxx"
#include <cstring>
#ifdef PQXX_HAVE_LIMITS
#include <limits>
#endif
#ifdef PQXX_HAVE_LOCALE
#include <locale>
#endif
#include "pqxx/except"
#include "pqxx/strconv"
using namespace PGSTD;
using namespace pqxx::internal;
namespace
{
// It turns out that NaNs are pretty hard to do portably. If the appropriate
// C++ traits functions are not available, C99 defines a NAN macro (also widely
// supported in other dialects, I believe) and some functions that can do the
// same work. But if none of those are available, we need to resort to
// compile-time "0/0" expressions. Most compilers won't crash while compiling
// those anymore, but there may be unneeded warnings--which are almost as bad.
template<typename T> void set_to_NaN(T &);
#if defined(PQXX_HAVE_QUIET_NAN)
template<typename T> inline void set_to_NaN(T &t)
{ t = numeric_limits<T>::quiet_NaN(); }
#elif defined(PQXX_HAVE_C_NAN)
template<typename T> inline void set_to_NaN(T &t) { t = NAN; }
#elif defined(PQXX_HAVE_NAN)
template<> inline void set_to_NaN(float &t) { t = fnan(""); }
template<> inline void set_to_NaN(double &t) { t = nan(""); }
#ifdef PQXX_HAVE_LONG_DOUBLE
template<> inline void set_to_NaN(long double &t) { t = lnan(""); }
#endif
#else
const float nan_f(0.0/0.0);
template<> inline void set_to_NaN(float &t) { t = nan_f; }
const double nan_d(0.0/0.0);
template<> inline void set_to_NaN(double &t) { t = nan_d; }
#ifdef PQXX_HAVE_LONG_DOUBLE
const long double nan_ld(0.0/0.0);
template<> inline void set_to_NaN(long double &t) { t = nan_ld; }
#endif
#endif
// TODO: This may need tweaking for various compilers.
template<typename T> inline void set_to_Inf(T &t, int sign=1)
{
#ifdef PQXX_HAVE_LIMITS
T value = numeric_limits<T>::infinity();
#else
T value = INFINITY;
#endif
if (sign < 0) value = -value;
t = value;
}
void report_overflow()
{
throw pqxx::failure(
"Could not convert string to integer: value out of range.");
}
/** Helper to check for underflow before multiplying a number by 10.
*
* Needed just so the compiler doesn't get to complain about an "if (n < 0)"
* clause that's pointless for unsigned numbers.
*/
template<typename T, bool is_signed> struct underflow_check;
/* Specialization for signed types: check.
*/
template<typename T> struct underflow_check<T, true>
{
static void check_before_adding_digit(T n)
{
const T ten(10);
if (n < 0 && (numeric_limits<T>::min() / ten) > n) report_overflow();
}
};
/* Specialization for unsigned types: no check needed becaue negative
* numbers don't exist.
*/
template<typename T> struct underflow_check<T, false>
{
static void check_before_adding_digit(T) {}
};
/// Return 10*n, or throw exception if it overflows.
template<typename T> T safe_multiply_by_ten(T n)
{
const T ten(10);
if (n > 0 && (numeric_limits<T>::max() / n) < ten) report_overflow();
underflow_check<T, numeric_limits<T>::is_signed>::check_before_adding_digit(
n);
return T(n * ten);
}
/// Add a digit d to n, or throw exception if it overflows.
template<typename T> T safe_add_digit(T n, T d)
{
assert((n >= 0 && d >= 0) || (n <=0 && d <= 0));
if ((n > 0) && (n > (numeric_limits<T>::max() - d))) report_overflow();
if ((n < 0) && (n < (numeric_limits<T>::min() - d))) report_overflow();
return n + d;
}
/// For use in string parsing: add new numeric digit to intermediate value
template<typename L, typename R>
inline L absorb_digit(L value, R digit)
{
return L(safe_multiply_by_ten(value) + L(digit));
}
template<typename T> void from_string_signed(const char Str[], T &Obj)
{
int i = 0;
T result = 0;
if (!isdigit(Str[i]))
{
if (Str[i] != '-')
throw pqxx::failure("Could not convert string to integer: '" +
string(Str) + "'");
for (++i; isdigit(Str[i]); ++i)
result = absorb_digit(result, -digit_to_number(Str[i]));
}
else for (; isdigit(Str[i]); ++i)
result = absorb_digit(result, digit_to_number(Str[i]));
if (Str[i])
throw pqxx::failure("Unexpected text after integer: '" + string(Str) + "'");
Obj = result;
}
template<typename T> void from_string_unsigned(const char Str[], T &Obj)
{
int i = 0;
T result = 0;
if (!isdigit(Str[i]))
throw pqxx::failure("Could not convert string to unsigned integer: '" +
string(Str) + "'");
for (; isdigit(Str[i]); ++i)
result = absorb_digit(result, digit_to_number(Str[i]));
if (Str[i])
throw pqxx::failure("Unexpected text after integer: '" + string(Str) + "'");
Obj = result;
}
bool valid_infinity_string(const char str[])
{
// TODO: Also accept less sensible case variations.
return
strcmp("infinity", str) == 0 ||
strcmp("Infinity", str) == 0 ||
strcmp("INFINITY", str) == 0 ||
strcmp("inf", str) == 0;
}
/* These are hard. Sacrifice performance of specialized, nonflexible,
* non-localized code and lean on standard library. Some special-case code
* handles NaNs.
*/
template<typename T> inline void from_string_float(const char Str[], T &Obj)
{
bool ok = false;
T result;
switch (Str[0])
{
case 'N':
case 'n':
// Accept "NaN," "nan," etc.
ok = ((Str[1]=='A'||Str[1]=='a') && (Str[2]=='N'||Str[2]=='n') && !Str[3]);
set_to_NaN(result);
break;
case 'I':
case 'i':
ok = valid_infinity_string(Str);
set_to_Inf(result);
break;
default:
if (Str[0] == '-' && valid_infinity_string(&Str[1]))
{
ok = true;
set_to_Inf(result, -1);
}
else
{
stringstream S(Str);
#if defined(PQXX_HAVE_IMBUE)
S.imbue(locale("C"));
#endif
ok = static_cast<bool>(S >> result);
}
break;
}
if (!ok)
throw pqxx::failure("Could not convert string to numeric value: '" +
string(Str) + "'");
Obj = result;
}
template<typename T> inline string to_string_unsigned(T Obj)
{
if (!Obj) return "0";
// Every byte of width on T adds somewhere between 3 and 4 digits to the
// maximum length of our decimal string.
char buf[4*sizeof(T)+1];
char *p = &buf[sizeof(buf)];
*--p = '\0';
while (Obj > 0)
{
*--p = number_to_digit(int(Obj%10));
Obj /= 10;
}
return p;
}
template<typename T> inline string to_string_fallback(T Obj)
{
stringstream S;
#ifdef PQXX_HAVE_IMBUE
S.imbue(locale("C"));
#endif
// Provide enough precision.
#ifdef PQXX_HAVE_LIMITS
// Kirit reports getting two more digits of precision than
// numeric_limits::digits10 would give him, so we try not to make him lose
// those last few bits.
S.precision(numeric_limits<T>::digits10 + 2);
#else
// Guess: enough for an IEEE 754 double-precision value.
S.precision(16);
#endif
S << Obj;
return S.str();
}
template<typename T> inline bool is_NaN(T Obj)
{
return
#if defined(PQXX_HAVE_C_ISNAN)
isnan(Obj);
#elif defined(PQXX_HAVE_LIMITS)
!(Obj <= Obj+numeric_limits<T>::max());
#else
!(Obj <= Obj + 1000);
#endif
}
template<typename T> inline bool is_Inf(T Obj)
{
return
#if defined(PQXX_HAVE_C_ISINF)
isinf(Obj);
#else
Obj >= Obj+1 && Obj <= 2*Obj && Obj >= 2*Obj;
#endif
}
template<typename T> inline string to_string_float(T Obj)
{
// TODO: Omit this special case if NaN is output as "nan"/"NAN"/"NaN"
#ifndef PQXX_HAVE_NAN_OUTPUT
if (is_NaN(Obj)) return "nan";
#endif
// TODO: Omit this special case if infinity is output as "infinity"
#ifndef PQXX_HAVE_INF_OUTPUT
if (is_Inf(Obj)) return Obj > 0 ? "infinity" : "-infinity";
#endif
return to_string_fallback(Obj);
}
template<typename T> inline string to_string_signed(T Obj)
{
if (Obj < 0)
{
// Remember--the smallest negative number for a given two's-complement type
// cannot be negated.
#if PQXX_HAVE_LIMITS
const bool negatable = (Obj != numeric_limits<T>::min());
#else
T Neg(-Obj);
const bool negatable = Neg > 0;
#endif
if (negatable)
return '-' + to_string_unsigned(-Obj);
else
return to_string_fallback(Obj);
}
return to_string_unsigned(Obj);
}
} // namespace
namespace pqxx
{
namespace internal
{
void throw_null_conversion(const PGSTD::string &type)
{
throw conversion_error("Attempt to convert null to " + type);
}
} // namespace pqxx::internal
void string_traits<bool>::from_string(const char Str[], bool &Obj)
{
bool OK, result=false;
switch (Str[0])
{
case 0:
result = false;
OK = true;
break;
case 'f':
case 'F':
result = false;
OK = !(Str[1] &&
(strcmp(Str+1, "alse") != 0) &&
(strcmp(Str+1, "ALSE") != 0));
break;
case '0':
{
int I;
string_traits<int>::from_string(Str, I);
result = (I != 0);
OK = ((I == 0) || (I == 1));
}
break;
case '1':
result = true;
OK = !Str[1];
break;
case 't':
case 'T':
result = true;
OK = !(Str[1] &&
(strcmp(Str+1, "rue") != 0) &&
(strcmp(Str+1, "RUE") != 0));
break;
default:
OK = false;
}
if (!OK)
throw argument_error("Failed conversion to bool: '" + string(Str) + "'");
Obj = result;
}
string string_traits<bool>::to_string(bool Obj)
{
return Obj ? "true" : "false";
}
void string_traits<short>::from_string(const char Str[], short &Obj)
{
from_string_signed(Str, Obj);
}
string string_traits<short>::to_string(short Obj)
{
return to_string_signed(Obj);
}
void string_traits<unsigned short>::from_string(
const char Str[],
unsigned short &Obj)
{
from_string_unsigned(Str, Obj);
}
string string_traits<unsigned short>::to_string(unsigned short Obj)
{
return to_string_unsigned(Obj);
}
void string_traits<int>::from_string(const char Str[], int &Obj)
{
from_string_signed(Str, Obj);
}
string string_traits<int>::to_string(int Obj)
{
return to_string_signed(Obj);
}
void string_traits<unsigned int>::from_string(
const char Str[],
unsigned int &Obj)
{
from_string_unsigned(Str, Obj);
}
string string_traits<unsigned int>::to_string(unsigned int Obj)
{
return to_string_unsigned(Obj);
}
void string_traits<long>::from_string(const char Str[], long &Obj)
{
from_string_signed(Str, Obj);
}
string string_traits<long>::to_string(long Obj)
{
return to_string_signed(Obj);
}
void string_traits<unsigned long>::from_string(
const char Str[],
unsigned long &Obj)
{
from_string_unsigned(Str, Obj);
}
string string_traits<unsigned long>::to_string(unsigned long Obj)
{
return to_string_unsigned(Obj);
}
#ifdef PQXX_HAVE_LONG_LONG
void string_traits<long long>::from_string(const char Str[], long long &Obj)
{
from_string_signed(Str, Obj);
}
string string_traits<long long>::to_string(long long Obj)
{
return to_string_signed(Obj);
}
void string_traits<unsigned long long>::from_string(
const char Str[],
unsigned long long &Obj)
{
from_string_unsigned(Str, Obj);
}
string string_traits<unsigned long long>::to_string(unsigned long long Obj)
{
return to_string_unsigned(Obj);
}
#endif
void string_traits<float>::from_string(const char Str[], float &Obj)
{
from_string_float(Str, Obj);
}
string string_traits<float>::to_string(float Obj)
{
return to_string_float(Obj);
}
void string_traits<double>::from_string(const char Str[], double &Obj)
{
from_string_float(Str, Obj);
}
string string_traits<double>::to_string(double Obj)
{
return to_string_float(Obj);
}
#ifdef PQXX_HAVE_LONG_DOUBLE
void string_traits<long double>::from_string(const char Str[], long double &Obj)
{
from_string_float(Str, Obj);
}
string string_traits<long double>::to_string(long double Obj)
{
return to_string_float(Obj);
}
#endif
} // namespace pqxx
<|endoftext|>
|
<commit_before>/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2014 Crytek
*
* 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.
******************************************************************************/
#include "driver/gl/gl_manager.h"
#include "driver/gl/gl_driver.h"
struct VertexArrayInitialData
{
VertexArrayInitialData()
{
RDCEraseEl(*this);
}
uint32_t enabled;
uint32_t vbslot;
uint32_t offset;
GLenum type;
int32_t normalized;
uint32_t integer;
uint32_t size;
};
bool GLResourceManager::SerialisableResource(ResourceId id, GLResourceRecord *record)
{
if(id == m_GL->GetContextResourceID())
return false;
return true;
}
bool GLResourceManager::Need_InitialStateChunk(GLResource res)
{
return res.Namespace != eResBuffer;
}
bool GLResourceManager::Prepare_InitialState(GLResource res)
{
ResourceId Id = GetID(res);
if(res.Namespace == eResBuffer)
{
GLResourceRecord *record = GetResourceRecord(res);
// TODO copy this to an immutable buffer elsewhere and SetInitialContents() it.
// then only do the readback in Serialise_InitialState
GLint length;
m_GL->glGetNamedBufferParameterivEXT(res.name, eGL_BUFFER_SIZE, &length);
m_GL->glGetNamedBufferSubDataEXT(res.name, 0, length, record->GetDataPtr());
}
else if(res.Namespace == eResVertexArray)
{
GLuint VAO = 0;
m_GL->glGetIntegerv(eGL_VERTEX_ARRAY_BINDING, (GLint *)&VAO);
m_GL->glBindVertexArray(res.name);
VertexArrayInitialData *data = (VertexArrayInitialData *)new byte[sizeof(VertexArrayInitialData)*16];
for(GLuint i=0; i < 16; i++)
{
m_GL->glGetVertexAttribiv(i, eGL_VERTEX_ATTRIB_ARRAY_ENABLED, (GLint *)&data[i].enabled);
m_GL->glGetVertexAttribiv(i, eGL_VERTEX_ATTRIB_BINDING, (GLint *)&data[i].vbslot);
m_GL->glGetVertexAttribiv(i, eGL_VERTEX_ATTRIB_RELATIVE_OFFSET, (GLint*)&data[i].offset);
m_GL->glGetVertexAttribiv(i, eGL_VERTEX_ATTRIB_ARRAY_TYPE, (GLint *)&data[i].type);
m_GL->glGetVertexAttribiv(i, eGL_VERTEX_ATTRIB_ARRAY_NORMALIZED, (GLint *)&data[i].normalized);
m_GL->glGetVertexAttribiv(i, eGL_VERTEX_ATTRIB_ARRAY_INTEGER, (GLint *)&data[i].integer);
m_GL->glGetVertexAttribiv(i, eGL_VERTEX_ATTRIB_ARRAY_SIZE, (GLint *)&data[i].size);
}
SetInitialContents(Id, InitialContentData(GLResource(MakeNullResource), 0, (byte *)data));
m_GL->glBindVertexArray(VAO);
}
else
{
RDCERR("Unexpected type of resource requiring initial state");
}
return true;
}
bool GLResourceManager::Force_InitialState(GLResource res)
{
// hack for now, these should be tracked through the normal dirty/ref tracking process.
if(res.Namespace == eResVertexArray) return true;
return false;
}
bool GLResourceManager::Serialise_InitialState(GLResource res)
{
ResourceId Id = ResourceId();
if(m_State >= WRITING)
{
Id = GetID(res);
if(res.Namespace != eResBuffer)
m_pSerialiser->Serialise("Id", Id);
}
else
{
m_pSerialiser->Serialise("Id", Id);
}
if(m_State < WRITING)
{
if(HasLiveResource(Id))
res = GetLiveResource(Id);
else
res = GLResource(MakeNullResource);
}
if(res.Namespace == eResBuffer)
{
// Nothing to serialize
}
else if(res.Namespace == eResVertexArray)
{
VertexArrayInitialData data[16];
if(m_State >= WRITING)
{
VertexArrayInitialData *initialdata = (VertexArrayInitialData *)GetInitialContents(Id).blob;
memcpy(data, initialdata, sizeof(data));
}
for(GLuint i=0; i < 16; i++)
{
m_pSerialiser->Serialise("data[].enabled", data[i].enabled);
m_pSerialiser->Serialise("data[].vbslot", data[i].vbslot);
m_pSerialiser->Serialise("data[].offset", data[i].offset);
m_pSerialiser->Serialise("data[].type", data[i].type);
m_pSerialiser->Serialise("data[].normalized", data[i].normalized);
m_pSerialiser->Serialise("data[].integer", data[i].integer);
m_pSerialiser->Serialise("data[].size", data[i].size);
}
if(m_State < WRITING)
{
byte *blob = new byte[sizeof(data)];
memcpy(blob, data, sizeof(data));
SetInitialContents(Id, InitialContentData(GLResource(MakeNullResource), 0, blob));
}
}
else
{
RDCERR("Unexpected type of resource requiring initial state");
}
return true;
}
void GLResourceManager::Create_InitialState(ResourceId id, GLResource live, bool hasData)
{
if(live.Namespace != eResBuffer)
{
RDCUNIMPLEMENTED("Expect all initial states to be created & not skipped, presently");
}
}
void GLResourceManager::Apply_InitialState(GLResource live, InitialContentData initial)
{
if(live.Namespace == eResVertexArray)
{
GLuint VAO = 0;
m_GL->glGetIntegerv(eGL_VERTEX_ARRAY_BINDING, (GLint *)&VAO);
m_GL->glBindVertexArray(live.name);
VertexArrayInitialData *initialdata = (VertexArrayInitialData *)initial.blob;
for(GLuint i=0; i < 16; i++)
{
if(initialdata[i].enabled)
m_GL->glEnableVertexAttribArray(i);
else
m_GL->glDisableVertexAttribArray(i);
m_GL->glVertexAttribBinding(i, initialdata[i].vbslot);
if(initialdata[i].integer == 0)
m_GL->glVertexAttribFormat(i, initialdata[i].size, initialdata[i].type, (GLboolean)initialdata[i].normalized, initialdata[i].offset);
else
m_GL->glVertexAttribIFormat(i, initialdata[i].size, initialdata[i].type, initialdata[i].offset);
}
m_GL->glBindVertexArray(VAO);
}
else
{
RDCERR("Unexpected type of resource requiring initial state");
}
}
<commit_msg>VAOs get marked as dirty via VertexArrayUpdateCheck()<commit_after>/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2014 Crytek
*
* 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.
******************************************************************************/
#include "driver/gl/gl_manager.h"
#include "driver/gl/gl_driver.h"
struct VertexArrayInitialData
{
VertexArrayInitialData()
{
RDCEraseEl(*this);
}
uint32_t enabled;
uint32_t vbslot;
uint32_t offset;
GLenum type;
int32_t normalized;
uint32_t integer;
uint32_t size;
};
bool GLResourceManager::SerialisableResource(ResourceId id, GLResourceRecord *record)
{
if(id == m_GL->GetContextResourceID())
return false;
return true;
}
bool GLResourceManager::Need_InitialStateChunk(GLResource res)
{
return res.Namespace != eResBuffer;
}
bool GLResourceManager::Prepare_InitialState(GLResource res)
{
ResourceId Id = GetID(res);
if(res.Namespace == eResBuffer)
{
GLResourceRecord *record = GetResourceRecord(res);
// TODO copy this to an immutable buffer elsewhere and SetInitialContents() it.
// then only do the readback in Serialise_InitialState
GLint length;
m_GL->glGetNamedBufferParameterivEXT(res.name, eGL_BUFFER_SIZE, &length);
m_GL->glGetNamedBufferSubDataEXT(res.name, 0, length, record->GetDataPtr());
}
else if(res.Namespace == eResVertexArray)
{
GLuint VAO = 0;
m_GL->glGetIntegerv(eGL_VERTEX_ARRAY_BINDING, (GLint *)&VAO);
m_GL->glBindVertexArray(res.name);
VertexArrayInitialData *data = (VertexArrayInitialData *)new byte[sizeof(VertexArrayInitialData)*16];
for(GLuint i=0; i < 16; i++)
{
m_GL->glGetVertexAttribiv(i, eGL_VERTEX_ATTRIB_ARRAY_ENABLED, (GLint *)&data[i].enabled);
m_GL->glGetVertexAttribiv(i, eGL_VERTEX_ATTRIB_BINDING, (GLint *)&data[i].vbslot);
m_GL->glGetVertexAttribiv(i, eGL_VERTEX_ATTRIB_RELATIVE_OFFSET, (GLint*)&data[i].offset);
m_GL->glGetVertexAttribiv(i, eGL_VERTEX_ATTRIB_ARRAY_TYPE, (GLint *)&data[i].type);
m_GL->glGetVertexAttribiv(i, eGL_VERTEX_ATTRIB_ARRAY_NORMALIZED, (GLint *)&data[i].normalized);
m_GL->glGetVertexAttribiv(i, eGL_VERTEX_ATTRIB_ARRAY_INTEGER, (GLint *)&data[i].integer);
m_GL->glGetVertexAttribiv(i, eGL_VERTEX_ATTRIB_ARRAY_SIZE, (GLint *)&data[i].size);
}
SetInitialContents(Id, InitialContentData(GLResource(MakeNullResource), 0, (byte *)data));
m_GL->glBindVertexArray(VAO);
}
else
{
RDCERR("Unexpected type of resource requiring initial state");
}
return true;
}
bool GLResourceManager::Force_InitialState(GLResource res)
{
return false;
}
bool GLResourceManager::Serialise_InitialState(GLResource res)
{
ResourceId Id = ResourceId();
if(m_State >= WRITING)
{
Id = GetID(res);
if(res.Namespace != eResBuffer)
m_pSerialiser->Serialise("Id", Id);
}
else
{
m_pSerialiser->Serialise("Id", Id);
}
if(m_State < WRITING)
{
if(HasLiveResource(Id))
res = GetLiveResource(Id);
else
res = GLResource(MakeNullResource);
}
if(res.Namespace == eResBuffer)
{
// Nothing to serialize
}
else if(res.Namespace == eResVertexArray)
{
VertexArrayInitialData data[16];
if(m_State >= WRITING)
{
VertexArrayInitialData *initialdata = (VertexArrayInitialData *)GetInitialContents(Id).blob;
memcpy(data, initialdata, sizeof(data));
}
for(GLuint i=0; i < 16; i++)
{
m_pSerialiser->Serialise("data[].enabled", data[i].enabled);
m_pSerialiser->Serialise("data[].vbslot", data[i].vbslot);
m_pSerialiser->Serialise("data[].offset", data[i].offset);
m_pSerialiser->Serialise("data[].type", data[i].type);
m_pSerialiser->Serialise("data[].normalized", data[i].normalized);
m_pSerialiser->Serialise("data[].integer", data[i].integer);
m_pSerialiser->Serialise("data[].size", data[i].size);
}
if(m_State < WRITING)
{
byte *blob = new byte[sizeof(data)];
memcpy(blob, data, sizeof(data));
SetInitialContents(Id, InitialContentData(GLResource(MakeNullResource), 0, blob));
}
}
else
{
RDCERR("Unexpected type of resource requiring initial state");
}
return true;
}
void GLResourceManager::Create_InitialState(ResourceId id, GLResource live, bool hasData)
{
if(live.Namespace != eResBuffer)
{
RDCUNIMPLEMENTED("Expect all initial states to be created & not skipped, presently");
}
}
void GLResourceManager::Apply_InitialState(GLResource live, InitialContentData initial)
{
if(live.Namespace == eResVertexArray)
{
GLuint VAO = 0;
m_GL->glGetIntegerv(eGL_VERTEX_ARRAY_BINDING, (GLint *)&VAO);
m_GL->glBindVertexArray(live.name);
VertexArrayInitialData *initialdata = (VertexArrayInitialData *)initial.blob;
for(GLuint i=0; i < 16; i++)
{
if(initialdata[i].enabled)
m_GL->glEnableVertexAttribArray(i);
else
m_GL->glDisableVertexAttribArray(i);
m_GL->glVertexAttribBinding(i, initialdata[i].vbslot);
if(initialdata[i].integer == 0)
m_GL->glVertexAttribFormat(i, initialdata[i].size, initialdata[i].type, (GLboolean)initialdata[i].normalized, initialdata[i].offset);
else
m_GL->glVertexAttribIFormat(i, initialdata[i].size, initialdata[i].type, initialdata[i].offset);
}
m_GL->glBindVertexArray(VAO);
}
else
{
RDCERR("Unexpected type of resource requiring initial state");
}
}
<|endoftext|>
|
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, 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 */
#include <moveit/warehouse/planning_scene_storage.h>
#include <moveit/warehouse/state_storage.h>
#include <moveit/warehouse/constraints_storage.h>
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/variables_map.hpp>
#include <moveit/planning_scene_monitor/planning_scene_monitor.h>
#include <moveit/kinematic_state/conversions.h>
#include <ros/ros.h>
static const std::string ROBOT_DESCRIPTION="robot_description";
typedef std::pair<geometry_msgs::Point, geometry_msgs::Quaternion> LinkConstraintPair;
typedef std::map<std::string, LinkConstraintPair > LinkConstraintMap;
void collectLinkConstraints(const moveit_msgs::Constraints& constraints, LinkConstraintMap& lcmap )
{
for(std::size_t i = 0; i < constraints.position_constraints.size(); ++i)
{
LinkConstraintPair lcp;
const moveit_msgs::PositionConstraint &pc = constraints.position_constraints[i];
lcp.first = pc.constraint_region.primitive_poses[0].position;
lcmap[constraints.position_constraints[i].link_name] = lcp;
}
for(std::size_t i = 0; i < constraints.orientation_constraints.size(); ++i)
{
if(lcmap.count(constraints.orientation_constraints[i].link_name))
{
lcmap[constraints.orientation_constraints[i].link_name].second = constraints.orientation_constraints[i].orientation;
} else{
ROS_WARN("Orientation constraint for %s has no matching position constraint", constraints.orientation_constraints[i].link_name.c_str());
}
}
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "save_warehouse_as_text", ros::init_options::AnonymousName);
boost::program_options::options_description desc;
desc.add_options()
("help", "Show help message")
("host", boost::program_options::value<std::string>(), "Host for the MongoDB.")
("port", boost::program_options::value<std::size_t>(), "Port for the MongoDB.");
boost::program_options::variables_map vm;
boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
boost::program_options::notify(vm);
if (vm.count("help"))
{
std::cout << desc << std::endl;
return 1;
}
ros::AsyncSpinner spinner(1);
spinner.start();
planning_scene_monitor::PlanningSceneMonitor psm(ROBOT_DESCRIPTION);
moveit_warehouse::PlanningSceneStorage pss(vm.count("host") ? vm["host"].as<std::string>() : "",
vm.count("port") ? vm["port"].as<std::size_t>() : 0);
moveit_warehouse::RobotStateStorage rss(vm.count("host") ? vm["host"].as<std::string>() : "",
vm.count("port") ? vm["port"].as<std::size_t>() : 0);
moveit_warehouse::ConstraintsStorage cs(vm.count("host") ? vm["host"].as<std::string>() : "",
vm.count("port") ? vm["port"].as<std::size_t>() : 0);
std::vector<std::string> scene_names;
pss.getPlanningSceneNames(scene_names);
for (std::size_t i = 0 ; i < scene_names.size() ; ++i)
{
moveit_warehouse::PlanningSceneWithMetadata pswm;
if (pss.getPlanningScene(pswm, scene_names[i]))
{
ROS_INFO("Saving scene '%s'", scene_names[i].c_str());
psm.getPlanningScene()->setPlanningSceneMsg(static_cast<const moveit_msgs::PlanningScene&>(*pswm));
std::ofstream fout((scene_names[i] + ".scene").c_str());
psm.getPlanningScene()->saveGeometryToStream(fout);
fout.close();
std::ofstream qfout((scene_names[i] + ".queries").c_str());
qfout << scene_names[i] << std::endl;
std::vector<std::string> robotStateNames;
kinematic_model::KinematicModelConstPtr km = psm.getKinematicModel();
// Get start states for scene
std::stringstream rsregex;
rsregex << ".*" << scene_names[i] << ".*";
rss.getKnownRobotStates(rsregex.str(), robotStateNames);
if(robotStateNames.size())
{
qfout << "start" << std::endl;
qfout << robotStateNames.size() << std::endl;
for(int k = 0; k < robotStateNames.size(); ++k)
{
ROS_INFO("Saving start state %s for scene %s", robotStateNames[k].c_str(), scene_names[i].c_str());
qfout << robotStateNames[k] << std::endl;
moveit_warehouse::RobotStateWithMetadata robotState;
rss.getRobotState(robotState, robotStateNames[k]);
kinematic_state::KinematicState ks(km);
kinematic_state::robotStateToKinematicState(*robotState, ks, false);
ks.printStateInfo(qfout);
qfout << "." << std::endl;
}
}
// Get goal constraints for scene
std::vector<std::string> constraintNames;
std::stringstream csregex;
csregex << ".*" << scene_names[i] << ".*";
cs.getKnownConstraints(csregex.str(), constraintNames);
if(constraintNames.size())
{
qfout << "goal" << std::endl;
qfout << constraintNames.size() << std::endl;
for(int k = 0; k < constraintNames.size(); ++k)
{
ROS_INFO("Saving goal %s for scene %s", constraintNames[k].c_str(), scene_names[i].c_str());
qfout << "link_constraint" << std::endl;
qfout << constraintNames[k] << std::endl;
moveit_warehouse::ConstraintsWithMetadata constraints;
cs.getConstraints(constraints, constraintNames[k]);
LinkConstraintMap lcmap;
collectLinkConstraints(*constraints, lcmap);
for(LinkConstraintMap::iterator iter = lcmap.begin(); iter != lcmap.end(); iter++)
{
std::string link_name = iter->first;
LinkConstraintPair lcp = iter->second;
qfout << link_name << std::endl;
qfout << "xyz " << lcp.first.x << " " << lcp.first.y << " " << lcp.first.z << std::endl;
Eigen::Quaterniond orientation(lcp.second.w, lcp.second.x, lcp.second.y, lcp.second.z);
Eigen::Vector3d rpy = orientation.matrix().eulerAngles(0, 1, 2);
qfout << "rpy " << rpy[0] << " " << rpy[1] << " " << rpy[2] << std::endl;
}
qfout << "." << std::endl;
}
}
qfout.close();
}
}
ROS_INFO("Done.");
return 0;
}
<commit_msg>Prevent creating queries files for scenes that have no queries.<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, 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 */
#include <moveit/warehouse/planning_scene_storage.h>
#include <moveit/warehouse/state_storage.h>
#include <moveit/warehouse/constraints_storage.h>
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/variables_map.hpp>
#include <moveit/planning_scene_monitor/planning_scene_monitor.h>
#include <moveit/kinematic_state/conversions.h>
#include <ros/ros.h>
static const std::string ROBOT_DESCRIPTION="robot_description";
typedef std::pair<geometry_msgs::Point, geometry_msgs::Quaternion> LinkConstraintPair;
typedef std::map<std::string, LinkConstraintPair > LinkConstraintMap;
void collectLinkConstraints(const moveit_msgs::Constraints& constraints, LinkConstraintMap& lcmap )
{
for(std::size_t i = 0; i < constraints.position_constraints.size(); ++i)
{
LinkConstraintPair lcp;
const moveit_msgs::PositionConstraint &pc = constraints.position_constraints[i];
lcp.first = pc.constraint_region.primitive_poses[0].position;
lcmap[constraints.position_constraints[i].link_name] = lcp;
}
for(std::size_t i = 0; i < constraints.orientation_constraints.size(); ++i)
{
if(lcmap.count(constraints.orientation_constraints[i].link_name))
{
lcmap[constraints.orientation_constraints[i].link_name].second = constraints.orientation_constraints[i].orientation;
} else{
ROS_WARN("Orientation constraint for %s has no matching position constraint", constraints.orientation_constraints[i].link_name.c_str());
}
}
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "save_warehouse_as_text", ros::init_options::AnonymousName);
boost::program_options::options_description desc;
desc.add_options()
("help", "Show help message")
("host", boost::program_options::value<std::string>(), "Host for the MongoDB.")
("port", boost::program_options::value<std::size_t>(), "Port for the MongoDB.");
boost::program_options::variables_map vm;
boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
boost::program_options::notify(vm);
if (vm.count("help"))
{
std::cout << desc << std::endl;
return 1;
}
ros::AsyncSpinner spinner(1);
spinner.start();
planning_scene_monitor::PlanningSceneMonitor psm(ROBOT_DESCRIPTION);
moveit_warehouse::PlanningSceneStorage pss(vm.count("host") ? vm["host"].as<std::string>() : "",
vm.count("port") ? vm["port"].as<std::size_t>() : 0);
moveit_warehouse::RobotStateStorage rss(vm.count("host") ? vm["host"].as<std::string>() : "",
vm.count("port") ? vm["port"].as<std::size_t>() : 0);
moveit_warehouse::ConstraintsStorage cs(vm.count("host") ? vm["host"].as<std::string>() : "",
vm.count("port") ? vm["port"].as<std::size_t>() : 0);
std::vector<std::string> scene_names;
pss.getPlanningSceneNames(scene_names);
for (std::size_t i = 0 ; i < scene_names.size() ; ++i)
{
moveit_warehouse::PlanningSceneWithMetadata pswm;
if (pss.getPlanningScene(pswm, scene_names[i]))
{
ROS_INFO("Saving scene '%s'", scene_names[i].c_str());
psm.getPlanningScene()->setPlanningSceneMsg(static_cast<const moveit_msgs::PlanningScene&>(*pswm));
std::ofstream fout((scene_names[i] + ".scene").c_str());
psm.getPlanningScene()->saveGeometryToStream(fout);
fout.close();
std::vector<std::string> robotStateNames;
kinematic_model::KinematicModelConstPtr km = psm.getKinematicModel();
// Get start states for scene
std::stringstream rsregex;
rsregex << ".*" << scene_names[i] << ".*";
rss.getKnownRobotStates(rsregex.str(), robotStateNames);
// Get goal constraints for scene
std::vector<std::string> constraintNames;
std::stringstream csregex;
csregex << ".*" << scene_names[i] << ".*";
cs.getKnownConstraints(csregex.str(), constraintNames);
if( !(robotStateNames.empty() && constraintNames.empty()) )
{
std::ofstream qfout((scene_names[i] + ".queries").c_str());
qfout << scene_names[i] << std::endl;
if(robotStateNames.size())
{
qfout << "start" << std::endl;
qfout << robotStateNames.size() << std::endl;
for(int k = 0; k < robotStateNames.size(); ++k)
{
ROS_INFO("Saving start state %s for scene %s", robotStateNames[k].c_str(), scene_names[i].c_str());
qfout << robotStateNames[k] << std::endl;
moveit_warehouse::RobotStateWithMetadata robotState;
rss.getRobotState(robotState, robotStateNames[k]);
kinematic_state::KinematicState ks(km);
kinematic_state::robotStateToKinematicState(*robotState, ks, false);
ks.printStateInfo(qfout);
qfout << "." << std::endl;
}
}
if(constraintNames.size())
{
qfout << "goal" << std::endl;
qfout << constraintNames.size() << std::endl;
for(int k = 0; k < constraintNames.size(); ++k)
{
ROS_INFO("Saving goal %s for scene %s", constraintNames[k].c_str(), scene_names[i].c_str());
qfout << "link_constraint" << std::endl;
qfout << constraintNames[k] << std::endl;
moveit_warehouse::ConstraintsWithMetadata constraints;
cs.getConstraints(constraints, constraintNames[k]);
LinkConstraintMap lcmap;
collectLinkConstraints(*constraints, lcmap);
for(LinkConstraintMap::iterator iter = lcmap.begin(); iter != lcmap.end(); iter++)
{
std::string link_name = iter->first;
LinkConstraintPair lcp = iter->second;
qfout << link_name << std::endl;
qfout << "xyz " << lcp.first.x << " " << lcp.first.y << " " << lcp.first.z << std::endl;
Eigen::Quaterniond orientation(lcp.second.w, lcp.second.x, lcp.second.y, lcp.second.z);
Eigen::Vector3d rpy = orientation.matrix().eulerAngles(0, 1, 2);
qfout << "rpy " << rpy[0] << " " << rpy[1] << " " << rpy[2] << std::endl;
}
qfout << "." << std::endl;
}
}
qfout.close();
}
}
}
ROS_INFO("Done.");
return 0;
}
<|endoftext|>
|
<commit_before>/*
*******************************************************************************
*
* Purpose: Low Power Mode implementation for ESP.
*
*******************************************************************************
* Copyright Oleg Kovalenko 2017.
*
* Distributed under the MIT License.
* (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
*******************************************************************************
*/
#ifndef BUTLER_ARDUINO_ESP_LPM_H_
#define BUTLER_ARDUINO_ESP_LPM_H_
/* System Includes */
#include <Arduino.h>
#include <stdint.h>
/* Internal Includes */
#include "ButlerArduinoLpm.hpp"
#include "ButlerArduinoCrc.h"
namespace Butler {
namespace Arduino {
class EspLpm: public Lpm {
public:
void idle(unsigned long ms) {
idle(ms, nullptr, 0);
}
void idle(uint32_t ms, uint32_t* data, uint32_t dataSize) {
// Initialize
LpmControl header;
header.ctx.msCounter = ms;
header.ctx.state = COUNT;
if (data) {
writeData(data, dataSize);
}
// Begin
update(header, data, dataSize);
}
bool check(uint8_t resetPin, uint32_t* data = nullptr, uint32_t dataSize = 0) {
if (LOW == digitalRead(resetPin)) {
resetHeader();
return false;
}
// Recover header and data
LpmControl header;
readHeader(header);
if (data) {
readData(data, dataSize);
}
// Check CRC
{
uint32_t crc = Crc::crc32Begin();
crc = Crc::crc32Continue(crc, reinterpret_cast<uint8_t*>(&(header.ctx)), sizeof(header.ctx));
if (data) {
crc = Crc::crc32Continue(crc, reinterpret_cast<uint8_t*>(data), dataSize);
}
crc = Crc::crc32End(crc);
if (header.crc != crc) {
return false;
}
}
// Continue
update(header, data, dataSize);
return true;
}
uint32_t getMaxDataSize() const {
return 512 - sizeof(LpmControl);
}
private:
enum LpmState {
COUNT,
DONE
};
struct LpmControlCtx {
LpmState state = DONE;
uint32_t msCounter;
} __attribute__((aligned(4)));
struct LpmControl {
uint32_t crc;
LpmControlCtx ctx;
} __attribute__((aligned(4)));
const uint32_t ONE_HOUR_MS = 1*60*60*1000;
void update(LpmControl& header, uint32_t* data = nullptr, uint32_t dataSize = 0) {
switch(header.ctx.state) {
case COUNT:
{
// Update state
RFMode rfMode = RF_DEFAULT;
// Subtract current BOOT-time
uint32_t bootTime = millis();
header.ctx.msCounter -= (header.ctx.msCounter > bootTime) ? bootTime : header.ctx.msCounter;
// Calculate next sleep time
uint32_t sleepTimeMs = header.ctx.msCounter;
if (sleepTimeMs > ONE_HOUR_MS) {
sleepTimeMs = ONE_HOUR_MS;
rfMode = RF_DISABLED;
} else {
header.ctx.state = DONE;
}
// Update sleep time counter
header.ctx.msCounter -= sleepTimeMs;
// Update CRC
{
uint32_t crc = Crc::crc32Begin();
crc = Crc::crc32Continue(crc, reinterpret_cast<uint8_t*>(&(header.ctx)), sizeof(header.ctx));
if (data) {
crc = Crc::crc32Continue(crc, reinterpret_cast<uint8_t*>(data), dataSize);
}
crc = Crc::crc32End(crc);
header.crc = crc;
}
// Store state
writeHeader(header);
// Sleep
ESP.deepSleep(sleepTimeMs * 1000L, rfMode);
}
break;
case DONE:
break;
default:
// Something wrong => wake-up
resetHeader();
break;
}
}
void resetHeader() {
LpmControl header;
writeHeader(header);
}
void readHeader(LpmControl& header) {
ESP.rtcUserMemoryRead(0, reinterpret_cast<uint32_t*>(&header), sizeof(LpmControl));
}
void writeHeader(const LpmControl& header) {
ESP.rtcUserMemoryWrite(0, const_cast<uint32_t*>(reinterpret_cast<const uint32_t*>(&header)), sizeof(LpmControl));
}
void readData(uint32_t* data, uint32_t dataSize) {
ESP.rtcUserMemoryWrite(sizeof(LpmControl), data, dataSize);
}
void writeData(const uint32_t* data, uint32_t dataSize) {
ESP.rtcUserMemoryWrite(sizeof(LpmControl), const_cast<uint32_t*>(data), dataSize);
}
};
}}
#endif // BUTLER_ARDUINO_ESP_LPM_H_
<commit_msg>Fix `EspLpm` data storage.<commit_after>/*
*******************************************************************************
*
* Purpose: Low Power Mode implementation for ESP.
*
*******************************************************************************
* Copyright Oleg Kovalenko 2017.
*
* Distributed under the MIT License.
* (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
*******************************************************************************
*/
#ifndef BUTLER_ARDUINO_ESP_LPM_H_
#define BUTLER_ARDUINO_ESP_LPM_H_
/* System Includes */
#include <Arduino.h>
#include <stdint.h>
/* Internal Includes */
#include "ButlerArduinoLpm.hpp"
#include "ButlerArduinoCrc.h"
namespace Butler {
namespace Arduino {
class EspLpm: public Lpm {
public:
void idle(unsigned long ms) {
idle(ms, nullptr, 0);
}
void idle(uint32_t ms, uint32_t* data, uint32_t dataSize, uint32_t* data2 = nullptr, uint32_t data2Size = 0) {
// Initialize
LpmControl header;
header.ctx.msCounter = ms;
header.ctx.state = COUNT;
if (data) {
writeData(data, dataSize);
if (data2) {
writeData(data2, data2Size, dataSize);
}
}
// Begin
update(header, data, dataSize, data2, data2Size);
}
bool check(uint8_t resetPin, uint32_t* data = nullptr, uint32_t dataSize = 0,
uint32_t* data2 = nullptr, uint32_t data2Size = 0)
{
if (LOW == digitalRead(resetPin)) {
resetHeader();
return false;
}
// Recover header and data
LpmControl header;
readHeader(header);
if (data) {
readData(data, dataSize);
if (data2) {
readData(data2, data2Size, dataSize);
}
}
// Check CRC
{
uint32_t crc = Crc::crc32Begin();
crc = Crc::crc32Continue(crc, reinterpret_cast<uint8_t*>(&(header.ctx)), sizeof(header.ctx));
if (data) {
crc = Crc::crc32Continue(crc, reinterpret_cast<uint8_t*>(data), dataSize);
if (data2) {
crc = Crc::crc32Continue(crc, reinterpret_cast<uint8_t*>(data2), data2Size);
}
}
crc = Crc::crc32End(crc);
if (header.crc != crc) {
if (data) {
memset(data, 0, dataSize);
if (data2) {
memset(data2, 0, data2Size);
}
}
return false;
}
}
// Continue
update(header, data, dataSize, data2, data2Size);
return true;
}
uint32_t getMaxDataSize() const {
return 512 - sizeof(LpmControl);
}
private:
enum LpmState {
COUNT,
DONE
};
struct LpmControlCtx {
LpmState state = DONE;
uint32_t msCounter;
} __attribute__((aligned(4)));
struct LpmControl {
uint32_t crc;
LpmControlCtx ctx;
} __attribute__((aligned(4)));
const uint32_t ONE_HOUR_MS = 1*60*60*1000;
void update(LpmControl& header, uint32_t* data = nullptr, uint32_t dataSize = 0,
uint32_t* data2 = nullptr, uint32_t data2Size = 0)
{
switch(header.ctx.state) {
case COUNT:
{
// Update state
RFMode rfMode = RF_DEFAULT;
// Subtract current BOOT-time
uint32_t bootTime = millis();
header.ctx.msCounter -= (header.ctx.msCounter > bootTime) ? bootTime : header.ctx.msCounter;
// Calculate next sleep time
uint32_t sleepTimeMs = header.ctx.msCounter;
if (sleepTimeMs > ONE_HOUR_MS) {
sleepTimeMs = ONE_HOUR_MS;
rfMode = RF_DISABLED;
} else {
header.ctx.state = DONE;
}
// Update sleep time counter
header.ctx.msCounter -= sleepTimeMs;
// Update CRC
{
uint32_t crc = Crc::crc32Begin();
crc = Crc::crc32Continue(crc, reinterpret_cast<uint8_t*>(&(header.ctx)), sizeof(header.ctx));
if (data) {
crc = Crc::crc32Continue(crc, reinterpret_cast<uint8_t*>(data), dataSize);
if (data2) {
crc = Crc::crc32Continue(crc, reinterpret_cast<uint8_t*>(data2), data2Size);
}
}
crc = Crc::crc32End(crc);
header.crc = crc;
}
// Store state
writeHeader(header);
// Sleep
ESP.deepSleep(sleepTimeMs * 1000L, rfMode);
}
break;
case DONE:
break;
default:
// Something wrong => wake-up
resetHeader();
break;
}
}
void resetHeader() {
LpmControl header;
writeHeader(header);
}
void readHeader(LpmControl& header) {
ESP.rtcUserMemoryRead(0, reinterpret_cast<uint32_t*>(&header), sizeof(LpmControl));
}
void writeHeader(const LpmControl& header) {
ESP.rtcUserMemoryWrite(0, const_cast<uint32_t*>(reinterpret_cast<const uint32_t*>(&header)), sizeof(LpmControl));
}
void readData(uint32_t* data, uint32_t dataSize, uint32_t offset = 0) {
ESP.rtcUserMemoryRead(sizeof(LpmControl) + offset, data, dataSize);
}
void writeData(const uint32_t* data, uint32_t dataSize, uint32_t offset = 0) {
ESP.rtcUserMemoryWrite(sizeof(LpmControl) + offset, const_cast<uint32_t*>(data), dataSize);
}
};
}}
#endif // BUTLER_ARDUINO_ESP_LPM_H_
<|endoftext|>
|
<commit_before>namespace factor
{
#define FACTOR_CPU_STRING "ppc"
#define VM_ASM_API VM_C_API
register cell ds asm("r13");
register cell rs asm("r14");
/* In the instruction sequence:
LOAD32 r3,...
B blah
the offset from the immediate operand to LOAD32 to the instruction after
the branch is two instructions. */
static const fixnum xt_tail_pic_offset = 4 * 2;
inline static void check_call_site(cell return_address)
{
#ifdef FACTOR_DEBUG
cell insn = *(cell *)return_address;
/* Check that absolute bit is 0 */
assert((insn & 0x2) == 0x0);
/* Check that instruction is branch */
assert((insn >> 26) == 0x12);
#endif
}
static const cell b_mask = 0x3fffffc;
inline static void *get_call_target(cell return_address)
{
return_address -= sizeof(cell);
check_call_site(return_address);
cell insn = *(cell *)return_address;
cell unsigned_addr = (insn & B_MASK);
fixnum signed_addr = (fixnum)(unsigned_addr << 6) >> 6;
return (void *)(signed_addr + return_address);
}
inline static void set_call_target(cell return_address, void *target)
{
return_address -= sizeof(cell);
check_call_site(return_address);
cell insn = *(cell *)return_address;
fixnum relative_address = ((cell)target - return_address);
insn = ((insn & ~B_MASK) | (relative_address & B_MASK));
*(cell *)return_address = insn;
/* Flush the cache line containing the call we just patched */
__asm__ __volatile__ ("icbi 0, %0\n" "sync\n"::"r" (return_address):);
}
inline static bool tail_call_site_p(cell return_address)
{
return_address -= sizeof(cell);
cell insn = *(cell *)return_address;
return (insn & 0x1) == 0;
}
/* Defined in assembly */
VM_ASM_API void c_to_factor(cell quot);
VM_ASM_API void throw_impl(cell quot, stack_frame *rewind);
VM_ASM_API void lazy_jit_compile(cell quot);
VM_ASM_API void flush_icache(cell start, cell len);
VM_ASM_API void set_callstack(stack_frame *to,
stack_frame *from,
cell length,
void *(*memcpy)(void*,const void*, size_t));
}
<commit_msg>Fix compile error in cpu-ppc.hpp<commit_after>namespace factor
{
#define FACTOR_CPU_STRING "ppc"
#define VM_ASM_API VM_C_API
register cell ds asm("r13");
register cell rs asm("r14");
/* In the instruction sequence:
LOAD32 r3,...
B blah
the offset from the immediate operand to LOAD32 to the instruction after
the branch is two instructions. */
static const fixnum xt_tail_pic_offset = 4 * 2;
inline static void check_call_site(cell return_address)
{
#ifdef FACTOR_DEBUG
cell insn = *(cell *)return_address;
/* Check that absolute bit is 0 */
assert((insn & 0x2) == 0x0);
/* Check that instruction is branch */
assert((insn >> 26) == 0x12);
#endif
}
static const cell b_mask = 0x3fffffc;
inline static void *get_call_target(cell return_address)
{
return_address -= sizeof(cell);
check_call_site(return_address);
cell insn = *(cell *)return_address;
cell unsigned_addr = (insn & b_mask);
fixnum signed_addr = (fixnum)(unsigned_addr << 6) >> 6;
return (void *)(signed_addr + return_address);
}
inline static void set_call_target(cell return_address, void *target)
{
return_address -= sizeof(cell);
check_call_site(return_address);
cell insn = *(cell *)return_address;
fixnum relative_address = ((cell)target - return_address);
insn = ((insn & ~b_mask) | (relative_address & b_mask));
*(cell *)return_address = insn;
/* Flush the cache line containing the call we just patched */
__asm__ __volatile__ ("icbi 0, %0\n" "sync\n"::"r" (return_address):);
}
inline static bool tail_call_site_p(cell return_address)
{
return_address -= sizeof(cell);
cell insn = *(cell *)return_address;
return (insn & 0x1) == 0;
}
/* Defined in assembly */
VM_ASM_API void c_to_factor(cell quot);
VM_ASM_API void throw_impl(cell quot, stack_frame *rewind);
VM_ASM_API void lazy_jit_compile(cell quot);
VM_ASM_API void flush_icache(cell start, cell len);
VM_ASM_API void set_callstack(stack_frame *to,
stack_frame *from,
cell length,
void *(*memcpy)(void*,const void*, size_t));
}
<|endoftext|>
|
<commit_before>#include "testing/testing.hpp"
#include "routing/turns_sound_settings.hpp"
#include "routing/turns_tts_text.hpp"
#include "std/cstring.hpp"
#include "std/string.hpp"
namespace
{
using namespace routing::turns;
using namespace routing::turns::sound;
bool pairDistEquals(PairDist const & lhs, PairDist const & rhs)
{
return lhs.first == rhs.first && strcmp(lhs.second, rhs.second) == 0;
}
UNIT_TEST(GetDistanceTextIdMetersTest)
{
// Notification(uint32_t distanceUnits, uint8_t exitNum, bool useThenInsteadOfDistance,
// TurnDirection turnDir, LengthUnits lengthUnits)
Notification const notifiation1(500, 0, false, TurnDirection::TurnRight, LengthUnits::Meters);
TEST_EQUAL(GetDistanceTextId(notifiation1), "in_500_meters", ());
Notification const notifiation2(500, 0, true, TurnDirection::TurnRight, LengthUnits::Meters);
TEST_EQUAL(GetDistanceTextId(notifiation2), "then", ());
Notification const notifiation3(200, 0, false, TurnDirection::TurnRight, LengthUnits::Meters);
TEST_EQUAL(GetDistanceTextId(notifiation3), "in_200_meters", ());
Notification const notifiation4(2000, 0, false, TurnDirection::TurnRight, LengthUnits::Meters);
TEST_EQUAL(GetDistanceTextId(notifiation4), "in_2_kilometers", ());
}
UNIT_TEST(GetDistanceTextIdFeetTest)
{
Notification const notifiation1(500, 0, false, TurnDirection::TurnRight, LengthUnits::Feet);
TEST_EQUAL(GetDistanceTextId(notifiation1), "in_500_feet", ());
Notification const notifiation2(500, 0, true, TurnDirection::TurnRight, LengthUnits::Feet);
TEST_EQUAL(GetDistanceTextId(notifiation2), "then", ());
Notification const notifiation3(800, 0, false, TurnDirection::TurnRight, LengthUnits::Feet);
TEST_EQUAL(GetDistanceTextId(notifiation3), "in_800_feet", ());
Notification const notifiation4(5000, 0, false, TurnDirection::TurnRight, LengthUnits::Feet);
TEST_EQUAL(GetDistanceTextId(notifiation4), "in_5000_feet", ());
}
UNIT_TEST(GetDirectionTextIdTest)
{
Notification const notifiation1(500, 0, false, TurnDirection::TurnRight, LengthUnits::Feet);
TEST_EQUAL(GetDirectionTextId(notifiation1), "make_a_right_turn", ());
Notification const notifiation2(1000, 0, false, TurnDirection::GoStraight, LengthUnits::Meters);
TEST_EQUAL(GetDirectionTextId(notifiation2), "go_straight", ());
Notification const notifiation3(700, 0, false, TurnDirection::UTurn, LengthUnits::Meters);
TEST_EQUAL(GetDirectionTextId(notifiation3), "make_a_u_turn", ());
}
UNIT_TEST(GetTtsTextTest)
{
string const engShortJson =
"\
{\
\"in_300_meters\":\"In 300 meters.\",\
\"in_500_meters\":\"In 500 meters.\",\
\"then\":\"Then.\",\
\"make_a_right_turn\":\"Make a right turn.\",\
\"make_a_left_turn\":\"Make a left turn.\",\
\"you_have_reached_the_destination\":\"You have reached the destination.\"\
}";
string const rusShortJson =
"\
{\
\"in_300_meters\":\"Через 300 метров.\",\
\"in_500_meters\":\"Через 500 метров.\",\
\"then\":\"Затем.\",\
\"make_a_right_turn\":\"Поворот направо.\",\
\"make_a_left_turn\":\"Поворот налево.\",\
\"you_have_reached_the_destination\":\"Вы достигли конца маршрута.\"\
}";
GetTtsText getTtsText;
// Notification(uint32_t distanceUnits, uint8_t exitNum, bool useThenInsteadOfDistance,
// TurnDirection turnDir, LengthUnits lengthUnits)
Notification const notifiation1(500, 0, false, TurnDirection::TurnRight, LengthUnits::Meters);
Notification const notifiation2(300, 0, false, TurnDirection::TurnLeft, LengthUnits::Meters);
Notification const notifiation3(0, 0, false, TurnDirection::ReachedYourDestination,
LengthUnits::Meters);
Notification const notifiation4(0, 0, true, TurnDirection::TurnLeft, LengthUnits::Meters);
getTtsText.SetLocaleWithJson(engShortJson);
TEST_EQUAL(getTtsText(notifiation1), "In 500 meters. Make a right turn.", ());
TEST_EQUAL(getTtsText(notifiation2), "In 300 meters. Make a left turn.", ());
TEST_EQUAL(getTtsText(notifiation3), "You have reached the destination.", ());
TEST_EQUAL(getTtsText(notifiation4), "Then. Make a left turn.", ());
getTtsText.SetLocaleWithJson(rusShortJson);
TEST_EQUAL(getTtsText(notifiation1), "Через 500 метров. Поворот направо.", ());
TEST_EQUAL(getTtsText(notifiation2), "Через 300 метров. Поворот налево.", ());
TEST_EQUAL(getTtsText(notifiation3), "Вы достигли конца маршрута.", ());
TEST_EQUAL(getTtsText(notifiation4), "Затем. Поворот налево.", ());
}
UNIT_TEST(GetAllSoundedDistMetersTest)
{
VecPairDist const allSoundedDistMeters = GetAllSoundedDistMeters();
TEST(is_sorted(allSoundedDistMeters.cbegin(), allSoundedDistMeters.cend(),
[](PairDist const & p1, PairDist const & p2)
{
return p1.first < p2.first;
}), ());
TEST_EQUAL(allSoundedDistMeters.size(), 17, ());
PairDist const expected1 = {50, "in_50_meters"};
TEST(pairDistEquals(allSoundedDistMeters[0], expected1), (allSoundedDistMeters[0], expected1));
PairDist const expected2 = {700, "in_700_meters"};
TEST(pairDistEquals(allSoundedDistMeters[8], expected2), (allSoundedDistMeters[8], expected2));
PairDist const expected3 = {3000, "in_3_kilometers"};
TEST(pairDistEquals(allSoundedDistMeters[16], expected3), (allSoundedDistMeters[16], expected3));
}
UNIT_TEST(GetAllSoundedDistFeet)
{
VecPairDist const allSoundedDistFeet = GetAllSoundedDistFeet();
TEST(is_sorted(allSoundedDistFeet.cbegin(), allSoundedDistFeet.cend(),
[](PairDist const & p1, PairDist const & p2)
{
return p1.first < p2.first;
}), ());
TEST_EQUAL(allSoundedDistFeet.size(), 22, ());
PairDist const expected1 = {50, "in_50_feet"};
TEST(pairDistEquals(allSoundedDistFeet[0], expected1), (allSoundedDistFeet[0], expected1));
PairDist const expected2 = {700, "in_700_feet"};
TEST(pairDistEquals(allSoundedDistFeet[7], expected2), (allSoundedDistFeet[7], expected2));
PairDist const expected3 = {10560, "in_2_miles"};
TEST(pairDistEquals(allSoundedDistFeet[21], expected3), (allSoundedDistFeet[21], expected3));
}
UNIT_TEST(GetSoundedDistMeters)
{
vector<uint32_t> const soundedDistMeters = GetSoundedDistMeters();
VecPairDist const allSoundedDistMeters = GetAllSoundedDistMeters();
TEST(is_sorted(soundedDistMeters.cbegin(), soundedDistMeters.cend()), ());
// Checking that allSounded contains any element of inst.
TEST(find_first_of(soundedDistMeters.cbegin(), soundedDistMeters.cend(),
allSoundedDistMeters.cbegin(), allSoundedDistMeters.cend(),
[](uint32_t p1, PairDist const & p2)
{
return p1 == p2.first;
}) != soundedDistMeters.cend(), ());
TEST_EQUAL(soundedDistMeters.size(), 11, ());
TEST_EQUAL(soundedDistMeters[0], 200, ());
TEST_EQUAL(soundedDistMeters[7], 900, ());
TEST_EQUAL(soundedDistMeters[10], 2000, ());
}
UNIT_TEST(GetSoundedDistFeet)
{
vector<uint32_t> soundedDistFeet = GetSoundedDistFeet();
VecPairDist const allSoundedDistFeet = GetAllSoundedDistFeet();
TEST(is_sorted(soundedDistFeet.cbegin(), soundedDistFeet.cend()), ());
// Checking that allSounded contains any element of inst.
TEST(find_first_of(soundedDistFeet.cbegin(), soundedDistFeet.cend(), allSoundedDistFeet.cbegin(),
allSoundedDistFeet.cend(), [](uint32_t p1, PairDist const & p2)
{
return p1 == p2.first;
}) != soundedDistFeet.cend(), ());
TEST_EQUAL(soundedDistFeet.size(), 11, ());
TEST_EQUAL(soundedDistFeet[0], 500, ());
TEST_EQUAL(soundedDistFeet[7], 2000, ());
TEST_EQUAL(soundedDistFeet[10], 5000, ());
}
} // namespace
<commit_msg>Review fixes.<commit_after>#include "testing/testing.hpp"
#include "routing/turns_sound_settings.hpp"
#include "routing/turns_tts_text.hpp"
#include "std/cstring.hpp"
#include "std/string.hpp"
namespace
{
using namespace routing::turns;
using namespace routing::turns::sound;
bool PairDistEquals(PairDist const & lhs, PairDist const & rhs)
{
return lhs.first == rhs.first && strcmp(lhs.second, rhs.second) == 0;
}
UNIT_TEST(GetDistanceTextIdMetersTest)
{
// Notification(uint32_t distanceUnits, uint8_t exitNum, bool useThenInsteadOfDistance,
// TurnDirection turnDir, LengthUnits lengthUnits)
Notification const notifiation1(500, 0, false, TurnDirection::TurnRight, LengthUnits::Meters);
TEST_EQUAL(GetDistanceTextId(notifiation1), "in_500_meters", ());
Notification const notifiation2(500, 0, true, TurnDirection::TurnRight, LengthUnits::Meters);
TEST_EQUAL(GetDistanceTextId(notifiation2), "then", ());
Notification const notifiation3(200, 0, false, TurnDirection::TurnRight, LengthUnits::Meters);
TEST_EQUAL(GetDistanceTextId(notifiation3), "in_200_meters", ());
Notification const notifiation4(2000, 0, false, TurnDirection::TurnRight, LengthUnits::Meters);
TEST_EQUAL(GetDistanceTextId(notifiation4), "in_2_kilometers", ());
}
UNIT_TEST(GetDistanceTextIdFeetTest)
{
Notification const notifiation1(500, 0, false, TurnDirection::TurnRight, LengthUnits::Feet);
TEST_EQUAL(GetDistanceTextId(notifiation1), "in_500_feet", ());
Notification const notifiation2(500, 0, true, TurnDirection::TurnRight, LengthUnits::Feet);
TEST_EQUAL(GetDistanceTextId(notifiation2), "then", ());
Notification const notifiation3(800, 0, false, TurnDirection::TurnRight, LengthUnits::Feet);
TEST_EQUAL(GetDistanceTextId(notifiation3), "in_800_feet", ());
Notification const notifiation4(5000, 0, false, TurnDirection::TurnRight, LengthUnits::Feet);
TEST_EQUAL(GetDistanceTextId(notifiation4), "in_5000_feet", ());
}
UNIT_TEST(GetDirectionTextIdTest)
{
Notification const notifiation1(500, 0, false, TurnDirection::TurnRight, LengthUnits::Feet);
TEST_EQUAL(GetDirectionTextId(notifiation1), "make_a_right_turn", ());
Notification const notifiation2(1000, 0, false, TurnDirection::GoStraight, LengthUnits::Meters);
TEST_EQUAL(GetDirectionTextId(notifiation2), "go_straight", ());
Notification const notifiation3(700, 0, false, TurnDirection::UTurn, LengthUnits::Meters);
TEST_EQUAL(GetDirectionTextId(notifiation3), "make_a_u_turn", ());
}
UNIT_TEST(GetTtsTextTest)
{
string const engShortJson =
"\
{\
\"in_300_meters\":\"In 300 meters.\",\
\"in_500_meters\":\"In 500 meters.\",\
\"then\":\"Then.\",\
\"make_a_right_turn\":\"Make a right turn.\",\
\"make_a_left_turn\":\"Make a left turn.\",\
\"you_have_reached_the_destination\":\"You have reached the destination.\"\
}";
string const rusShortJson =
"\
{\
\"in_300_meters\":\"Через 300 метров.\",\
\"in_500_meters\":\"Через 500 метров.\",\
\"then\":\"Затем.\",\
\"make_a_right_turn\":\"Поворот направо.\",\
\"make_a_left_turn\":\"Поворот налево.\",\
\"you_have_reached_the_destination\":\"Вы достигли конца маршрута.\"\
}";
GetTtsText getTtsText;
// Notification(uint32_t distanceUnits, uint8_t exitNum, bool useThenInsteadOfDistance,
// TurnDirection turnDir, LengthUnits lengthUnits)
Notification const notifiation1(500, 0, false, TurnDirection::TurnRight, LengthUnits::Meters);
Notification const notifiation2(300, 0, false, TurnDirection::TurnLeft, LengthUnits::Meters);
Notification const notifiation3(0, 0, false, TurnDirection::ReachedYourDestination,
LengthUnits::Meters);
Notification const notifiation4(0, 0, true, TurnDirection::TurnLeft, LengthUnits::Meters);
getTtsText.SetLocaleWithJson(engShortJson);
TEST_EQUAL(getTtsText(notifiation1), "In 500 meters. Make a right turn.", ());
TEST_EQUAL(getTtsText(notifiation2), "In 300 meters. Make a left turn.", ());
TEST_EQUAL(getTtsText(notifiation3), "You have reached the destination.", ());
TEST_EQUAL(getTtsText(notifiation4), "Then. Make a left turn.", ());
getTtsText.SetLocaleWithJson(rusShortJson);
TEST_EQUAL(getTtsText(notifiation1), "Через 500 метров. Поворот направо.", ());
TEST_EQUAL(getTtsText(notifiation2), "Через 300 метров. Поворот налево.", ());
TEST_EQUAL(getTtsText(notifiation3), "Вы достигли конца маршрута.", ());
TEST_EQUAL(getTtsText(notifiation4), "Затем. Поворот налево.", ());
}
UNIT_TEST(GetAllSoundedDistMetersTest)
{
VecPairDist const allSoundedDistMeters = GetAllSoundedDistMeters();
TEST(is_sorted(allSoundedDistMeters.cbegin(), allSoundedDistMeters.cend(),
[](PairDist const & p1, PairDist const & p2)
{
return p1.first < p2.first;
}), ());
TEST_EQUAL(allSoundedDistMeters.size(), 17, ());
PairDist const expected1 = {50, "in_50_meters"};
TEST(PairDistEquals(allSoundedDistMeters[0], expected1), (allSoundedDistMeters[0], expected1));
PairDist const expected2 = {700, "in_700_meters"};
TEST(PairDistEquals(allSoundedDistMeters[8], expected2), (allSoundedDistMeters[8], expected2));
PairDist const expected3 = {3000, "in_3_kilometers"};
TEST(PairDistEquals(allSoundedDistMeters[16], expected3), (allSoundedDistMeters[16], expected3));
}
UNIT_TEST(GetAllSoundedDistFeet)
{
VecPairDist const allSoundedDistFeet = GetAllSoundedDistFeet();
TEST(is_sorted(allSoundedDistFeet.cbegin(), allSoundedDistFeet.cend(),
[](PairDist const & p1, PairDist const & p2)
{
return p1.first < p2.first;
}), ());
TEST_EQUAL(allSoundedDistFeet.size(), 22, ());
PairDist const expected1 = {50, "in_50_feet"};
TEST(PairDistEquals(allSoundedDistFeet[0], expected1), (allSoundedDistFeet[0], expected1));
PairDist const expected2 = {700, "in_700_feet"};
TEST(PairDistEquals(allSoundedDistFeet[7], expected2), (allSoundedDistFeet[7], expected2));
PairDist const expected3 = {10560, "in_2_miles"};
TEST(PairDistEquals(allSoundedDistFeet[21], expected3), (allSoundedDistFeet[21], expected3));
}
UNIT_TEST(GetSoundedDistMeters)
{
vector<uint32_t> const soundedDistMeters = GetSoundedDistMeters();
VecPairDist const allSoundedDistMeters = GetAllSoundedDistMeters();
TEST(is_sorted(soundedDistMeters.cbegin(), soundedDistMeters.cend()), ());
// Checking that allSounded contains any element of inst.
TEST(find_first_of(soundedDistMeters.cbegin(), soundedDistMeters.cend(),
allSoundedDistMeters.cbegin(), allSoundedDistMeters.cend(),
[](uint32_t p1, PairDist const & p2)
{
return p1 == p2.first;
}) != soundedDistMeters.cend(), ());
TEST_EQUAL(soundedDistMeters.size(), 11, ());
TEST_EQUAL(soundedDistMeters[0], 200, ());
TEST_EQUAL(soundedDistMeters[7], 900, ());
TEST_EQUAL(soundedDistMeters[10], 2000, ());
}
UNIT_TEST(GetSoundedDistFeet)
{
vector<uint32_t> soundedDistFeet = GetSoundedDistFeet();
VecPairDist const allSoundedDistFeet = GetAllSoundedDistFeet();
TEST(is_sorted(soundedDistFeet.cbegin(), soundedDistFeet.cend()), ());
// Checking that allSounded contains any element of inst.
TEST(find_first_of(soundedDistFeet.cbegin(), soundedDistFeet.cend(), allSoundedDistFeet.cbegin(),
allSoundedDistFeet.cend(), [](uint32_t p1, PairDist const & p2)
{
return p1 == p2.first;
}) != soundedDistFeet.cend(), ());
TEST_EQUAL(soundedDistFeet.size(), 11, ());
TEST_EQUAL(soundedDistFeet[0], 500, ());
TEST_EQUAL(soundedDistFeet[7], 2000, ());
TEST_EQUAL(soundedDistFeet[10], 5000, ());
}
} // namespace
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 1998 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)
#ident "$Id: display.cc,v 1.2 1998/11/10 00:48:31 steve Exp $"
#endif
# include "vvm.h"
# include "vvm_calltf.h"
# include <iostream>
static void format_bit(ostream&os, class vvm_calltf_parm*parm)
{
switch (parm->type()) {
case vvm_calltf_parm::NONE:
os << "z";
break;
case vvm_calltf_parm::ULONG:
os << ((parm->as_ulong()&1) ? "0" : "1");
break;
case vvm_calltf_parm::STRING:
os << parm->as_string();
break;
case vvm_calltf_parm::BITS:
os << parm->as_bits()->get_bit(0);
break;
}
}
static void format_dec(vvm_simulation*sim, ostream&os,
class vvm_calltf_parm*parm)
{
switch (parm->type()) {
case vvm_calltf_parm::TIME:
os << sim->get_sim_time();
break;
case vvm_calltf_parm::NONE:
os << "0";
break;
case vvm_calltf_parm::ULONG:
os << parm->as_ulong();
break;
case vvm_calltf_parm::STRING:
os << parm->as_string();
break;
case vvm_calltf_parm::BITS: {
unsigned long val = 0;
unsigned long mask = 1;
const vvm_bits_t*bstr = parm->as_bits();
for (unsigned idx = 0 ; idx < bstr->get_width() ; idx += 1) {
if (bstr->get_bit(idx) == V1) val |= mask;
mask <<= 1;
}
os << val;
break;
}
}
}
static void format_name(ostream&os, class vvm_calltf_parm*parm)
{
switch (parm->type()) {
case vvm_calltf_parm::TIME:
os << "$time";
break;
case vvm_calltf_parm::NONE:
break;
case vvm_calltf_parm::ULONG:
os << parm->as_ulong();
break;
case vvm_calltf_parm::STRING:
os << "\"" << parm->as_string() << "\"";
break;
case vvm_calltf_parm::BITS:
os << parm->sig_name();
break;
}
}
static unsigned format(vvm_simulation*sim, const string&str,
unsigned nparms,
class vvm_calltf_parm*parms)
{
char prev = 0;
unsigned next_parm = 0;
unsigned idx = 0;
while (idx < str.length()) {
if (prev == '%') {
switch (str[idx]) {
case 'b':
case 'B':
format_bit(cout, parms+next_parm);
next_parm += 1;
break;
case 'd':
case 'D':
format_dec(sim, cout, parms+next_parm);
next_parm += 1;
break;
case 'm':
case 'M':
format_name(cout, parms+next_parm);
next_parm += 1;
break;
case '%':
cout << str[idx];
break;
}
prev = 0;
} else {
if (str[idx] != '%')
cout << str[idx];
else
prev = '%';
}
idx += 1;
}
return next_parm;
}
void Sdisplay(vvm_simulation*sim, const string&name,
unsigned nparms, class vvm_calltf_parm*parms)
{
for (unsigned idx = 0 ; idx < nparms ; idx += 1)
switch (parms[idx].type()) {
case vvm_calltf_parm::NONE:
cout << " ";
break;
case vvm_calltf_parm::TIME:
cout << sim->get_sim_time();
break;
case vvm_calltf_parm::ULONG:
cout << parms[idx].as_ulong();
break;
case vvm_calltf_parm::STRING:
idx += format(sim, parms[idx].as_string(),
nparms-idx-1, parms+idx+1);
break;
case vvm_calltf_parm::BITS:
cout << *parms[idx].as_bits();
break;
}
cout << endl;
}
class monitor_event : public vvm_event {
public:
monitor_event(vvm_simulation*sim,
unsigned nparms, class vvm_calltf_parm*parms)
{ sim_ = sim;
nparms_ = nparms;
parms_ = new vvm_calltf_parm[nparms];
for (unsigned idx = 0 ; idx < nparms_ ; idx += 1)
parms_[idx] = parms[idx];
}
~monitor_event() { delete[]parms_; }
private:
vvm_simulation*sim_;
unsigned nparms_;
vvm_calltf_parm*parms_;
void event_function();
};
void monitor_event::event_function()
{
Sdisplay(sim_, "$display", nparms_, parms_);
}
static monitor_event*mon = 0;
void Smonitor(vvm_simulation*sim, const string&name,
unsigned nparms, class vvm_calltf_parm*parms)
{
if (mon) delete mon;
mon = new monitor_event(sim, nparms, parms);
for (unsigned idx = 0 ; idx < nparms ; idx += 1) {
if (parms[idx].type() != vvm_calltf_parm::BITS)
continue;
parms[idx].as_mon()->enable(mon);
}
}
/*
* $Log: display.cc,v $
* Revision 1.2 1998/11/10 00:48:31 steve
* Add support it vvm target for level-sensitive
* triggers (i.e. the Verilog wait).
* Fix display of $time is format strings.
*
* Revision 1.1 1998/11/09 23:44:10 steve
* Add vvm library.
*
*/
<commit_msg> Proberly print vectors in binary.<commit_after>/*
* Copyright (c) 1998 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)
#ident "$Id: display.cc,v 1.3 1999/01/01 01:44:40 steve Exp $"
#endif
# include "vvm.h"
# include "vvm_calltf.h"
# include <iostream>
static void format_bit(ostream&os, class vvm_calltf_parm*parm)
{
switch (parm->type()) {
case vvm_calltf_parm::NONE:
os << "z";
break;
case vvm_calltf_parm::ULONG:
os << ((parm->as_ulong()&1) ? "0" : "1");
break;
case vvm_calltf_parm::STRING:
os << parm->as_string();
break;
case vvm_calltf_parm::BITS:
for (unsigned idx = parm->as_bits()->get_width()
; idx > 0 ; idx -= 1)
os << parm->as_bits()->get_bit(idx-1);
break;
}
}
static void format_dec(vvm_simulation*sim, ostream&os,
class vvm_calltf_parm*parm)
{
switch (parm->type()) {
case vvm_calltf_parm::TIME:
os << sim->get_sim_time();
break;
case vvm_calltf_parm::NONE:
os << "0";
break;
case vvm_calltf_parm::ULONG:
os << parm->as_ulong();
break;
case vvm_calltf_parm::STRING:
os << parm->as_string();
break;
case vvm_calltf_parm::BITS: {
unsigned long val = 0;
unsigned long mask = 1;
const vvm_bits_t*bstr = parm->as_bits();
for (unsigned idx = 0 ; idx < bstr->get_width() ; idx += 1) {
if (bstr->get_bit(idx) == V1) val |= mask;
mask <<= 1;
}
os << val;
break;
}
}
}
static void format_name(ostream&os, class vvm_calltf_parm*parm)
{
switch (parm->type()) {
case vvm_calltf_parm::TIME:
os << "$time";
break;
case vvm_calltf_parm::NONE:
break;
case vvm_calltf_parm::ULONG:
os << parm->as_ulong();
break;
case vvm_calltf_parm::STRING:
os << "\"" << parm->as_string() << "\"";
break;
case vvm_calltf_parm::BITS:
os << parm->sig_name();
break;
}
}
static unsigned format(vvm_simulation*sim, const string&str,
unsigned nparms,
class vvm_calltf_parm*parms)
{
char prev = 0;
unsigned next_parm = 0;
unsigned idx = 0;
while (idx < str.length()) {
if (prev == '%') {
switch (str[idx]) {
case 'b':
case 'B':
format_bit(cout, parms+next_parm);
next_parm += 1;
break;
case 'd':
case 'D':
format_dec(sim, cout, parms+next_parm);
next_parm += 1;
break;
case 'm':
case 'M':
format_name(cout, parms+next_parm);
next_parm += 1;
break;
case '%':
cout << str[idx];
break;
}
prev = 0;
} else {
if (str[idx] != '%')
cout << str[idx];
else
prev = '%';
}
idx += 1;
}
return next_parm;
}
void Sdisplay(vvm_simulation*sim, const string&name,
unsigned nparms, class vvm_calltf_parm*parms)
{
for (unsigned idx = 0 ; idx < nparms ; idx += 1)
switch (parms[idx].type()) {
case vvm_calltf_parm::NONE:
cout << " ";
break;
case vvm_calltf_parm::TIME:
cout << sim->get_sim_time();
break;
case vvm_calltf_parm::ULONG:
cout << parms[idx].as_ulong();
break;
case vvm_calltf_parm::STRING:
idx += format(sim, parms[idx].as_string(),
nparms-idx-1, parms+idx+1);
break;
case vvm_calltf_parm::BITS:
cout << *parms[idx].as_bits();
break;
}
cout << endl;
}
class monitor_event : public vvm_event {
public:
monitor_event(vvm_simulation*sim,
unsigned nparms, class vvm_calltf_parm*parms)
{ sim_ = sim;
nparms_ = nparms;
parms_ = new vvm_calltf_parm[nparms];
for (unsigned idx = 0 ; idx < nparms_ ; idx += 1)
parms_[idx] = parms[idx];
}
~monitor_event() { delete[]parms_; }
private:
vvm_simulation*sim_;
unsigned nparms_;
vvm_calltf_parm*parms_;
void event_function();
};
void monitor_event::event_function()
{
Sdisplay(sim_, "$display", nparms_, parms_);
}
static monitor_event*mon = 0;
void Smonitor(vvm_simulation*sim, const string&name,
unsigned nparms, class vvm_calltf_parm*parms)
{
if (mon) delete mon;
mon = new monitor_event(sim, nparms, parms);
for (unsigned idx = 0 ; idx < nparms ; idx += 1) {
if (parms[idx].type() != vvm_calltf_parm::BITS)
continue;
parms[idx].as_mon()->enable(mon);
}
}
/*
* $Log: display.cc,v $
* Revision 1.3 1999/01/01 01:44:40 steve
* Proberly print vectors in binary.
*
* Revision 1.2 1998/11/10 00:48:31 steve
* Add support it vvm target for level-sensitive
* triggers (i.e. the Verilog wait).
* Fix display of $time is format strings.
*
* Revision 1.1 1998/11/09 23:44:10 steve
* Add vvm library.
*
*/
<|endoftext|>
|
<commit_before><commit_msg>Don't use SDCH until open_vcdiff works on all platforms.<commit_after><|endoftext|>
|
<commit_before><commit_msg>Adding pipeline test, gotta figure out whats up with the threads and memory leaks<commit_after>//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// pipeline_test.cpp
//
// Identification: tests/mfabric/pipeline_test.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <string.h>
#include <unistd.h>
#include <assert.h>
#include <stdio.h>
#include <cstring>
#include <cassert>
#include "gtest/gtest.h"
#include "harness.h"
#include "backend/mfabric/libnanomsg/src/nn.h"
#include "backend/mfabric/libnanomsg/src/pipeline.h"
namespace peloton {
namespace test {
//===--------------------------------------------------------------------===//
// Pipeline Tests
//===--------------------------------------------------------------------===//
#define NODE0 "node0"
#define NODE1 "node1"
int node0 (const char *url)
{
int sock = nn_socket (AF_SP, NN_PULL);
assert (sock >= 0);
assert (nn_bind (sock, url) >= 0);
while (1)
{
char *buf = NULL;
int bytes = nn_recv (sock, &buf, NN_MSG, 0);
assert (bytes >= 0);
printf ("NODE0: RECEIVED \"%s\"\n", buf);
nn_freemsg (buf);
}
}
int node1 (const char *url, const char *msg)
{
int sz_msg = strlen (msg) + 1; // '\0' too
int sock = nn_socket (AF_SP, NN_PUSH);
assert (sock >= 0);
assert (nn_connect (sock, url) >= 0);
printf ("NODE1: SENDING \"%s\"\n", msg);
int bytes = nn_send (sock, msg, sz_msg, 0);
assert (bytes == sz_msg);
return nn_shutdown (sock, 0);
}
TEST (PipelineTest, BasicTest)
{
std::thread send(node0,"ipc:///tmp/pair.ipc");
send.detach();
std::thread recv(node1,"ipc:///tmp/pair.ipc","Hello!");
recv.detach();
sleep(3);
}
} // End test namespace
} // End peloton namespace
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: sizedev.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: nn $ $Date: 2001-05-15 13:40:48 $
*
* 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 SC_SIZEDEV_HXX
#define SC_SIZEDEV_HXX
#ifndef _SV_MAPMOD_HXX
#include <vcl/mapmod.hxx>
#endif
class OutputDevice;
class ScDocShell;
class ScSizeDeviceProvider
{
OutputDevice* pDevice;
BOOL bOwner;
double nPPTX;
double nPPTY;
MapMode aOldMapMode;
public:
ScSizeDeviceProvider( ScDocShell* pDocSh );
~ScSizeDeviceProvider();
OutputDevice* GetDevice() const { return pDevice; }
double GetPPTX() const { return nPPTX; }
double GetPPTY() const { return nPPTY; }
BOOL IsPrinter() const { return !bOwner; }
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.930); FILE MERGED 2005/09/05 15:05:49 rt 1.2.930.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sizedev.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 21:50:46 $
*
* 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
*
************************************************************************/
#ifndef SC_SIZEDEV_HXX
#define SC_SIZEDEV_HXX
#ifndef _SV_MAPMOD_HXX
#include <vcl/mapmod.hxx>
#endif
class OutputDevice;
class ScDocShell;
class ScSizeDeviceProvider
{
OutputDevice* pDevice;
BOOL bOwner;
double nPPTX;
double nPPTY;
MapMode aOldMapMode;
public:
ScSizeDeviceProvider( ScDocShell* pDocSh );
~ScSizeDeviceProvider();
OutputDevice* GetDevice() const { return pDevice; }
double GetPPTX() const { return nPPTX; }
double GetPPTY() const { return nPPTY; }
BOOL IsPrinter() const { return !bOwner; }
};
#endif
<|endoftext|>
|
<commit_before>#include "Resources.h"
#include "cinder/ObjLoader.h"
#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "cinder/Arcball.h"
#include "cinder/CameraUi.h"
#include "cinder/Sphere.h"
#include "cinder/ImageIo.h"
#include "cinder/ip/Checkerboard.h"
#include "Resources.h"
using namespace ci;
using namespace ci::app;
class ObjLoaderApp : public App {
public:
void setup() override;
void mouseDown( MouseEvent event ) override;
void mouseDrag( MouseEvent event ) override;
void keyDown( KeyEvent event ) override;
void loadObj( const DataSourceRef &dataSource );
void frameCurrentObject();
void draw() override;
Arcball mArcball;
CameraUi mCamUi;
CameraPersp mCam;
TriMeshRef mMesh;
Sphere mBoundingSphere;
gl::BatchRef mBatch;
gl::GlslProgRef mGlsl;
gl::TextureRef mCheckerTexture;
};
void ObjLoaderApp::setup()
{
#if defined( CINDER_GL_ES )
mGlsl = gl::GlslProg::create( loadAsset( "shader_es2.vert" ), loadAsset( "shader_es2.frag" ) );
#else
mGlsl = gl::GlslProg::create( loadAsset( "shader.vert" ), loadAsset( "shader.frag" ) );
#endif
mGlsl->uniform( "uTex0", 0 );
mCam.setPerspective( 45.0f, getWindowAspectRatio(), 0.1, 10000 );
mCamUi = CameraUi( &mCam );
mCheckerTexture = gl::Texture::create( ip::checkerboard( 512, 512, 32 ) );
mCheckerTexture->bind( 0 );
loadObj( loadResource( RES_8LBS_OBJ ) );
mArcball = Arcball( &mCam, mBoundingSphere );
}
void ObjLoaderApp::mouseDown( MouseEvent event )
{
if( event.isMetaDown() )
mCamUi.mouseDown( event );
else
mArcball.mouseDown( event );
}
void ObjLoaderApp::mouseDrag( MouseEvent event )
{
if( event.isMetaDown() )
mCamUi.mouseDrag( event );
else
mArcball.mouseDrag( event );
}
void ObjLoaderApp::loadObj( const DataSourceRef &dataSource )
{
ObjLoader loader( dataSource );
mMesh = TriMesh::create( loader );
if( ! loader.getAvailableAttribs().count( geom::NORMAL ) )
mMesh->recalculateNormals();
mBatch = gl::Batch::create( *mMesh, mGlsl );
mBoundingSphere = Sphere::calculateBoundingSphere( mMesh->getPositions<3>(), mMesh->getNumVertices() );
mArcball.setSphere( mBoundingSphere );
}
void ObjLoaderApp::frameCurrentObject()
{
mCam = mCam.calcFraming( mBoundingSphere );
}
void ObjLoaderApp::keyDown( KeyEvent event )
{
if( event.getChar() == 'o' ) {
fs::path path = getOpenFilePath();
if( ! path.empty() ) {
loadObj( loadFile( path ) );
}
}
else if( event.getChar() == 'f' ) {
frameCurrentObject();
}
}
void ObjLoaderApp::draw()
{
gl::enableDepthWrite();
gl::enableDepthRead();
gl::clear( Color( 0.0f, 0.1f, 0.2f ) );
gl::setMatrices( mCam );
gl::pushMatrices();
gl::rotate( mArcball.getQuat() );
mBatch->draw();
gl::popMatrices();
}
CINDER_APP( ObjLoaderApp, RendererGl, [] ( App::Settings *settings ) {
settings->setMultiTouchEnabled( false );
} )<commit_msg>added sample code to write an obj as it wasn’t used anywhere else<commit_after>#include "Resources.h"
#include "cinder/ObjLoader.h"
#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "cinder/Arcball.h"
#include "cinder/CameraUi.h"
#include "cinder/Sphere.h"
#include "cinder/ImageIo.h"
#include "cinder/ip/Checkerboard.h"
#include "Resources.h"
using namespace ci;
using namespace ci::app;
class ObjLoaderApp : public App {
public:
void setup() override;
void mouseDown( MouseEvent event ) override;
void mouseDrag( MouseEvent event ) override;
void keyDown( KeyEvent event ) override;
void loadObj( const DataSourceRef &dataSource );
void writeObj();
void frameCurrentObject();
void draw() override;
Arcball mArcball;
CameraUi mCamUi;
CameraPersp mCam;
TriMeshRef mMesh;
Sphere mBoundingSphere;
gl::BatchRef mBatch;
gl::GlslProgRef mGlsl;
gl::TextureRef mCheckerTexture;
};
void ObjLoaderApp::setup()
{
#if defined( CINDER_GL_ES )
mGlsl = gl::GlslProg::create( loadAsset( "shader_es2.vert" ), loadAsset( "shader_es2.frag" ) );
#else
mGlsl = gl::GlslProg::create( loadAsset( "shader.vert" ), loadAsset( "shader.frag" ) );
#endif
mGlsl->uniform( "uTex0", 0 );
mCam.setPerspective( 45.0f, getWindowAspectRatio(), 0.1, 10000 );
mCamUi = CameraUi( &mCam );
mCheckerTexture = gl::Texture::create( ip::checkerboard( 512, 512, 32 ) );
mCheckerTexture->bind( 0 );
loadObj( loadResource( RES_8LBS_OBJ ) );
mArcball = Arcball( &mCam, mBoundingSphere );
}
void ObjLoaderApp::mouseDown( MouseEvent event )
{
if( event.isMetaDown() )
mCamUi.mouseDown( event );
else
mArcball.mouseDown( event );
}
void ObjLoaderApp::mouseDrag( MouseEvent event )
{
if( event.isMetaDown() )
mCamUi.mouseDrag( event );
else
mArcball.mouseDrag( event );
}
void ObjLoaderApp::loadObj( const DataSourceRef &dataSource )
{
ObjLoader loader( dataSource );
mMesh = TriMesh::create( loader );
if( ! loader.getAvailableAttribs().count( geom::NORMAL ) )
mMesh->recalculateNormals();
mBatch = gl::Batch::create( *mMesh, mGlsl );
mBoundingSphere = Sphere::calculateBoundingSphere( mMesh->getPositions<3>(), mMesh->getNumVertices() );
mArcball.setSphere( mBoundingSphere );
}
void ObjLoaderApp::writeObj()
{
fs::path filePath = getSaveFilePath();
if( ! filePath.empty() ) {
console() << "writing mesh to file path: " << filePath << std::endl;
objWrite( writeFile( filePath ), mMesh );
}
}
void ObjLoaderApp::frameCurrentObject()
{
mCam = mCam.calcFraming( mBoundingSphere );
}
void ObjLoaderApp::keyDown( KeyEvent event )
{
if( event.getChar() == 'o' ) {
fs::path path = getOpenFilePath();
if( ! path.empty() ) {
loadObj( loadFile( path ) );
}
}
else if( event.getChar() == 'f' ) {
frameCurrentObject();
}
else if( event.getChar() == 'w' ) {
writeObj();
}
}
void ObjLoaderApp::draw()
{
gl::enableDepthWrite();
gl::enableDepthRead();
gl::clear( Color( 0.0f, 0.1f, 0.2f ) );
gl::setMatrices( mCam );
gl::pushMatrices();
gl::rotate( mArcball.getQuat() );
mBatch->draw();
gl::popMatrices();
}
CINDER_APP( ObjLoaderApp, RendererGl, [] ( App::Settings *settings ) {
settings->setMultiTouchEnabled( false );
} )<|endoftext|>
|
<commit_before>/*
Copyright (c) 2014 Harm Hanemaaijer <fgenfb@yahoo.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
// X11 (low-level) OpenGL(GLX) interface.
// Uses X11 handling in x11-common.c.
// Currently requires freeglut to get around issues with
// initializing GLEW and destroying atemporary window at
// start-up.
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include <sys/time.h>
#include <assert.h>
#include <GL/glew.h>
#include <GL/glxew.h>
#include <GL/gl.h>
#include <GL/glext.h>
#include <GL/glx.h>
// We don´t really use glut, but only use it to create a temporary
// rendering context before initializing GLEW.
#include <GL/glut.h>
#include <GL/freeglut_ext.h>
#include "sre.h"
#include "demo.h"
#include "x11-common.h"
#include "gui-common.h"
typedef struct
{
uint32_t screen_width;
uint32_t screen_height;
Display *XDisplay;
GLXWindow XWindow;
GLXContext context;
} GL_STATE_T;
static GL_STATE_T *state;
static GLXFBConfig chosen_fb_config;
#define check() assert(glGetError() == 0)
// Default Open GL context settings: 8-bit truecolor with alpha,
// 24-bit depth buffer, 8-bit stencil, 4 sample MSAA.
static GLint visual_attributes[] = {
GLX_X_RENDERABLE, True,
GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
GLX_RENDER_TYPE, GLX_RGBA_BIT,
GLX_X_VISUAL_TYPE, GLX_TRUE_COLOR,
GLX_RED_SIZE, 8,
GLX_GREEN_SIZE, 8,
GLX_BLUE_SIZE, 8,
GLX_ALPHA_SIZE, 8,
GLX_DEPTH_SIZE, 24,
GLX_STENCIL_SIZE, 8,
GLX_DOUBLEBUFFER, True,
#ifndef NO_MULTI_SAMPLE
GLX_SAMPLE_BUFFERS, 1, // Use MSAA
GLX_SAMPLES, 4,
#endif
None
};
void CloseGlutWindow() {
}
void GUIInitialize(int *argc, char ***argv) {
// To call GLX functions with glew, we need to call glewInit()
// first, but it needs an active OpenGL context to be present. So we have to
// create a temporary GL context.
glutInit(argc, *argv);
int glut_window = glutCreateWindow("GLEW Test");
GLenum err = glewInit();
if (GLEW_OK != err) {
/* Problem: glewInit failed, something is seriously wrong. */
fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
exit(1);
}
fprintf(stdout, "Status: Using GLEW %s.\n", glewGetString(GLEW_VERSION));
// glutCloseFunc(CloseGlutWindow);
glutHideWindow();
glutDestroyWindow(glut_window);
// Problem: How to completely hide the glut window? It doesn't disappear. Requires
// freeglut to fix.
glutMainLoopEvent();
state = (GL_STATE_T *)malloc(sizeof(GL_STATE_T));
// Clear application state
memset(state, 0, sizeof(*state));
X11OpenDisplay();
state->XDisplay = (Display *)X11GetDisplay();
// XDestroyWindow(state->XDisplay, glut_window);
// Require GLX >= 1.3
GLint glx_major, glx_minor;
GLint result = glXQueryVersion(state->XDisplay, &glx_major, &glx_minor);
if (glx_major < 1 || (glx_major == 1 && glx_minor < 3)) {
printf("Error: GLX version major reported is %d.%d, need at least 1.3.\n",
glx_major, glx_minor);
exit(1);
}
printf("GLX version: %d.%d\n", glx_major, glx_minor);
// Obtain appropriate GLX framebuffer configurations.
GLint num_config;
GLXFBConfig *fb_config = glXChooseFBConfig(state->XDisplay, X11GetScreenIndex(),
visual_attributes, &num_config);
assert(result != GL_FALSE);
if (num_config == 0) {
printf("GLX returned no suitable framebuffer configurations.\n");
exit(1);
}
printf("OpenGL (GLX): %d framebuffer configurations returned.\n", num_config);
for (int i = 0; i < num_config; i++ ) {
XVisualInfo *vi = glXGetVisualFromFBConfig(state->XDisplay, fb_config[i]);
if (vi) {
int samp_buf, samples;
glXGetFBConfigAttrib(state->XDisplay, fb_config[i], GLX_SAMPLE_BUFFERS, &samp_buf);
glXGetFBConfigAttrib(state->XDisplay, fb_config[i], GLX_SAMPLES, &samples);
printf( " Matching framebuffer config %d, visual ID 0x%2x: SAMPLE_BUFFERS = %d,"
" SAMPLES = %d\n", i, vi->visualid, samp_buf, samples);
XFree(vi);
}
}
chosen_fb_config = fb_config[0];
XFree(fb_config);
XVisualInfo *vi = glXGetVisualFromFBConfig(state->XDisplay, chosen_fb_config);
printf("Chosen visual ID = 0x%x\n", vi->visualid );
// Create an X window with that visual.
X11CreateWindow(window_width, window_height, vi, "render OpenGL 3.0+ X11 demo");
XFree(vi);
state->XWindow = (GLXWindow)X11GetWindow();
if (!GLXEW_ARB_create_context) {
// Create GLX rendering context.
printf("Creating old-style (GLX 1.3) context.\n");
state->context = glXCreateNewContext(state->XDisplay, chosen_fb_config,
GLX_RGBA_TYPE, 0, True);
}
else {
int context_attribs[] = {
GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
GLX_CONTEXT_MINOR_VERSION_ARB, 0,
//GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
None
};
printf( "Creating OpenGL 3.0 context.\n" );
state->context = glXCreateContextAttribsARB(state->XDisplay,
chosen_fb_config, 0, True, context_attribs);
}
assert(state->context != NULL);
check();
int stencil_bits = 8;
int depth_bits = 24;
printf("Opened OpenGL context of size %d x %d with 32-bit pixels, %d-bit depthbuffer and %d-bit stencil.\n", window_width,
window_height, depth_bits, stencil_bits);
// Verifying that context is a direct context
if (!glXIsDirect(state->XDisplay, state->context)) {
printf("Indirect GLX rendering context obtained.\n");
}
else {
printf("Direct GLX rendering context obtained.\n");
}
glXMakeCurrent(state->XDisplay, X11GetWindow(), state->context);
check();
sreInitialize(window_width, window_height, GUIGLSwapBuffers);
}
void GUIFinalize() {
// Clear screen.
glClear(GL_COLOR_BUFFER_BIT);
GUIGLSync();
glXMakeCurrent(state->XDisplay, 0, NULL);
glXDestroyContext(state->XDisplay, state->context);
X11DestroyWindow();
X11CloseDisplay();
}
void GUIGLSwapBuffers() {
glXSwapBuffers(state->XDisplay, state->XWindow);
}
void GUIGLSync() {
glXSwapBuffers(state->XDisplay, state->XWindow);
glXWaitGL();
}
const char *GUIGetBackendName() {
return "OpenGL X11 (low-level)";
}
<commit_msg>Change window title when using OpenGL X11 back-end<commit_after>/*
Copyright (c) 2014 Harm Hanemaaijer <fgenfb@yahoo.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
// X11 (low-level) OpenGL(GLX) interface.
// Uses X11 handling in x11-common.c.
// Currently requires freeglut to get around issues with
// initializing GLEW and destroying atemporary window at
// start-up.
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include <sys/time.h>
#include <assert.h>
#include <GL/glew.h>
#include <GL/glxew.h>
#include <GL/gl.h>
#include <GL/glext.h>
#include <GL/glx.h>
// We don´t really use glut, but only use it to create a temporary
// rendering context before initializing GLEW.
#include <GL/glut.h>
#include <GL/freeglut_ext.h>
#include "sre.h"
#include "demo.h"
#include "x11-common.h"
#include "gui-common.h"
typedef struct
{
uint32_t screen_width;
uint32_t screen_height;
Display *XDisplay;
GLXWindow XWindow;
GLXContext context;
} GL_STATE_T;
static GL_STATE_T *state;
static GLXFBConfig chosen_fb_config;
#define check() assert(glGetError() == 0)
// Default Open GL context settings: 8-bit truecolor with alpha,
// 24-bit depth buffer, 8-bit stencil, 4 sample MSAA.
static GLint visual_attributes[] = {
GLX_X_RENDERABLE, True,
GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
GLX_RENDER_TYPE, GLX_RGBA_BIT,
GLX_X_VISUAL_TYPE, GLX_TRUE_COLOR,
GLX_RED_SIZE, 8,
GLX_GREEN_SIZE, 8,
GLX_BLUE_SIZE, 8,
GLX_ALPHA_SIZE, 8,
GLX_DEPTH_SIZE, 24,
GLX_STENCIL_SIZE, 8,
GLX_DOUBLEBUFFER, True,
#ifndef NO_MULTI_SAMPLE
GLX_SAMPLE_BUFFERS, 1, // Use MSAA
GLX_SAMPLES, 4,
#endif
None
};
void CloseGlutWindow() {
}
void GUIInitialize(int *argc, char ***argv) {
// To call GLX functions with glew, we need to call glewInit()
// first, but it needs an active OpenGL context to be present. So we have to
// create a temporary GL context.
glutInit(argc, *argv);
int glut_window = glutCreateWindow("GLEW Test");
GLenum err = glewInit();
if (GLEW_OK != err) {
/* Problem: glewInit failed, something is seriously wrong. */
fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
exit(1);
}
fprintf(stdout, "Status: Using GLEW %s.\n", glewGetString(GLEW_VERSION));
// glutCloseFunc(CloseGlutWindow);
glutHideWindow();
glutDestroyWindow(glut_window);
// Problem: How to completely hide the glut window? It doesn't disappear. Requires
// freeglut to fix.
glutMainLoopEvent();
state = (GL_STATE_T *)malloc(sizeof(GL_STATE_T));
// Clear application state
memset(state, 0, sizeof(*state));
X11OpenDisplay();
state->XDisplay = (Display *)X11GetDisplay();
// XDestroyWindow(state->XDisplay, glut_window);
// Require GLX >= 1.3
GLint glx_major, glx_minor;
GLint result = glXQueryVersion(state->XDisplay, &glx_major, &glx_minor);
if (glx_major < 1 || (glx_major == 1 && glx_minor < 3)) {
printf("Error: GLX version major reported is %d.%d, need at least 1.3.\n",
glx_major, glx_minor);
exit(1);
}
printf("GLX version: %d.%d\n", glx_major, glx_minor);
// Obtain appropriate GLX framebuffer configurations.
GLint num_config;
GLXFBConfig *fb_config = glXChooseFBConfig(state->XDisplay, X11GetScreenIndex(),
visual_attributes, &num_config);
assert(result != GL_FALSE);
if (num_config == 0) {
printf("GLX returned no suitable framebuffer configurations.\n");
exit(1);
}
printf("OpenGL (GLX): %d framebuffer configurations returned.\n", num_config);
for (int i = 0; i < num_config; i++ ) {
XVisualInfo *vi = glXGetVisualFromFBConfig(state->XDisplay, fb_config[i]);
if (vi) {
int samp_buf, samples;
glXGetFBConfigAttrib(state->XDisplay, fb_config[i], GLX_SAMPLE_BUFFERS, &samp_buf);
glXGetFBConfigAttrib(state->XDisplay, fb_config[i], GLX_SAMPLES, &samples);
printf( " Matching framebuffer config %d, visual ID 0x%2x: SAMPLE_BUFFERS = %d,"
" SAMPLES = %d\n", i, vi->visualid, samp_buf, samples);
XFree(vi);
}
}
chosen_fb_config = fb_config[0];
XFree(fb_config);
XVisualInfo *vi = glXGetVisualFromFBConfig(state->XDisplay, chosen_fb_config);
printf("Chosen visual ID = 0x%x\n", vi->visualid );
// Create an X window with that visual.
X11CreateWindow(window_width, window_height, vi, "SRE OpenGL 3.0+ X11 demo");
XFree(vi);
state->XWindow = (GLXWindow)X11GetWindow();
if (!GLXEW_ARB_create_context) {
// Create GLX rendering context.
printf("Creating old-style (GLX 1.3) context.\n");
state->context = glXCreateNewContext(state->XDisplay, chosen_fb_config,
GLX_RGBA_TYPE, 0, True);
}
else {
int context_attribs[] = {
GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
GLX_CONTEXT_MINOR_VERSION_ARB, 0,
//GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
None
};
printf( "Creating OpenGL 3.0 context.\n" );
state->context = glXCreateContextAttribsARB(state->XDisplay,
chosen_fb_config, 0, True, context_attribs);
}
assert(state->context != NULL);
check();
int stencil_bits = 8;
int depth_bits = 24;
printf("Opened OpenGL context of size %d x %d with 32-bit pixels, %d-bit depthbuffer and %d-bit stencil.\n", window_width,
window_height, depth_bits, stencil_bits);
// Verifying that context is a direct context
if (!glXIsDirect(state->XDisplay, state->context)) {
printf("Indirect GLX rendering context obtained.\n");
}
else {
printf("Direct GLX rendering context obtained.\n");
}
glXMakeCurrent(state->XDisplay, X11GetWindow(), state->context);
check();
sreInitialize(window_width, window_height, GUIGLSwapBuffers);
}
void GUIFinalize() {
// Clear screen.
glClear(GL_COLOR_BUFFER_BIT);
GUIGLSync();
glXMakeCurrent(state->XDisplay, 0, NULL);
glXDestroyContext(state->XDisplay, state->context);
X11DestroyWindow();
X11CloseDisplay();
}
void GUIGLSwapBuffers() {
glXSwapBuffers(state->XDisplay, state->XWindow);
}
void GUIGLSync() {
glXSwapBuffers(state->XDisplay, state->XWindow);
glXWaitGL();
}
const char *GUIGetBackendName() {
return "OpenGL X11 (low-level)";
}
<|endoftext|>
|
<commit_before>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#pragma once
#include"ork/ork.hpp"
namespace ork {
/*
The C++ standard does not offer a smart pointer with value sematics.
For one, C++ does not offer a standard way to copy an object to prevent slicing.
Nonetheless, pimpl is so common that we implement a unique ownership, copyable pointer.
The pointer therefore has value semantics, and if such a thing is ever standardized it may be called value_ptr.
We implement a simple wrapper around unique_ptr that delegates copying and deleting to a templated functor.
No default templates are offered.
If pimpl is being used the functor interfaces cannot be defined in a header.
The functor must implement both copy and delete interfaces
std::unique_ptr<T, D> D(const T&);
void D(T*);
No casting interface is offered, although if the copier supports it...
No auto_ptr conversion is offered, because who uses auto_ptr?
No relational operators are offered, because these are a source of more bugs than functionality.
*/
template<class T, class D>
class value_ptr {
public:
using element_type = T;
using pointer = T*;//This is a little simplistic
using copier_type = D;
using deleter_type = D;
private:
std::unique_ptr<T, D>_ptr;
public:
constexpr value_ptr() noexcept : _ptr() {}
constexpr value_ptr(nullptr_t) noexcept : _ptr(nullptr) {}
explicit value_ptr(pointer p) noexcept : _ptr(p) {}
value_ptr(pointer p, typename std::conditional<std::is_reference<D>::value, D, const D&> del) noexcept : _ptr(p, del) {}
value_ptr(pointer p, typename std::remove_reference<D>::type&& del) noexcept : _ptr(p, std::move(del)) {}
value_ptr(value_ptr&& x) noexcept : _ptr(std::mode(x._ptr)) {}
template<class D2>
value_ptr(value_ptr<T, D2>&& x) noexcept : _ptr(std::move(x._ptr)) {}
//Allow conversion from unique_ptr
value_ptr(std::unique_ptr<T, D>&& x) noexcept : _ptr(std::move(x)) {}
template<class D2>
value_ptr(std::unique_ptr<T, D2>&& x) noexcept : _ptr(std::move(x)) {}
//The big payoff
value_ptr(const value_ptr&x) : _ptr(x.get_deleter()(*x._ptr)) {}
template<class D2>
value_ptr(const value_ptr<T, D2>& x) : _ptr(x.get_deleter()(*x._ptr)) {}
//The big payoff + conversion
value_ptr(const std::unique_ptr<T, D>& x) : _ptr(x.get_deleter()(*x._ptr)) {}
template<class D2>
value_ptr(const std::unique_ptr<T, D2>& x) : _ptr(x.get_deleter()(*x._ptr)) {}
//Destructor is implicitly defined
public:
value_ptr& operator=(nullptr_t) noexcept {
_ptr = nullptr;
return *this;
}
value_ptr& operator=(value_ptr&& x) noexcept {
_ptr = std::move(x._ptr);
}
template<class D2>
value_ptr& operator=(value_ptr<T, D2>&& x) noexcept {
_ptr = std::move(x._ptr);
return *this;
}
//Allow conversion from unique_ptr
value_ptr& operator=(std::unique_ptr<T, D>&& x) noexcept {
_ptr = std::move(x);
return *this;
}
template<class D2>
value_ptr& operator=(std::unique_ptr<T, D2>&& x) noexcept {
_ptr = std::move(x);
return *this;
}
//The big payoff
value_ptr& operator=(const value_ptr& x) {
_ptr = x.get_deleter()(*x);
return *this;
}
template<class D2>
value_ptr& operator=(const value_ptr<T, D2>& x) {
_ptr = x.get_deleter()(*x);
return *this;
}
//The big payoff + conversion
value_ptr& operator=(const std::unique_ptr<T, D>& x) {
_ptr = x.get_deleter()(*x);
return *this;
}
template<class D2>
value_ptr& operator=(const std::unique_ptr<T, D2>& x) {
_ptr = x.get_deleter()(*x);
return *this;
}
public:
typename std::add_lvalue_reference<element_type>::type operator*() const {
return _ptr.operator*();
}
pointer operator->() const noexcept {
return _ptr.operator->();
}
pointer get() const noexcept {
return _ptr.get();
}
deleter_type& get_deleter() noexcept {
return _ptr.get_deleter();
}
const deleter_type& get_deleter() const noexcept {
return _ptr.get_deleter();
}
explicit operator bool() const noexcept {
return _ptr.operator bool();
}
pointer release() noexcept {
return _ptr.release();
}
//The reset interface is different than std, but I prefer overloads to default params
void reset() noexcept {
_ptr.reset();
}
void reset(pointer p) noexcept {
_ptr.reset(p);
}
void swap(value_ptr& x) noexcept {
_ptr.swap(x._ptr);
}
};
}//namespace ork
namespace std {
template <class T, class D>
void swap(ork::value_ptr<T, D>& x, ork::value_ptr<T, D>& y) noexcept {
x.swap(y);
}
}//namespace std
<commit_msg>Added clarifying comment about copy interface<commit_after>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#pragma once
#include"ork/ork.hpp"
namespace ork {
/*
The C++ standard does not offer a smart pointer with value sematics.
For one, C++ does not offer a standard way to copy an object to prevent slicing.
Nonetheless, pimpl is so common that we implement a unique ownership, copyable pointer.
The pointer therefore has value semantics, and if such a thing is ever standardized it may be called value_ptr.
We implement a simple wrapper around unique_ptr that delegates copying and deleting to a templated functor.
No default templates are offered.
If pimpl is being used the functor interfaces cannot be defined in a header.
The functor must implement both copy and delete interfaces
std::unique_ptr<T, D> D(const T&);
void D(T*);
Note that the copy interface must handle null objects by returning empty pointer
No casting interface is offered, although if the copier supports it...
No auto_ptr conversion is offered, because who uses auto_ptr?
No relational operators are offered, because these are a source of more bugs than functionality.
*/
template<class T, class D>
class value_ptr {
public:
using element_type = T;
using pointer = T*;//This is a little simplistic
using copier_type = D;
using deleter_type = D;
private:
std::unique_ptr<T, D>_ptr;
public:
constexpr value_ptr() noexcept : _ptr() {}
constexpr value_ptr(nullptr_t) noexcept : _ptr(nullptr) {}
explicit value_ptr(pointer p) noexcept : _ptr(p) {}
value_ptr(pointer p, typename std::conditional<std::is_reference<D>::value, D, const D&> del) noexcept : _ptr(p, del) {}
value_ptr(pointer p, typename std::remove_reference<D>::type&& del) noexcept : _ptr(p, std::move(del)) {}
value_ptr(value_ptr&& x) noexcept : _ptr(std::mode(x._ptr)) {}
template<class D2>
value_ptr(value_ptr<T, D2>&& x) noexcept : _ptr(std::move(x._ptr)) {}
//Allow conversion from unique_ptr
value_ptr(std::unique_ptr<T, D>&& x) noexcept : _ptr(std::move(x)) {}
template<class D2>
value_ptr(std::unique_ptr<T, D2>&& x) noexcept : _ptr(std::move(x)) {}
//The big payoff
value_ptr(const value_ptr&x) : _ptr(x.get_deleter()(*x._ptr)) {}
template<class D2>
value_ptr(const value_ptr<T, D2>& x) : _ptr(x.get_deleter()(*x._ptr)) {}
//The big payoff + conversion
value_ptr(const std::unique_ptr<T, D>& x) : _ptr(x.get_deleter()(*x._ptr)) {}
template<class D2>
value_ptr(const std::unique_ptr<T, D2>& x) : _ptr(x.get_deleter()(*x._ptr)) {}
//Destructor is implicitly defined
public:
value_ptr& operator=(nullptr_t) noexcept {
_ptr = nullptr;
return *this;
}
value_ptr& operator=(value_ptr&& x) noexcept {
_ptr = std::move(x._ptr);
}
template<class D2>
value_ptr& operator=(value_ptr<T, D2>&& x) noexcept {
_ptr = std::move(x._ptr);
return *this;
}
//Allow conversion from unique_ptr
value_ptr& operator=(std::unique_ptr<T, D>&& x) noexcept {
_ptr = std::move(x);
return *this;
}
template<class D2>
value_ptr& operator=(std::unique_ptr<T, D2>&& x) noexcept {
_ptr = std::move(x);
return *this;
}
//The big payoff
value_ptr& operator=(const value_ptr& x) {
_ptr = x.get_deleter()(*x);
return *this;
}
template<class D2>
value_ptr& operator=(const value_ptr<T, D2>& x) {
_ptr = x.get_deleter()(*x);
return *this;
}
//The big payoff + conversion
value_ptr& operator=(const std::unique_ptr<T, D>& x) {
_ptr = x.get_deleter()(*x);
return *this;
}
template<class D2>
value_ptr& operator=(const std::unique_ptr<T, D2>& x) {
_ptr = x.get_deleter()(*x);
return *this;
}
public:
typename std::add_lvalue_reference<element_type>::type operator*() const {
return _ptr.operator*();
}
pointer operator->() const noexcept {
return _ptr.operator->();
}
pointer get() const noexcept {
return _ptr.get();
}
deleter_type& get_deleter() noexcept {
return _ptr.get_deleter();
}
const deleter_type& get_deleter() const noexcept {
return _ptr.get_deleter();
}
explicit operator bool() const noexcept {
return _ptr.operator bool();
}
pointer release() noexcept {
return _ptr.release();
}
//The reset interface is different than std, but I prefer overloads to default params
void reset() noexcept {
_ptr.reset();
}
void reset(pointer p) noexcept {
_ptr.reset(p);
}
void swap(value_ptr& x) noexcept {
_ptr.swap(x._ptr);
}
};
}//namespace ork
namespace std {
template <class T, class D>
void swap(ork::value_ptr<T, D>& x, ork::value_ptr<T, D>& y) noexcept {
x.swap(y);
}
}//namespace std
<|endoftext|>
|
<commit_before>//@ {"targets":[{"name":"parser.hpp","type":"include"}]}
#ifndef TEMPLE_PARSER_HPP
#define TEMPLE_PARSER_HPP
#include "item.hpp"
#include "converters.hpp"
#include <clocale>
#include <stack>
namespace Temple
{
namespace
{
struct Locale
{
Locale():m_handle(newlocale(LC_ALL,"C",0))
{m_loc_old=uselocale(m_handle);}
~Locale()
{
uselocale(m_loc_old);
freelocale(m_handle);
}
locale_t m_handle;
locale_t m_loc_old;
};
#if 0
//SFINAE for detecting a map
struct has_not_member{};
struct has_member:public has_not_member{};
template<class X> struct member_test
{typedef int type;};
template<class T,typename member_test<typename T::mapped_type>::type=0>
static constexpr bool test_mapped_type(has_member)
{return 1;}
template<class T>
static constexpr bool test_mapped_type(has_not_member)
{return 0;}
template <class T>
struct IsMap
{static constexpr bool value=test_mapped_type<T>(has_member{});};
template<class T,std::enable_if_t<IsMap<T>::value,int> x=0>
void doStuff()
{
printf("This is a map\n");
}
template<class T,std::enable_if_t<!IsMap<T>::value,int> x=0>
void doStuff()
{
printf("This is not a map\n");
}
template<class T,class StorageModel,class Node,class ExceptionHandler
,std::enable_if_t< std::is_same<T,typename StorageModel::MapType> > x=0>
void append(ItemBase<StorageModel>& item,Node&& node,ExceptionHandler& eh)
{
if(!item.template value<T>().insert({std::move(node.key), std::move(node.item)}).second)
{eh.raise(Error("Double key"));}
}
template<class T,class StorageModel,class Node,class ExceptionHandler
,std::enable_if_t< std::is_same<T,typename StorageModel::ArrayType> > x=0>
void append(ItemBase<StorageModel>& item,Node&& node,ExceptionHandler& eh)
{item.template value<T>().push_back(convert<T>(node.value));}
#endif
// Array append functions
template<class T,class StorageModel,class BufferType,class ExceptionHandler>
void append(ItemBase<StorageModel>& item,const BufferType& buffer,ExceptionHandler& eh)
{
using value_type=typename TypeGet<arrayUnset(IdGet<T,StorageModel>::id),StorageModel>::type;
item.template value<T>().push_back(convert<value_type>(buffer,eh));
}
template<class StorageModel,class BufferType,class ExceptionHandler>
using AppendFunc=void (*)(ItemBase<StorageModel>& item,const BufferType& buffer,ExceptionHandler& eh);
template<class StorageModel,class BufferType,class ExceptionHandler>
auto appendFunction(Type type)
{
AppendFunc<StorageModel,BufferType,ExceptionHandler> ret;
for_type<StorageModel,Type::I8_ARRAY,2,Type::STRING_ARRAY>(type,[&ret](auto tag)
{
using T=typename decltype(tag)::type;
ret=append<T,StorageModel,BufferType,ExceptionHandler>;
});
return ret;
}
template<class ArrayType,class ItemType>
auto append(ArrayType& array,ItemType&& item)
{
auto ret=item.get();
array.push_back(std::move(item));
return ret;
}
// Item insertion (into map)
template<class MapType,class BufferType,class ItemType,class ExceptionHandler>
auto insert(MapType& map,const BufferType& key,ItemType&& item,ExceptionHandler& eh)
{
auto ret=item.get();
if(!map.emplace(typename MapType::key_type(key),std::move(item)).second)
{
eh.raise(Error("Key ",key.c_str()," already exists in the current node."));
ret=nullptr;
}
return ret;
}
}
template<class StorageModel,class BufferType,class Source,class ProgressMonitor>
ItemBase<StorageModel>* temple_load(Source& src,ProgressMonitor& monitor)
{
using MapType=typename StorageModel::template MapType< std::unique_ptr< ItemBase<StorageModel> > > ;
using CompoundArray=typename StorageModel::template ArrayType<MapType>;
enum class State:int
{
KEY,COMMENT,ESCAPE,KEY_STRING,TYPE,COMPOUND,VALUE_ARRAY_CHECK
,VALUE_ARRAY,VALUE,VALUE_STRING,ITEM_STRING
};
uintmax_t line_count=1;
uintmax_t col_count=0;
auto state_current=State::COMPOUND;
auto state_old=state_current;
Locale loc;
auto type_current=Type::COMPOUND;
BufferType key_current;
std::unique_ptr<ItemBase<StorageModel>> item_current;
AppendFunc<StorageModel,BufferType,ProgressMonitor> append_func;
ItemBase<StorageModel>* node_current;
std::stack<ItemBase<StorageModel>*> nodes;
// Do not call feof, since that function expects that the caller
// has tried to read data first. This is not compatible with API:s
// that have UB when trying to read at EOF. Using a wrapper solves
// that problem.
typename BufferType::value_type ch_in;
BufferType token_in;
while(read(src,ch_in))
{
if(ch_in=='\n')
{
++line_count;
col_count=0;
}
++col_count;
monitor.positionUpdate(line_count,col_count);
switch(state_current)
{
case State::KEY:
switch(ch_in)
{
case '#':
state_old=state_current;
state_current=State::COMMENT;
break;
case '\\':
state_old=state_current;
state_current=State::ESCAPE;
break;
case '"':
state_current=State::KEY_STRING;
break;
case ',':
key_current=token_in;
token_in.clear();
state_current=State::TYPE;
break;
case ':':
key_current=token_in;
type_current=Type::COMPOUND;
token_in.clear();
state_current=State::COMPOUND;
break;
case '}':
insert(node_current->template value<MapType>()
,key_current
,itemCreate<StorageModel>(type_current,token_in,monitor)
,monitor);
//POP
state_current=State::COMPOUND;
break;
default:
if(! (ch_in>=0 && ch_in<=' ') )
{token_in.push_back(ch_in);}
}
break;
case State::COMMENT:
switch(ch_in)
{
case '\n':
state_current=state_old;
break;
default:
break;
}
break;
case State::ESCAPE:
token_in+=ch_in;
state_current=state_old;
break;
case State::KEY_STRING:
switch(ch_in)
{
case '\\':
state_old=state_current;
state_current=State::ESCAPE;
break;
case '"':
state_current=State::KEY;
break;
default:
token_in.push_back(ch_in);
}
break;
case State::TYPE:
switch(ch_in)
{
case '#':
state_old=state_current;
state_current=State::COMMENT;
break;
case ':':
type_current=type(token_in,monitor);
token_in.clear();
state_current=type_current==Type::COMPOUND?
State::COMPOUND : State::VALUE_ARRAY_CHECK;
break;
default:
token_in.push_back(ch_in);
}
break;
case State::VALUE_ARRAY_CHECK:
switch(ch_in)
{
case '#':
state_old=state_current;
state_current=State::COMMENT;
break;
case '[':
type_current=arraySet(type_current);
item_current=itemCreate<StorageModel>(type_current);
append_func=appendFunction<StorageModel,BufferType,ProgressMonitor>(type_current);
state_current=State::VALUE_ARRAY;
break;
case '"':
state_current=State::VALUE_STRING;
break;
case ',':
state_current=State::KEY;
break;
case '}':
insert(node_current->template value<MapType>()
,key_current
,itemCreate<StorageModel>(type_current,token_in,monitor)
,monitor);
//POP
state_current=State::COMPOUND;
break;
default:
if(!(ch_in>=0 && ch_in<=' ') )
{
token_in.push_back(ch_in);
state_current=State::VALUE;
}
}
break;
case State::VALUE:
switch(ch_in)
{
case '\\':
state_old=state_current;
state_current=State::ESCAPE;
break;
case '"':
state_current=State::VALUE_STRING;
break;
case ',':
insert(node_current->template value<MapType>()
,key_current
,itemCreate<StorageModel>(type_current,token_in,monitor)
,monitor);
state_current=State::KEY;
break;
case '}':
insert(node_current->template value<MapType>()
,key_current
,itemCreate<StorageModel>(type_current,token_in,monitor)
,monitor);
//POP
state_current=State::COMPOUND;
break;
default:
if(!(ch_in>=0 && ch_in<=' '))
{token_in.push_back(ch_in);}
}
break;
case State::VALUE_STRING:
switch(ch_in)
{
case '\"':
state_current=State::VALUE;
break;
case '\\':
state_old=state_current;
state_current=State::ESCAPE;
break;
default:
token_in.push_back(ch_in);
}
break;
case State::VALUE_ARRAY:
switch(ch_in)
{
case '#':
state_old=state_current;
state_current=State::COMMENT;
break;
case '"':
state_current=State::ITEM_STRING;
break;
case '\\':
state_old=state_current;
state_current=State::ESCAPE;
break;
case ',':
append_func(*item_current.get(),token_in,monitor);
state_current=State::VALUE_ARRAY;
break;
case ']':
append_func(*item_current.get(),token_in,monitor);
insert(node_current->template value<MapType>()
,key_current,item_current,monitor);
state_current=State::KEY;
break;
default:
if(!(ch_in>=0 && ch_in<=' '))
{token_in.push_back(ch_in);}
}
break;
case State::ITEM_STRING:
switch(ch_in)
{
case '\"':
state_current=State::VALUE_ARRAY;
break;
case '\\':
state_old=state_current;
state_current=State::ESCAPE;
break;
default:
token_in.push_back(ch_in);
}
break;
case State::COMPOUND:
switch(ch_in)
{
case '#':
state_old=state_current;
state_current=State::COMMENT;
break;
case '{':
nodes.push(node_current);
if(node_current->array())
{
/* node_current=append(node_current->template value<CompoundArray>()
,Item<MapType,StorageModel>::create());*/
}
else
{
node_current=insert(node_current->template value<MapType>()
,key_current,Item<MapType,StorageModel>::create(),monitor);
}
state_current=State::KEY;
break;
case '[':
nodes.push(node_current);
if(node_current->array())
{
/* node_current=append(node_current->template value<CompoundArray>()
,Item<CompoundArray,StorageModel>::create());*/
}
else
{
node_current=insert(node_current->template value<MapType>()
,key_current,Item<CompoundArray,StorageModel>::create(),monitor);
}
state_current=State::COMPOUND;
break;
case '}':
if(node_current->array())
{
monitor.raise(Error("An array of compounds must be terminated with ']'"));
return nullptr;
}
node_current=nodes.top();
nodes.pop();
state_current=State::COMPOUND;
break;
case ']':
//Error if not array
//POP
state_current=State::COMPOUND;
break;
case ',':
//KEY or COMPOUND (depending on array)
state_current=State::COMPOUND;
break;
default:
if(!(ch_in>=0 && ch_in<=' '))
{
monitor.raise(Error("Illegal character '",ch_in,"'."));
return nullptr; //FIXME
}
}
break;
}
}
if(nodes.size()!=0)
{monitor.raise(Error("Unterminated block at EOF."));}
return node_current;
}
}
#endif
<commit_msg>All append functions implemented<commit_after>//@ {"targets":[{"name":"parser.hpp","type":"include"}]}
#ifndef TEMPLE_PARSER_HPP
#define TEMPLE_PARSER_HPP
#include "item.hpp"
#include "converters.hpp"
#include <clocale>
#include <stack>
#include <type_traits>
namespace Temple
{
namespace
{
template<class StorageModel,class BufferType,class ExceptionHandler>
using AppendFunc=void (*)(ItemBase<StorageModel>& item,const BufferType& buffer,ExceptionHandler& eh);
}
template<class ExceptionHandler>
[[noreturn]] static void raise(const Error& msg,ExceptionHandler& eh)
{
eh.raise(msg);
assert(0 && "Exception handler must not return to its caller.");
}
// Array append functions
template<class ArrayType>
static typename ArrayType::value_type& append(ArrayType& array)
{
array.emplace_back( typename ArrayType::value_type{} );
return array.back();
}
template<class T,class StorageModel,class BufferType,class ExceptionHandler>
static void append(ItemBase<StorageModel>& item,const BufferType& buffer,ExceptionHandler& eh)
{
using value_type=typename TypeGet<arrayUnset(IdGet<T,StorageModel>::id),StorageModel>::type;
item.template value<T>().push_back(convert<value_type>(buffer,eh));
}
template<class StorageModel,class BufferType,class ExceptionHandler>
static auto appendFunction(Type type)
{
AppendFunc<StorageModel,BufferType,ExceptionHandler> ret;
for_type<StorageModel,Type::I8_ARRAY,2,Type::STRING_ARRAY>(type,[&ret](auto tag)
{
using T=typename decltype(tag)::type;
ret=append<T,StorageModel,BufferType,ExceptionHandler>;
});
return ret;
}
// Item insertion (into map)
template<class MapType,class BufferType,class ItemType,class ExceptionHandler>
static auto& insert(MapType& map,const BufferType& key,ItemType&& item,ExceptionHandler& eh)
{
auto ret=item.get();
if(!map.emplace(typename MapType::key_type(key),std::move(item)).second)
{raise(Error("Key ",key.c_str()," already exists in the current node."),eh);}
return *ret;
}
namespace
{
struct Locale
{
Locale():m_handle(newlocale(LC_ALL,"C",0))
{m_loc_old=uselocale(m_handle);}
~Locale()
{
uselocale(m_loc_old);
freelocale(m_handle);
}
locale_t m_handle;
locale_t m_loc_old;
};
template<class ArrayType,class MapType>
class Node
{
public:
Node():m_container(nullptr),m_array(0){}
template<class T>
explicit Node(T& container):m_container(&container)
,m_array(std::is_same<std::remove_reference_t<T>,ArrayType>::value)
{}
template<class BufferType,class ItemType,class ExceptionHandler>
auto& insert(const BufferType& key,ItemType&& item,ExceptionHandler& eh)
{
assert(m_container);
assert(!m_array);
return Temple::insert(*(reinterpret_cast<MapType*>(m_container))
,key,std::move(item),eh);
}
auto& append()
{
assert(m_container);
assert(m_array);
return Temple::append(*(reinterpret_cast<ArrayType*>(m_container)));
}
bool array() const noexcept
{return m_array;}
template<class T>
T& container() noexcept
{return *reinterpret_cast<T*>(m_container);}
private:
void* m_container;
bool m_array;
};
}
template<class StorageModel,class BufferType,class Source,class ProgressMonitor>
ItemBase<StorageModel>* temple_load(Source& src,ProgressMonitor& monitor)
{
using MapType=typename StorageModel::template MapType< std::unique_ptr< ItemBase<StorageModel> > > ;
using CompoundArray=typename StorageModel::template ArrayType<MapType>;
enum class State:int
{
KEY,COMMENT,ESCAPE,KEY_STRING,TYPE,COMPOUND,VALUE_ARRAY_CHECK
,VALUE_ARRAY,VALUE,VALUE_STRING,ITEM_STRING
};
uintmax_t line_count=1;
uintmax_t col_count=0;
auto state_current=State::COMPOUND;
auto state_old=state_current;
Locale loc;
auto type_current=Type::COMPOUND;
BufferType key_current;
std::unique_ptr<ItemBase<StorageModel>> item_current;
AppendFunc<StorageModel,BufferType,ProgressMonitor> append_func;
Node<CompoundArray,MapType> node_current;
std::stack<decltype(node_current)> nodes;
// Do not call feof, since that function expects that the caller
// has tried to read data first. This is not compatible with API:s
// that have UB when trying to read at EOF. Using a wrapper solves
// that problem.
typename BufferType::value_type ch_in;
BufferType token_in;
while(read(src,ch_in))
{
if(ch_in=='\n')
{
++line_count;
col_count=0;
}
++col_count;
monitor.positionUpdate(line_count,col_count);
switch(state_current)
{
case State::KEY:
switch(ch_in)
{
case '#':
state_old=state_current;
state_current=State::COMMENT;
break;
case '\\':
state_old=state_current;
state_current=State::ESCAPE;
break;
case '"':
state_current=State::KEY_STRING;
break;
case ',':
key_current=token_in;
token_in.clear();
state_current=State::TYPE;
break;
case ':':
key_current=token_in;
type_current=Type::COMPOUND;
token_in.clear();
state_current=State::COMPOUND;
break;
case '}':
node_current.insert(key_current
,itemCreate<StorageModel>(type_current,token_in,monitor)
,monitor);
//POP
state_current=State::COMPOUND;
break;
default:
if(! (ch_in>=0 && ch_in<=' ') )
{token_in.push_back(ch_in);}
}
break;
case State::COMMENT:
switch(ch_in)
{
case '\n':
state_current=state_old;
break;
default:
break;
}
break;
case State::ESCAPE:
token_in+=ch_in;
state_current=state_old;
break;
case State::KEY_STRING:
switch(ch_in)
{
case '\\':
state_old=state_current;
state_current=State::ESCAPE;
break;
case '"':
state_current=State::KEY;
break;
default:
token_in.push_back(ch_in);
}
break;
case State::TYPE:
switch(ch_in)
{
case '#':
state_old=state_current;
state_current=State::COMMENT;
break;
case ':':
type_current=type(token_in,monitor);
token_in.clear();
state_current=type_current==Type::COMPOUND?
State::COMPOUND : State::VALUE_ARRAY_CHECK;
break;
default:
token_in.push_back(ch_in);
}
break;
case State::VALUE_ARRAY_CHECK:
switch(ch_in)
{
case '#':
state_old=state_current;
state_current=State::COMMENT;
break;
case '[':
type_current=arraySet(type_current);
item_current=itemCreate<StorageModel>(type_current);
append_func=appendFunction<StorageModel,BufferType,ProgressMonitor>(type_current);
state_current=State::VALUE_ARRAY;
break;
case '"':
state_current=State::VALUE_STRING;
break;
case ',':
state_current=State::KEY;
break;
case '}':
node_current.insert(key_current
,itemCreate<StorageModel>(type_current,token_in,monitor)
,monitor);
//POP
state_current=State::COMPOUND;
break;
default:
if(!(ch_in>=0 && ch_in<=' ') )
{
token_in.push_back(ch_in);
state_current=State::VALUE;
}
}
break;
case State::VALUE:
switch(ch_in)
{
case '\\':
state_old=state_current;
state_current=State::ESCAPE;
break;
case '"':
state_current=State::VALUE_STRING;
break;
case ',':
node_current.insert(key_current
,itemCreate<StorageModel>(type_current,token_in,monitor)
,monitor);
state_current=State::KEY;
break;
case '}':
node_current.insert(key_current
,itemCreate<StorageModel>(type_current,token_in,monitor)
,monitor);
//POP
state_current=State::COMPOUND;
break;
default:
if(!(ch_in>=0 && ch_in<=' '))
{token_in.push_back(ch_in);}
}
break;
case State::VALUE_STRING:
switch(ch_in)
{
case '\"':
state_current=State::VALUE;
break;
case '\\':
state_old=state_current;
state_current=State::ESCAPE;
break;
default:
token_in.push_back(ch_in);
}
break;
case State::VALUE_ARRAY:
switch(ch_in)
{
case '#':
state_old=state_current;
state_current=State::COMMENT;
break;
case '"':
state_current=State::ITEM_STRING;
break;
case '\\':
state_old=state_current;
state_current=State::ESCAPE;
break;
case ',':
append_func(*item_current.get(),token_in,monitor);
state_current=State::VALUE_ARRAY;
break;
case ']':
append_func(*item_current.get(),token_in,monitor);
node_current.insert(key_current,item_current,monitor);
state_current=State::KEY;
break;
default:
if(!(ch_in>=0 && ch_in<=' '))
{token_in.push_back(ch_in);}
}
break;
case State::ITEM_STRING:
switch(ch_in)
{
case '\"':
state_current=State::VALUE_ARRAY;
break;
case '\\':
state_old=state_current;
state_current=State::ESCAPE;
break;
default:
token_in.push_back(ch_in);
}
break;
case State::COMPOUND:
switch(ch_in)
{
case '#':
state_old=state_current;
state_current=State::COMMENT;
break;
case '{':
nodes.push(node_current);
if(node_current.array())
{node_current=decltype(node_current)(node_current.append());}
else
{
node_current=decltype(node_current)(node_current.insert(key_current
,Item<MapType,StorageModel>::create(),monitor));
}
state_current=State::KEY;
break;
case '[':
nodes.push(node_current);
if(node_current.array())
{raise(Error("An array cannot contain another array"),monitor);}
else
{
node_current=decltype(node_current)(node_current.insert(key_current
,Item<CompoundArray,StorageModel>::create(),monitor));
}
state_current=State::COMPOUND;
break;
case '}':
if(node_current.array())
{raise(Error("An array of compounds must be terminated with ']'"),monitor);}
node_current=nodes.top();
nodes.pop();
state_current=State::COMPOUND;
break;
case ']':
//Error if not array
//POP
state_current=State::COMPOUND;
break;
case ',':
//KEY or COMPOUND (depending on array)
state_current=State::COMPOUND;
break;
default:
if(!(ch_in>=0 && ch_in<=' '))
{raise(Error("Illegal character '",ch_in,"'."),monitor);}
}
break;
}
}
if(nodes.size()!=0)
{raise(Error("Unterminated block at EOF."),monitor);}
return nullptr; //FIXME
}
}
#endif
<|endoftext|>
|
<commit_before>#include "our_string.h"
using namespace std;
our_string our_string:: trim(string right_string,char c)
{
if(right_string.find(c)==-1)
{
return right_string;
}
string left_string="";
int i=right_string.find(c)+1;
left_string=right_string.substr(0,i-1);
return left_string+trim(right_string.substr(i,right_string.length()-1),c);
}
bool our_string :: is_number (string c , double & number ){
for(int i=0; i<c.length() ; i++){
if((int(c[i])>=48 && int(c[i])<=57)|| int(c[i])==46)
continue;
else return 0;
}
number=atof(c.c_str());;
return 1;
}
int our_string:: find_str (string input ,char a,int& howmany,int start)
{
howmany=0;
int x=0;
int index;
for(int i=start;i<input.length();i++)
{
if (input[i]==a)
{
howmany ++;
x++;
}
if(x==1)
{
index=i;
x++;
}
}
if (howmany==0){
return -1;
}
return index;
}
int our_string :: find_2str (string input,char a,char b,int start){
for (int i=start;i<input.length();i++){
if(input[i]==a || input[i]==b){
return i;
}
}
return -1;
}
<commit_msg> youmnaas /trim/find_2str/find_str/is_number<commit_after>#include "our_string.h"
using namespace std;
string our_string:: trim(string right_string,char c)
{
if(right_string.find(c)==-1)
{
return right_string;
}
string left_string="";
int i=right_string.find(c)+1;
left_string=right_string.substr(0,i-1);
return left_string+trim(right_string.substr(i,right_string.length()-1),c);
}
bool our_string :: is_number (string c , double & number ){
for(int i=0; i<c.length() ; i++){
if((int(c[i])>=48 && int(c[i])<=57)|| int(c[i])==46)
continue;
else return 0;
}
number=atof(c.c_str());;
return 1;
}
int our_string:: find_str (string input ,char a,int& howmany,int start)
{
howmany=0;
int x=0;
int index;
for(int i=start;i<input.length();i++)
{
if (input[i]==a)
{
howmany ++;
x++;
}
if(x==1)
{
index=i;
x++;
}
}
if (howmany==0){
return -1;
}
return index;
}
int our_string :: find_2str (string input,char a,char b,int start){
for (int i=start;i<input.length();i++){
if(input[i]==a || input[i]==b){
return i;
}
}
return -1;
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2019 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#define CAF_SUITE stream_socket
#include "caf/net/stream_socket.hpp"
#include "caf/test/dsl.hpp"
#include "host_fixture.hpp"
#include "caf/byte.hpp"
#include "caf/span.hpp"
using namespace caf;
using namespace caf::net;
namespace {
byte operator"" _b(unsigned long long x) {
return static_cast<byte>(x);
}
} // namespace
CAF_TEST_FIXTURE_SCOPE(network_socket_simple_tests, host_fixture)
CAF_TEST(invalid socket) {
stream_socket x;
CAF_CHECK_EQUAL(keepalive(x, true), sec::network_syscall_failed);
CAF_CHECK_EQUAL(nodelay(x, true), sec::network_syscall_failed);
CAF_CHECK_EQUAL(allow_sigpipe(x, true), sec::network_syscall_failed);
}
CAF_TEST_FIXTURE_SCOPE_END()
namespace {
struct fixture : host_fixture {
fixture() : rd_buf(124) {
std::tie(first, second) = unbox(make_stream_socket_pair());
CAF_REQUIRE_EQUAL(nonblocking(first, true), caf::none);
CAF_REQUIRE_EQUAL(nonblocking(second, true), caf::none);
CAF_REQUIRE_NOT_EQUAL(unbox(send_buffer_size(first)), 0u);
CAF_REQUIRE_NOT_EQUAL(unbox(send_buffer_size(second)), 0u);
}
~fixture() {
close(first);
close(second);
}
stream_socket first;
stream_socket second;
std::vector<byte> rd_buf;
};
} // namespace
CAF_TEST_FIXTURE_SCOPE(network_socket_tests, fixture)
CAF_TEST(read on empty sockets) {
CAF_CHECK_EQUAL(read(first, make_span(rd_buf)),
sec::unavailable_or_would_block);
CAF_CHECK_EQUAL(read(second, make_span(rd_buf)),
sec::unavailable_or_would_block);
}
CAF_TEST(transfer data from first to second socket) {
std::vector<byte> wr_buf{1_b, 2_b, 4_b, 8_b, 16_b, 32_b, 64_b};
CAF_MESSAGE("transfer data from first to second socket");
CAF_CHECK_EQUAL(write(first, make_span(wr_buf)), wr_buf.size());
CAF_CHECK_EQUAL(read(second, make_span(rd_buf)), wr_buf.size());
CAF_CHECK(std::equal(wr_buf.begin(), wr_buf.end(), rd_buf.begin()));
rd_buf.assign(rd_buf.size(), byte(0));
}
CAF_TEST(transfer data from second to first socket) {
std::vector<byte> wr_buf{1_b, 2_b, 4_b, 8_b, 16_b, 32_b, 64_b};
CAF_CHECK_EQUAL(write(second, make_span(wr_buf)), wr_buf.size());
CAF_CHECK_EQUAL(read(first, make_span(rd_buf)), wr_buf.size());
CAF_CHECK(std::equal(wr_buf.begin(), wr_buf.end(), rd_buf.begin()));
}
CAF_TEST(shut down first socket and observe shutdown on the second one) {
close(first);
CAF_CHECK_EQUAL(read(second, make_span(rd_buf)), sec::socket_disconnected);
first.id = invalid_socket_id;
}
CAF_TEST(transfer data using multiple buffers) {
std::vector<byte> wr_buf_1{1_b, 2_b, 4_b};
std::vector<byte> wr_buf_2{8_b, 16_b, 32_b, 64_b};
std::vector<byte> full_buf;
full_buf.insert(full_buf.end(), wr_buf_1.begin(), wr_buf_1.end());
full_buf.insert(full_buf.end(), wr_buf_2.begin(), wr_buf_2.end());
CAF_CHECK_EQUAL(write(second, {make_span(wr_buf_1), make_span(wr_buf_2)}),
full_buf.size());
CAF_CHECK_EQUAL(read(first, make_span(rd_buf)), full_buf.size());
CAF_CHECK(std::equal(full_buf.begin(), full_buf.end(), rd_buf.begin()));
}
CAF_TEST_FIXTURE_SCOPE_END()
<commit_msg>Add missing newline<commit_after>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2019 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#define CAF_SUITE stream_socket
#include "caf/net/stream_socket.hpp"
#include "caf/test/dsl.hpp"
#include "host_fixture.hpp"
#include "caf/byte.hpp"
#include "caf/span.hpp"
using namespace caf;
using namespace caf::net;
namespace {
byte operator"" _b(unsigned long long x) {
return static_cast<byte>(x);
}
} // namespace
CAF_TEST_FIXTURE_SCOPE(network_socket_simple_tests, host_fixture)
CAF_TEST(invalid socket) {
stream_socket x;
CAF_CHECK_EQUAL(keepalive(x, true), sec::network_syscall_failed);
CAF_CHECK_EQUAL(nodelay(x, true), sec::network_syscall_failed);
CAF_CHECK_EQUAL(allow_sigpipe(x, true), sec::network_syscall_failed);
}
CAF_TEST_FIXTURE_SCOPE_END()
namespace {
struct fixture : host_fixture {
fixture() : rd_buf(124) {
std::tie(first, second) = unbox(make_stream_socket_pair());
CAF_REQUIRE_EQUAL(nonblocking(first, true), caf::none);
CAF_REQUIRE_EQUAL(nonblocking(second, true), caf::none);
CAF_REQUIRE_NOT_EQUAL(unbox(send_buffer_size(first)), 0u);
CAF_REQUIRE_NOT_EQUAL(unbox(send_buffer_size(second)), 0u);
}
~fixture() {
close(first);
close(second);
}
stream_socket first;
stream_socket second;
std::vector<byte> rd_buf;
};
} // namespace
CAF_TEST_FIXTURE_SCOPE(network_socket_tests, fixture)
CAF_TEST(read on empty sockets) {
CAF_CHECK_EQUAL(read(first, make_span(rd_buf)),
sec::unavailable_or_would_block);
CAF_CHECK_EQUAL(read(second, make_span(rd_buf)),
sec::unavailable_or_would_block);
}
CAF_TEST(transfer data from first to second socket) {
std::vector<byte> wr_buf{1_b, 2_b, 4_b, 8_b, 16_b, 32_b, 64_b};
CAF_MESSAGE("transfer data from first to second socket");
CAF_CHECK_EQUAL(write(first, make_span(wr_buf)), wr_buf.size());
CAF_CHECK_EQUAL(read(second, make_span(rd_buf)), wr_buf.size());
CAF_CHECK(std::equal(wr_buf.begin(), wr_buf.end(), rd_buf.begin()));
rd_buf.assign(rd_buf.size(), byte(0));
}
CAF_TEST(transfer data from second to first socket) {
std::vector<byte> wr_buf{1_b, 2_b, 4_b, 8_b, 16_b, 32_b, 64_b};
CAF_CHECK_EQUAL(write(second, make_span(wr_buf)), wr_buf.size());
CAF_CHECK_EQUAL(read(first, make_span(rd_buf)), wr_buf.size());
CAF_CHECK(std::equal(wr_buf.begin(), wr_buf.end(), rd_buf.begin()));
}
CAF_TEST(shut down first socket and observe shutdown on the second one) {
close(first);
CAF_CHECK_EQUAL(read(second, make_span(rd_buf)), sec::socket_disconnected);
first.id = invalid_socket_id;
}
CAF_TEST(transfer data using multiple buffers) {
std::vector<byte> wr_buf_1{1_b, 2_b, 4_b};
std::vector<byte> wr_buf_2{8_b, 16_b, 32_b, 64_b};
std::vector<byte> full_buf;
full_buf.insert(full_buf.end(), wr_buf_1.begin(), wr_buf_1.end());
full_buf.insert(full_buf.end(), wr_buf_2.begin(), wr_buf_2.end());
CAF_CHECK_EQUAL(write(second, {make_span(wr_buf_1), make_span(wr_buf_2)}),
full_buf.size());
CAF_CHECK_EQUAL(read(first, make_span(rd_buf)), full_buf.size());
CAF_CHECK(std::equal(full_buf.begin(), full_buf.end(), rd_buf.begin()));
}
CAF_TEST_FIXTURE_SCOPE_END()
<|endoftext|>
|
<commit_before>/*---------------------------------------------------------------------\
| |
| _ _ _ _ __ _ |
| | | | | | \_/ | / \ | | |
| | | | | | |_| | / /\ \ | | |
| | |__ | | | | | | / ____ \ | |__ |
| |____||_| |_| |_|/ / \ \|____| |
| |
| ca-mgm library |
| |
| (C) SUSE Linux Products GmbH |
\----------------------------------------------------------------------/
File: ExtendedKeyUsageExt.cpp
Author: <Michael Calmer> <mc@suse.de>
Maintainer: <Michael Calmer> <mc@suse.de>
Purpose:
/-*/
#include <limal/ca-mgm/BitExtensions.hpp>
#include <limal/ca-mgm/CA.hpp>
#include <limal/ValueRegExCheck.hpp>
#include <limal/Exception.hpp>
#include <blocxx/Format.hpp>
#include <blocxx/COWIntrusiveCountableBase.hpp>
#include "Utils.hpp"
namespace LIMAL_NAMESPACE
{
namespace CA_MGM_NAMESPACE
{
using namespace limal;
using namespace blocxx;
class ExtendedKeyUsageExtImpl : public blocxx::COWIntrusiveCountableBase
{
public:
ExtendedKeyUsageExtImpl()
: usage(StringList())
{}
ExtendedKeyUsageExtImpl(const ExtendedKeyUsageExtImpl& impl)
: COWIntrusiveCountableBase(impl)
, usage(impl.usage)
{}
~ExtendedKeyUsageExtImpl() {}
ExtendedKeyUsageExtImpl* clone() const
{
return new ExtendedKeyUsageExtImpl(*this);
}
StringList usage;
};
ExtendedKeyUsageExt::ExtendedKeyUsageExt()
: ExtensionBase()
, m_impl(new ExtendedKeyUsageExtImpl())
{}
ExtendedKeyUsageExt::ExtendedKeyUsageExt(CAConfig* caConfig, Type type)
: ExtensionBase()
, m_impl(new ExtendedKeyUsageExtImpl())
{
LOGIT_DEBUG("Parse ExtendedKeyUsage");
// These types are not supported by this object
if(type == E_CRL)
{
LOGIT_ERROR("wrong type" << type);
BLOCXX_THROW(limal::ValueException,
Format(__("Wrong type: %1."), type).c_str());
}
bool p = caConfig->exists(type2Section(type, true), "extendedKeyUsage");
if(p)
{
String ct = caConfig->getValue(type2Section(type, true),
"extendedKeyUsage");
StringArray sp = PerlRegEx("\\s*,\\s*").split(ct);
StringArray::const_iterator it = sp.begin();
if(sp[0].equalsIgnoreCase("critical"))
{
setCritical(true);
++it; // ignore critical for further checks
}
for(; it != sp.end(); ++it)
{
if(checkValue(*it))
{
m_impl->usage.push_back(*it);
}
else
LOGIT_INFO("Unknown ExtendedKeyUsage option: " << (*it));
}
}
setPresent(p);
}
ExtendedKeyUsageExt::ExtendedKeyUsageExt(const StringList& extKeyUsages)
: ExtensionBase()
, m_impl(new ExtendedKeyUsageExtImpl())
{
StringList::const_iterator it = extKeyUsages.begin();
for(; it != extKeyUsages.end(); ++it)
{
if(checkValue(*it))
{
m_impl->usage.push_back(*it);
}
else
{
LOGIT_INFO("Unknown ExtendedKeyUsage option: " << (*it));
BLOCXX_THROW(limal::ValueException,
Format(__("Invalid ExtendedKeyUsage option %1."),
*it).c_str());
}
}
if(m_impl->usage.empty())
{
BLOCXX_THROW(limal::ValueException,
__("Invalid ExtendedKeyUsageExt."));
}
setPresent(true);
}
ExtendedKeyUsageExt::ExtendedKeyUsageExt(const ExtendedKeyUsageExt& extension)
: ExtensionBase(extension), m_impl(extension.m_impl)
{}
ExtendedKeyUsageExt::~ExtendedKeyUsageExt()
{}
ExtendedKeyUsageExt&
ExtendedKeyUsageExt::operator=(const ExtendedKeyUsageExt& extension)
{
if(this == &extension) return *this;
ExtensionBase::operator=(extension);
m_impl = extension.m_impl;
return *this;
}
void
ExtendedKeyUsageExt::setExtendedKeyUsage(const StringList& usageList)
{
StringList::const_iterator it = usageList.begin();
m_impl->usage.clear();
for(; it != usageList.end(); ++it)
{
if(checkValue(*it))
{
m_impl->usage.push_back(*it);
}
else
{
LOGIT_INFO("Unknown ExtendedKeyUsage option: " << (*it));
BLOCXX_THROW(limal::ValueException,
Format(__("Invalid ExtendedKeyUsage option %1."),
*it).c_str());
}
}
if(m_impl->usage.empty())
{
BLOCXX_THROW(limal::ValueException,
__("Invalid ExtendedKeyUsageExt."));
}
setPresent(true);
}
StringList
ExtendedKeyUsageExt::getExtendedKeyUsage() const
{
if(!isPresent())
{
BLOCXX_THROW(limal::RuntimeException,
__("ExtendedKeyUsageExt is not present."));
}
return m_impl->usage;
}
bool
ExtendedKeyUsageExt::isEnabledFor(const String& extKeyUsage) const
{
// if ! isPresent() ... throw exceptions?
if(!isPresent() || m_impl->usage.empty()) return false;
StringList::const_iterator it = m_impl->usage.begin();
for(;it != m_impl->usage.end(); ++it)
{
if(extKeyUsage.equalsIgnoreCase(*it))
{
return true;
}
}
return false;
}
void
ExtendedKeyUsageExt::commit2Config(CA& ca, Type type) const
{
if(!valid())
{
LOGIT_ERROR("invalid ExtendedKeyUsageExt object");
BLOCXX_THROW(limal::ValueException,
__("Invalid ExtendedKeyUsageExt object."));
}
// This extension is not supported by type CRL
if(type == E_CRL)
{
LOGIT_ERROR("wrong type" << type);
BLOCXX_THROW(limal::ValueException,
Format(__("Wrong type: %1."), type).c_str());
}
if(isPresent())
{
String extendedKeyUsageString;
if(isCritical()) extendedKeyUsageString += "critical,";
StringList::const_iterator it = m_impl->usage.begin();
for(; it != m_impl->usage.end(); ++it)
{
extendedKeyUsageString += (*it)+",";
}
ca.getConfig()->setValue(type2Section(type, true),
"extendedKeyUsage",
extendedKeyUsageString.erase(extendedKeyUsageString.length()-1));
}
else
{
ca.getConfig()->deleteValue(type2Section(type, true), "extendedKeyUsage");
}
}
bool
ExtendedKeyUsageExt::valid() const
{
if(!isPresent()) return true;
if(m_impl->usage.empty())
{
return false;
}
StringList::const_iterator it = m_impl->usage.begin();
for(;it != m_impl->usage.end(); it++)
{
if(!checkValue(*it))
{
return false;
}
}
return true;
}
blocxx::StringArray
ExtendedKeyUsageExt::verify() const
{
blocxx::StringArray result;
if(!isPresent()) return result;
if(m_impl->usage.empty())
{
result.append(String("invalid ExtendedKeyUsageExt."));
}
StringList::const_iterator it = m_impl->usage.begin();
for(;it != m_impl->usage.end(); it++)
{
if(!checkValue(*it))
{
result.append(Format("invalid additionalOID(%1)", *it).toString());
}
}
LOGIT_DEBUG_STRINGARRAY("ExtendedKeyUsageExt::verify()", result);
return result;
}
blocxx::StringArray
ExtendedKeyUsageExt::dump() const
{
StringArray result;
result.append("ExtendedKeyUsageExt::dump()");
result.appendArray(ExtensionBase::dump());
if(!isPresent()) return result;
StringList::const_iterator it = m_impl->usage.begin();
for(; it != m_impl->usage.end(); ++it)
{
result.append("Extended KeyUsage = " + (*it));
}
return result;
}
bool
ExtendedKeyUsageExt::checkValue(const String& value) const
{
StringList validValues;
validValues.push_back("serverAuth");
validValues.push_back("clientAuth");
validValues.push_back("codeSigning");
validValues.push_back("emailProtection");
validValues.push_back("timeStamping");
validValues.push_back("msCodeInd");
validValues.push_back("msCodeCom");
validValues.push_back("msCTLSign");
validValues.push_back("msSGC");
validValues.push_back("msEFS");
validValues.push_back("nsSGC");
StringList::const_iterator it = validValues.begin();
for(; it != validValues.end(); ++it)
{
if(value.equalsIgnoreCase(*it))
{
return true;
}
}
return initOIDCheck().isValid(value);
}
}
}
<commit_msg>better value check for ExtendedKeyUsage types<commit_after>/*---------------------------------------------------------------------\
| |
| _ _ _ _ __ _ |
| | | | | | \_/ | / \ | | |
| | | | | | |_| | / /\ \ | | |
| | |__ | | | | | | / ____ \ | |__ |
| |____||_| |_| |_|/ / \ \|____| |
| |
| ca-mgm library |
| |
| (C) SUSE Linux Products GmbH |
\----------------------------------------------------------------------/
File: ExtendedKeyUsageExt.cpp
Author: <Michael Calmer> <mc@suse.de>
Maintainer: <Michael Calmer> <mc@suse.de>
Purpose:
/-*/
#include <limal/ca-mgm/BitExtensions.hpp>
#include <limal/ca-mgm/CA.hpp>
#include <limal/ValueRegExCheck.hpp>
#include <limal/Exception.hpp>
#include <blocxx/Format.hpp>
#include <blocxx/COWIntrusiveCountableBase.hpp>
#include "Utils.hpp"
namespace LIMAL_NAMESPACE
{
namespace CA_MGM_NAMESPACE
{
using namespace limal;
using namespace blocxx;
class ExtendedKeyUsageExtImpl : public blocxx::COWIntrusiveCountableBase
{
public:
ExtendedKeyUsageExtImpl()
: usage(StringList())
{}
ExtendedKeyUsageExtImpl(const ExtendedKeyUsageExtImpl& impl)
: COWIntrusiveCountableBase(impl)
, usage(impl.usage)
{}
~ExtendedKeyUsageExtImpl() {}
ExtendedKeyUsageExtImpl* clone() const
{
return new ExtendedKeyUsageExtImpl(*this);
}
StringList usage;
};
ExtendedKeyUsageExt::ExtendedKeyUsageExt()
: ExtensionBase()
, m_impl(new ExtendedKeyUsageExtImpl())
{}
ExtendedKeyUsageExt::ExtendedKeyUsageExt(CAConfig* caConfig, Type type)
: ExtensionBase()
, m_impl(new ExtendedKeyUsageExtImpl())
{
LOGIT_DEBUG("Parse ExtendedKeyUsage");
// These types are not supported by this object
if(type == E_CRL)
{
LOGIT_ERROR("wrong type" << type);
BLOCXX_THROW(limal::ValueException,
Format(__("Wrong type: %1."), type).c_str());
}
bool p = caConfig->exists(type2Section(type, true), "extendedKeyUsage");
if(p)
{
String ct = caConfig->getValue(type2Section(type, true),
"extendedKeyUsage");
StringArray sp = PerlRegEx("\\s*,\\s*").split(ct);
StringArray::const_iterator it = sp.begin();
if(sp[0].equalsIgnoreCase("critical"))
{
setCritical(true);
++it; // ignore critical for further checks
}
for(; it != sp.end(); ++it)
{
if(checkValue(*it))
{
m_impl->usage.push_back(*it);
}
else
LOGIT_INFO("Unknown ExtendedKeyUsage option: " << (*it));
}
}
setPresent(p);
}
ExtendedKeyUsageExt::ExtendedKeyUsageExt(const StringList& extKeyUsages)
: ExtensionBase()
, m_impl(new ExtendedKeyUsageExtImpl())
{
StringList::const_iterator it = extKeyUsages.begin();
for(; it != extKeyUsages.end(); ++it)
{
if(checkValue(*it))
{
m_impl->usage.push_back(*it);
}
else
{
LOGIT_INFO("Unknown ExtendedKeyUsage option: " << (*it));
BLOCXX_THROW(limal::ValueException,
Format(__("Invalid ExtendedKeyUsage option %1."),
*it).c_str());
}
}
if(m_impl->usage.empty())
{
BLOCXX_THROW(limal::ValueException,
__("Invalid ExtendedKeyUsageExt."));
}
setPresent(true);
}
ExtendedKeyUsageExt::ExtendedKeyUsageExt(const ExtendedKeyUsageExt& extension)
: ExtensionBase(extension), m_impl(extension.m_impl)
{}
ExtendedKeyUsageExt::~ExtendedKeyUsageExt()
{}
ExtendedKeyUsageExt&
ExtendedKeyUsageExt::operator=(const ExtendedKeyUsageExt& extension)
{
if(this == &extension) return *this;
ExtensionBase::operator=(extension);
m_impl = extension.m_impl;
return *this;
}
void
ExtendedKeyUsageExt::setExtendedKeyUsage(const StringList& usageList)
{
StringList::const_iterator it = usageList.begin();
m_impl->usage.clear();
for(; it != usageList.end(); ++it)
{
if(checkValue(*it))
{
m_impl->usage.push_back(*it);
}
else
{
LOGIT_INFO("Unknown ExtendedKeyUsage option: " << (*it));
BLOCXX_THROW(limal::ValueException,
Format(__("Invalid ExtendedKeyUsage option %1."),
*it).c_str());
}
}
if(m_impl->usage.empty())
{
BLOCXX_THROW(limal::ValueException,
__("Invalid ExtendedKeyUsageExt."));
}
setPresent(true);
}
StringList
ExtendedKeyUsageExt::getExtendedKeyUsage() const
{
if(!isPresent())
{
BLOCXX_THROW(limal::RuntimeException,
__("ExtendedKeyUsageExt is not present."));
}
return m_impl->usage;
}
bool
ExtendedKeyUsageExt::isEnabledFor(const String& extKeyUsage) const
{
// if ! isPresent() ... throw exceptions?
if(!isPresent() || m_impl->usage.empty()) return false;
StringList::const_iterator it = m_impl->usage.begin();
for(;it != m_impl->usage.end(); ++it)
{
if(extKeyUsage.equalsIgnoreCase(*it))
{
return true;
}
}
return false;
}
void
ExtendedKeyUsageExt::commit2Config(CA& ca, Type type) const
{
if(!valid())
{
LOGIT_ERROR("invalid ExtendedKeyUsageExt object");
BLOCXX_THROW(limal::ValueException,
__("Invalid ExtendedKeyUsageExt object."));
}
// This extension is not supported by type CRL
if(type == E_CRL)
{
LOGIT_ERROR("wrong type" << type);
BLOCXX_THROW(limal::ValueException,
Format(__("Wrong type: %1."), type).c_str());
}
if(isPresent())
{
String extendedKeyUsageString;
if(isCritical()) extendedKeyUsageString += "critical,";
StringList::const_iterator it = m_impl->usage.begin();
for(; it != m_impl->usage.end(); ++it)
{
extendedKeyUsageString += (*it)+",";
}
ca.getConfig()->setValue(type2Section(type, true),
"extendedKeyUsage",
extendedKeyUsageString.erase(extendedKeyUsageString.length()-1));
}
else
{
ca.getConfig()->deleteValue(type2Section(type, true), "extendedKeyUsage");
}
}
bool
ExtendedKeyUsageExt::valid() const
{
if(!isPresent()) return true;
if(m_impl->usage.empty())
{
return false;
}
StringList::const_iterator it = m_impl->usage.begin();
for(;it != m_impl->usage.end(); it++)
{
if(!checkValue(*it))
{
return false;
}
}
return true;
}
blocxx::StringArray
ExtendedKeyUsageExt::verify() const
{
blocxx::StringArray result;
if(!isPresent()) return result;
if(m_impl->usage.empty())
{
result.append(String("invalid ExtendedKeyUsageExt."));
}
StringList::const_iterator it = m_impl->usage.begin();
for(;it != m_impl->usage.end(); it++)
{
if(!checkValue(*it))
{
result.append(Format("invalid additionalOID(%1)", *it).toString());
}
}
LOGIT_DEBUG_STRINGARRAY("ExtendedKeyUsageExt::verify()", result);
return result;
}
blocxx::StringArray
ExtendedKeyUsageExt::dump() const
{
StringArray result;
result.append("ExtendedKeyUsageExt::dump()");
result.appendArray(ExtensionBase::dump());
if(!isPresent()) return result;
StringList::const_iterator it = m_impl->usage.begin();
for(; it != m_impl->usage.end(); ++it)
{
result.append("Extended KeyUsage = " + (*it));
}
return result;
}
bool
ExtendedKeyUsageExt::checkValue(const String& value) const
{
if(OBJ_sn2nid(value.c_str()) == NID_undef)
{
return initOIDCheck().isValid(value);
}
else
{
return true;
}
}
}
}
<|endoftext|>
|
<commit_before>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#include<fstream>
#include<iostream>
#include<sstream>
#include"ork/glm.hpp"
#include ORK_FILE_INCLUDE
#include"ork/geometry.hpp"
#include"ork/text_io.hpp"
#if ORK_USE_JSON
#if ORK_MSC
#pragma warning(push)
#pragma warning(disable:4668) //Json undefined macro
#endif
#include"json/json.h"
#if ORK_MSC
#pragma warning(pop)
#endif
#endif
#if ORK_USE_PUGI
#include"pugixml.hpp"
#endif
#if ORK_USE_JSON
#if ORK_MSC
#pragma warning(push)
#pragma warning(disable:4668) //Json undefined macro
#endif
#include"json/json.h"
#if ORK_MSC
#pragma warning(pop)
#endif
#endif
namespace ork {
namespace json {
#if ORK_USE_JSON
void export_file(const string&path_to_file, const Json::Value&root) {
file::ensure_directory(path_to_file);
ORK_FILE_WRITE(path_to_file);
Json::StreamWriterBuilder write_builder;
write_builder["indentation"] = "\t";
bstring document = Json::writeString(write_builder, root);
fout << document;
}
void export_file(const string&path_to_file, const exportable&object) {
Json::Value root;
object.export_json(root);
export_file(path_to_file, root);
}
void load_and_parse(i_stream&fin, Json::Value&root) {
fin >> root;
}
Json::Value load_and_parse(i_stream&fin) {
Json::Value root;
fin >> root;
return std::move(root);
}
#endif//ORK_USE_JSON
}//namespace json
namespace xml {
#if ORK_USE_PUGI
void export_file(const string&filename, const exportable&object, const string&root_node_name) {
void export_file(const string&path_to_file, const exportable&object, const string&root_node_name) {
pugi::xml_document doc;
pugi::xml_node root_node = doc.append_child(root_node_name.c_str());
object.export_xml(root_node);
file::ensure_directory(path_to_file);
ORK_FILE_WRITE(path_to_file);
doc.save(fout);
}
void load_and_parse(i_stream&fin, pugi::xml_document&xml) {
pugi::xml_parse_result result = xml.load(fin);
if(!result) {
ORK_THROW(ORK("XML parse error") \
<< ORK("\n -- Error: ") << result.description() \
<< ORK("\n -- Offset: ") << result.offset)//<< ORK(" at [") << (source + result.offset) << ORK("]"))
}
else {
ORK_LOG(ork::severity_level::trace) << ORK("XML parse success");
}
}
#endif//ORK_USE_PUGI
}//namespace xml
#if ORK_USE_GLM
struct vector::impl {
public:
glm::dvec3 data;
public:
impl() : data{} {}
explicit impl(const glm::dvec3&vec) : data{vec} {}
impl(const double x, const double y, const double z) : data{x, y, z} {}
};
void vector::deleter::operator()(const vector::impl*ptr) {
delete ptr;
}
vector::impl vector::deleter::operator()(const vector::impl&val) {
return impl(val);
}
vector::vector() : _pimpl{new impl()} {}
vector::vector(const glm::dvec3&vec) : _pimpl{new impl(vec)} {}
vector::vector(const GLM::dunit3&vec) : _pimpl{new impl(vec.get())} {}
vector::vector(const double x, const double y, const double z) : _pimpl{new impl(x, y, z)} {}
vector&vector::operator=(const glm::dvec3&vec) {
_pimpl->data = vec;
return *this;
}
vector&vector::operator=(const GLM::dunit3&vec) {
_pimpl->data = vec.get();
return *this;
}
double&vector::x() {
return _pimpl->data.x;
}
const double&vector::x()const {
return _pimpl->data.x;
}
double&vector::y() {
return _pimpl->data.y;
}
const double&vector::y()const {
return _pimpl->data.y;
}
double&vector::z() {
return _pimpl->data.z;
}
const double&vector::z()const {
return _pimpl->data.z;
}
glm::dvec3&vector::get() {
return _pimpl->data;
}
const glm::dvec3&vector::get()const {
return _pimpl->data;
}
bool vector::operator == (const vector &other) const {
return GLM::equal(_pimpl->data, other._pimpl->data);
}
bool vector::operator != (const vector &other) const {
return !(*this == other);
}
string vector::as_string() const {
string_stream stream;
stream << ORK("(") << to_dimension(_pimpl->data.x)
<< ORK(", ") << to_dimension(_pimpl->data.y)
<< ORK(", ") << to_dimension(_pimpl->data.z) << ORK(")");
return stream.str();
}
#if ORK_USE_PUGI
vector::vector(pugi::xml_node &node) {
_pimpl->data.x = node.attribute(ORK("x")).as_double();
_pimpl->data.y = node.attribute(ORK("y")).as_double();
_pimpl->data.z = node.attribute(ORK("z")).as_double();
}
void vector::export_xml(pugi::xml_node &node) const {
node.append_attribute(ORK("x")).set_value(to_dimension(_pimpl->data.x).c_str());
node.append_attribute(ORK("y")).set_value(to_dimension(_pimpl->data.y).c_str());
node.append_attribute(ORK("z")).set_value(to_dimension(_pimpl->data.z).c_str());
}
#endif
o_stream &operator << (o_stream&stream, const ork::vector &vec) {
return stream << vec.as_string();
}
#endif//ORK_USE_GLM
}//namespace ork
<commit_msg>Added include for yaml and disabled warnings<commit_after>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#include<fstream>
#include<iostream>
#include<sstream>
#include"ork/glm.hpp"
#include ORK_FILE_INCLUDE
#include"ork/geometry.hpp"
#include"ork/text_io.hpp"
#if ORK_USE_JSON
#if ORK_MSC
#pragma warning(push)
#pragma warning(disable:4668) //Json undefined macro
#endif
#include"json/json.h"
#if ORK_MSC
#pragma warning(pop)
#endif
#endif
#if ORK_USE_PUGI
#include"pugixml.hpp"
#endif
#if ORK_USE_YAML
#if ORK_MSC
#pragma warning(push)
#pragma warning(disable:4127) //conditional expression is constant
#pragma warning(disable:4365) //signed/unsigned mismatch
#pragma warning(disable:4571) //catch(...) semantics changed
#pragma warning(disable:4625) //copy constructor was implicitly deleted
#pragma warning(disable:4626) //copy assigment was implicitly deleted
#pragma warning(disable:4668) //undefined preprocessor macro
#pragma warning(disable:5026) //move constructor implicitly deleted
#pragma warning(disable:5027) //move assignment implicitly deleted
#endif
#include"yaml-cpp/yaml.h"
#if ORK_MSC
#pragma warning(pop)
#endif
#endif
namespace ork {
namespace json {
#if ORK_USE_JSON
void export_file(const string&path_to_file, const Json::Value&root) {
file::ensure_directory(path_to_file);
ORK_FILE_WRITE(path_to_file);
Json::StreamWriterBuilder write_builder;
write_builder["indentation"] = "\t";
bstring document = Json::writeString(write_builder, root);
fout << document;
}
void export_file(const string&path_to_file, const exportable&object) {
Json::Value root;
object.export_json(root);
export_file(path_to_file, root);
}
void load_and_parse(i_stream&fin, Json::Value&root) {
fin >> root;
}
Json::Value load_and_parse(i_stream&fin) {
Json::Value root;
fin >> root;
return std::move(root);
}
#endif//ORK_USE_JSON
}//namespace json
namespace xml {
#if ORK_USE_PUGI
void export_file(const string&filename, const exportable&object, const string&root_node_name) {
void export_file(const string&path_to_file, const exportable&object, const string&root_node_name) {
pugi::xml_document doc;
pugi::xml_node root_node = doc.append_child(root_node_name.c_str());
object.export_xml(root_node);
file::ensure_directory(path_to_file);
ORK_FILE_WRITE(path_to_file);
doc.save(fout);
}
void load_and_parse(i_stream&fin, pugi::xml_document&xml) {
pugi::xml_parse_result result = xml.load(fin);
if(!result) {
ORK_THROW(ORK("XML parse error") \
<< ORK("\n -- Error: ") << result.description() \
<< ORK("\n -- Offset: ") << result.offset)//<< ORK(" at [") << (source + result.offset) << ORK("]"))
}
else {
ORK_LOG(ork::severity_level::trace) << ORK("XML parse success");
}
}
#endif//ORK_USE_PUGI
}//namespace xml
#if ORK_USE_GLM
struct vector::impl {
public:
glm::dvec3 data;
public:
impl() : data{} {}
explicit impl(const glm::dvec3&vec) : data{vec} {}
impl(const double x, const double y, const double z) : data{x, y, z} {}
};
void vector::deleter::operator()(const vector::impl*ptr) {
delete ptr;
}
vector::impl vector::deleter::operator()(const vector::impl&val) {
return impl(val);
}
vector::vector() : _pimpl{new impl()} {}
vector::vector(const glm::dvec3&vec) : _pimpl{new impl(vec)} {}
vector::vector(const GLM::dunit3&vec) : _pimpl{new impl(vec.get())} {}
vector::vector(const double x, const double y, const double z) : _pimpl{new impl(x, y, z)} {}
vector&vector::operator=(const glm::dvec3&vec) {
_pimpl->data = vec;
return *this;
}
vector&vector::operator=(const GLM::dunit3&vec) {
_pimpl->data = vec.get();
return *this;
}
double&vector::x() {
return _pimpl->data.x;
}
const double&vector::x()const {
return _pimpl->data.x;
}
double&vector::y() {
return _pimpl->data.y;
}
const double&vector::y()const {
return _pimpl->data.y;
}
double&vector::z() {
return _pimpl->data.z;
}
const double&vector::z()const {
return _pimpl->data.z;
}
glm::dvec3&vector::get() {
return _pimpl->data;
}
const glm::dvec3&vector::get()const {
return _pimpl->data;
}
bool vector::operator == (const vector &other) const {
return GLM::equal(_pimpl->data, other._pimpl->data);
}
bool vector::operator != (const vector &other) const {
return !(*this == other);
}
string vector::as_string() const {
string_stream stream;
stream << ORK("(") << to_dimension(_pimpl->data.x)
<< ORK(", ") << to_dimension(_pimpl->data.y)
<< ORK(", ") << to_dimension(_pimpl->data.z) << ORK(")");
return stream.str();
}
#if ORK_USE_PUGI
vector::vector(pugi::xml_node &node) {
_pimpl->data.x = node.attribute(ORK("x")).as_double();
_pimpl->data.y = node.attribute(ORK("y")).as_double();
_pimpl->data.z = node.attribute(ORK("z")).as_double();
}
void vector::export_xml(pugi::xml_node &node) const {
node.append_attribute(ORK("x")).set_value(to_dimension(_pimpl->data.x).c_str());
node.append_attribute(ORK("y")).set_value(to_dimension(_pimpl->data.y).c_str());
node.append_attribute(ORK("z")).set_value(to_dimension(_pimpl->data.z).c_str());
}
#endif
o_stream &operator << (o_stream&stream, const ork::vector &vec) {
return stream << vec.as_string();
}
#endif//ORK_USE_GLM
}//namespace ork
<|endoftext|>
|
<commit_before>/*
** Copyright (C) 2012 Aldebaran Robotics
*/
#include <event2/event.h>
#include <event2/bufferevent.h>
#include <event2/thread.h>
#include <boost/thread.hpp>
#include <qi/log.hpp>
#include <qi/application.hpp>
#include <qimessaging/event_loop.hpp>
#include "src/event_loop_p.hpp"
namespace qi {
EventLoopPrivate::EventLoopPrivate()
: _destroyMe(false)
, _running(false)
, _threaded(false)
{
static bool libevent_init = false;
#ifdef _WIN32
// libevent does not call WSAStartup
WSADATA WSAData;
// TODO: handle return code
::WSAStartup(MAKEWORD(1, 0), &WSAData);
#endif
if (!libevent_init)
{
#ifdef EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED
evthread_use_windows_threads();
#endif
#ifdef EVTHREAD_USE_PTHREADS_IMPLEMENTED
evthread_use_pthreads();
#endif
libevent_init = !libevent_init;
}
if (!(_base = event_base_new()))
return;
}
void EventLoopPrivate::start()
{
if (_running || _threaded)
return;
_threaded = true;
_thd = boost::thread(&EventLoopPrivate::run, this);
while (!_running)
qi::os::msleep(0);
}
EventLoopPrivate::~EventLoopPrivate()
{
if (_running && boost::this_thread::get_id() != _id)
qiLogError("Destroying EventLoopPrivate from itself while running");
stop();
join();
#ifdef _WIN32
// TODO handle return code
::WSACleanup();
#endif
}
void EventLoopPrivate::destroy(bool join)
{
bool needJoin;
bool needDelete;
{
boost::recursive_mutex::scoped_lock sl(_mutex);
needJoin = join && _running && (boost::this_thread::get_id() != _id);
needDelete = needJoin || !_running;
_destroyMe = !needDelete;
}
stop(); // Deadlock if called within the scoped_lock
if (needJoin)
this->join();
if (needDelete)
delete this;
}
void EventLoopPrivate::run()
{
qiLogDebug("qi.EventLoop") << this << "run starting";
_running = true;
_id = boost::this_thread::get_id();
// stop will set _base to 0 to delect usage attempts after stop
// so use a local copy.
event_base* base = _base;
// libevent needs a dummy op to perform otherwise dispatch exits immediately
struct bufferevent *bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_THREADSAFE);
//bufferevent_setcb(bev, NULL, NULL, ::qi::errorcb, this);
bufferevent_enable(bev, EV_READ|EV_WRITE);
event_base_dispatch(base);
qiLogDebug("qi.EventLoop") << this << "run ending";
//bufferevent_free(bev);
event_base_free(base);
{
boost::recursive_mutex::scoped_lock sl(_mutex);
_running = false;
if (_destroyMe)
delete this;
}
}
bool EventLoopPrivate::isInEventLoopThread()
{
return boost::this_thread::get_id() == _id;
}
void EventLoopPrivate::stop()
{
event_base* base = 0;
{ // Ensure no multipe calls are made.
boost::recursive_mutex::scoped_lock sl(_mutex);
if (_base && _running)
{
base = _base;
_base = 0;
}
}
if (base)
if (event_base_loopexit(base, NULL) != 0)
qiLogError("networkThread") << "Can't stop the EventLoopPrivate";
}
void EventLoopPrivate::join()
{
if (_base)
qiLogError("EventLoop") << "join() called before stop()";
if (boost::this_thread::get_id() == _id)
return;
if (_threaded)
_thd.join();
else
while (_running)
qi::os::msleep(0);
}
static void async_call(evutil_socket_t,
short what,
void *context)
{
EventLoop::AsyncCallHandle* handle = (EventLoop::AsyncCallHandle*)context;
if (!handle->_p->cancelled)
handle->_p->callback();
event_del(handle->_p->ev);
event_free(handle->_p->ev);
delete handle;
}
EventLoop::AsyncCallHandle EventLoopPrivate::asyncCall(uint64_t usDelay, boost::function<void ()> cb)
{
EventLoop::AsyncCallHandle res;
struct timeval period;
period.tv_sec = usDelay / 1000000ULL;
period.tv_usec = usDelay % 1000000ULL;
struct event *ev = event_new(_base, -1, 0, async_call,
new EventLoop::AsyncCallHandle(res));
// Order is important.
res._p->ev = ev;
res._p->cancelled = false;
res._p->callback = cb;
event_add(ev, &period);
return res;
}
// Basic pimpl bouncers.
EventLoop::AsyncCallHandle::AsyncCallHandle()
{
_p = boost::shared_ptr<AsyncCallHandlePrivate>(new AsyncCallHandlePrivate());
}
EventLoop::AsyncCallHandle::~AsyncCallHandle()
{
}
void EventLoop::AsyncCallHandle::cancel()
{
_p->cancel();
}
EventLoop::EventLoop()
{
_p = new EventLoopPrivate();
}
EventLoop::~EventLoop()
{
_p->destroy(false);
_p = 0;
}
bool EventLoop::isInEventLoopThread()
{
return _p->isInEventLoopThread();
}
void EventLoop::join()
{
_p->join();
}
void EventLoop::start()
{
_p->start();
}
void EventLoop::stop()
{
_p->stop();
}
void EventLoop::run()
{
_p->run();
}
EventLoop::AsyncCallHandle
EventLoop::asyncCall(
uint64_t usDelay,
boost::function<void ()> callback)
{
return _p->asyncCall(usDelay, callback);
}
static void eventloop_stop(EventLoop* ctx)
{
ctx->stop();
ctx->join();
delete ctx;
}
static EventLoop* _get(EventLoop* &ctx)
{
if (!ctx)
{
if (! qi::Application::initialized())
{
qiLogError("EventLoop") << "EventLoop created before qi::Application()";
}
ctx = new EventLoop();
ctx->start();
Application::atExit(boost::bind(&eventloop_stop, ctx));
}
return ctx;
}
static EventLoop* _netEventLoop = 0;
static EventLoop* _objEventLoop = 0;
EventLoop* getDefaultNetworkEventLoop()
{
return _get(_netEventLoop);
}
EventLoop* getDefaultObjectEventLoop()
{
return _get(_objEventLoop);
}
}
<commit_msg>event_loop: free the bufferevent<commit_after>/*
** Copyright (C) 2012 Aldebaran Robotics
*/
#include <event2/event.h>
#include <event2/bufferevent.h>
#include <event2/thread.h>
#include <boost/thread.hpp>
#include <qi/log.hpp>
#include <qi/application.hpp>
#include <qimessaging/event_loop.hpp>
#include "src/event_loop_p.hpp"
namespace qi {
EventLoopPrivate::EventLoopPrivate()
: _destroyMe(false)
, _running(false)
, _threaded(false)
{
static bool libevent_init = false;
#ifdef _WIN32
// libevent does not call WSAStartup
WSADATA WSAData;
// TODO: handle return code
::WSAStartup(MAKEWORD(1, 0), &WSAData);
#endif
if (!libevent_init)
{
#ifdef EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED
evthread_use_windows_threads();
#endif
#ifdef EVTHREAD_USE_PTHREADS_IMPLEMENTED
evthread_use_pthreads();
#endif
libevent_init = !libevent_init;
}
if (!(_base = event_base_new()))
return;
}
void EventLoopPrivate::start()
{
if (_running || _threaded)
return;
_threaded = true;
_thd = boost::thread(&EventLoopPrivate::run, this);
while (!_running)
qi::os::msleep(0);
}
EventLoopPrivate::~EventLoopPrivate()
{
if (_running && boost::this_thread::get_id() != _id)
qiLogError("Destroying EventLoopPrivate from itself while running");
stop();
join();
#ifdef _WIN32
// TODO handle return code
::WSACleanup();
#endif
}
void EventLoopPrivate::destroy(bool join)
{
bool needJoin;
bool needDelete;
{
boost::recursive_mutex::scoped_lock sl(_mutex);
needJoin = join && _running && (boost::this_thread::get_id() != _id);
needDelete = needJoin || !_running;
_destroyMe = !needDelete;
}
stop(); // Deadlock if called within the scoped_lock
if (needJoin)
this->join();
if (needDelete)
delete this;
}
void EventLoopPrivate::run()
{
qiLogDebug("qi.EventLoop") << this << "run starting";
_running = true;
_id = boost::this_thread::get_id();
// stop will set _base to 0 to delect usage attempts after stop
// so use a local copy.
event_base* base = _base;
// libevent needs a dummy op to perform otherwise dispatch exits immediately
struct bufferevent *bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_THREADSAFE);
//bufferevent_setcb(bev, NULL, NULL, ::qi::errorcb, this);
bufferevent_enable(bev, EV_READ|EV_WRITE);
event_base_dispatch(base);
qiLogDebug("qi.EventLoop") << this << "run ending";
bufferevent_free(bev);
event_base_free(base);
{
boost::recursive_mutex::scoped_lock sl(_mutex);
_running = false;
if (_destroyMe)
delete this;
}
}
bool EventLoopPrivate::isInEventLoopThread()
{
return boost::this_thread::get_id() == _id;
}
void EventLoopPrivate::stop()
{
event_base* base = 0;
{ // Ensure no multipe calls are made.
boost::recursive_mutex::scoped_lock sl(_mutex);
if (_base && _running)
{
base = _base;
_base = 0;
}
}
if (base)
if (event_base_loopexit(base, NULL) != 0)
qiLogError("networkThread") << "Can't stop the EventLoopPrivate";
}
void EventLoopPrivate::join()
{
if (_base)
qiLogError("EventLoop") << "join() called before stop()";
if (boost::this_thread::get_id() == _id)
return;
if (_threaded)
_thd.join();
else
while (_running)
qi::os::msleep(0);
}
static void async_call(evutil_socket_t,
short what,
void *context)
{
EventLoop::AsyncCallHandle* handle = (EventLoop::AsyncCallHandle*)context;
if (!handle->_p->cancelled)
handle->_p->callback();
event_del(handle->_p->ev);
event_free(handle->_p->ev);
delete handle;
}
EventLoop::AsyncCallHandle EventLoopPrivate::asyncCall(uint64_t usDelay, boost::function<void ()> cb)
{
EventLoop::AsyncCallHandle res;
struct timeval period;
period.tv_sec = usDelay / 1000000ULL;
period.tv_usec = usDelay % 1000000ULL;
struct event *ev = event_new(_base, -1, 0, async_call,
new EventLoop::AsyncCallHandle(res));
// Order is important.
res._p->ev = ev;
res._p->cancelled = false;
res._p->callback = cb;
event_add(ev, &period);
return res;
}
// Basic pimpl bouncers.
EventLoop::AsyncCallHandle::AsyncCallHandle()
{
_p = boost::shared_ptr<AsyncCallHandlePrivate>(new AsyncCallHandlePrivate());
}
EventLoop::AsyncCallHandle::~AsyncCallHandle()
{
}
void EventLoop::AsyncCallHandle::cancel()
{
_p->cancel();
}
EventLoop::EventLoop()
{
_p = new EventLoopPrivate();
}
EventLoop::~EventLoop()
{
_p->destroy(false);
_p = 0;
}
bool EventLoop::isInEventLoopThread()
{
return _p->isInEventLoopThread();
}
void EventLoop::join()
{
_p->join();
}
void EventLoop::start()
{
_p->start();
}
void EventLoop::stop()
{
_p->stop();
}
void EventLoop::run()
{
_p->run();
}
EventLoop::AsyncCallHandle
EventLoop::asyncCall(
uint64_t usDelay,
boost::function<void ()> callback)
{
return _p->asyncCall(usDelay, callback);
}
static void eventloop_stop(EventLoop* ctx)
{
ctx->stop();
ctx->join();
delete ctx;
}
static EventLoop* _get(EventLoop* &ctx)
{
if (!ctx)
{
if (! qi::Application::initialized())
{
qiLogError("EventLoop") << "EventLoop created before qi::Application()";
}
ctx = new EventLoop();
ctx->start();
Application::atExit(boost::bind(&eventloop_stop, ctx));
}
return ctx;
}
static EventLoop* _netEventLoop = 0;
static EventLoop* _objEventLoop = 0;
EventLoop* getDefaultNetworkEventLoop()
{
return _get(_netEventLoop);
}
EventLoop* getDefaultObjectEventLoop()
{
return _get(_objEventLoop);
}
}
<|endoftext|>
|
<commit_before>// -*- c-basic-offset: 2; related-file-name: "tuple.h" -*-
/*
* @(#)$Id$
*
* This file is distributed under the terms in the attached LICENSE file.
* If you do not find this file, copies can be found by writing to:
* Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300,
* Berkeley, CA, 94704. Attention: Intel License Inquiry.
* Or
* UC Berkeley EECS Computer Science Division, 387 Soda Hall #1776,
* Berkeley, CA, 94707. Attention: P2 Group.
*
* DESCRIPTION: Tuple fields and Tuple implementations
*
*/
#include "value.h"
#include "tuple.h"
#include <assert.h>
void
Tuple::xdr_marshal( XDR *x )
{
assert(frozen);
// we used to pass a pointer to a size_t into xdr_uint32_t, hence
// the following assertion. However, gcc 4.0 forbids that anyway,
// so we now do the cast and copy, and this assertion may be
// unnecessary. -- JMH 1/10/06
assert(sizeof(size_t) == sizeof(u_int32_t));
// Tuple size overall
size_t sz = fields.size();
u_int32_t i = (u_int32_t)sz;
xdr_uint32_t(x, &i);
// Marshal the fields
for(size_t i=0; i < fields.size(); i++) {
fields[i]->xdr_marshal(x);
};
}
TuplePtr
Tuple::xdr_unmarshal(XDR* x)
{
TuplePtr t = Tuple::mk();
// we used to pass a pointer to a size_t into xdr_uint32_t, hence
// the following assertion. However, gcc 4.0 forbids that anyway,
// so we now do the cast and copy, and this assertion may be
// unnecessary. -- JMH 1/10/06
assert(sizeof(size_t) == sizeof(u_int32_t));
// Tuple size overall
u_int32_t ui;
xdr_uint32_t(x, &ui);
// Marshal the fields
size_t sz = ui;
for(size_t i=0; i < sz; i++) {
t->append(Value::xdr_unmarshal(x));
}
return t;
}
string
Tuple::toString() const
{
ostringstream sb;
sb << "<";
for(size_t i=0; i < fields.size(); i++) {
sb << fields[i]->toString();
if (i != fields.size() - 1) {
sb << ", ";
}
}
sb << ">";
return sb.str();
}
string
Tuple::toConfString() const
{
ostringstream sb;
sb << "<";
for(size_t i=0; i < fields.size(); i++) {
sb << fields[i]->toConfString();
if (i != fields.size() - 1) {
sb << ", ";
}
}
sb << ">";
return sb.str();
}
int
Tuple::compareTo(TuplePtr other) const
{
if (size() == other->size()) {
for (size_t i = 0;
i < size();
i++) {
ValuePtr mine = fields[i];
ValuePtr its = (*other)[i];
int result = mine->compareTo(its);
if (result != 0) {
// Found a field position for which we are different. Return
// the difference.
return result;
}
}
// All fields are equal.
return 0;
} else if (size() < other->size()) {
return -1;
} else {
return 1;
}
}
void
Tuple::tag(string key,
ValuePtr value)
{
assert(!frozen);
// Is the tag map created?
if (_tags == 0) {
// Create it
_tags = new std::map< string, ValuePtr >();
// We'd better still have memory for this
assert(_tags != 0);
}
_tags->insert(std::make_pair(key, value));
}
ValuePtr
Tuple::tag(string key)
{
// Do we have a tag map?
if (_tags == 0) {
// Nope, just say no
return ValuePtr();
} else {
// Find the pair for that map
std::map< string, ValuePtr >::iterator result = _tags->find(key);
// Did we get it?
if (result == _tags->end()) {
// Nope, no such tag
return ValuePtr();
} else {
return result->second;
}
}
}
TuplePtr
Tuple::EMPTY = Tuple::mk();
uint
Tuple::_tupleIDCounter = 0;
// Create an empty initializer object so that the EMPTY tuple is fully
// initialized.
Tuple::EmptyInitializer
_theEmptyInitializer;
void
Tuple::concat(TuplePtr tf)
{
assert(!frozen);
// Copy fields
for (size_t i = 0;
i < tf->size();
i++) {
append((*tf)[i]);
}
};
Tuple::~Tuple()
{
if (_tags) {
delete _tags;
}
}
uint
Tuple::ID()
{
return _ID;
}
<commit_msg>Moved over constructors, destructors, and freeze from .h file<commit_after>// -*- c-basic-offset: 2; related-file-name: "tuple.h" -*-
/*
* @(#)$Id$
*
* This file is distributed under the terms in the attached LICENSE file.
* If you do not find this file, copies can be found by writing to:
* Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300,
* Berkeley, CA, 94704. Attention: Intel License Inquiry.
* Or
* UC Berkeley EECS Computer Science Division, 387 Soda Hall #1776,
* Berkeley, CA, 94707. Attention: P2 Group.
*
* DESCRIPTION: Tuple fields and Tuple implementations
*
*/
#include "value.h"
#include "tuple.h"
#include <assert.h>
void
Tuple::xdr_marshal( XDR *x )
{
assert(frozen);
// we used to pass a pointer to a size_t into xdr_uint32_t, hence
// the following assertion. However, gcc 4.0 forbids that anyway,
// so we now do the cast and copy, and this assertion may be
// unnecessary. -- JMH 1/10/06
assert(sizeof(size_t) == sizeof(u_int32_t));
// Tuple size overall
size_t sz = fields.size();
u_int32_t i = (u_int32_t)sz;
xdr_uint32_t(x, &i);
// Marshal the fields
for(size_t i=0; i < fields.size(); i++) {
fields[i]->xdr_marshal(x);
};
}
TuplePtr
Tuple::xdr_unmarshal(XDR* x)
{
TuplePtr t = Tuple::mk();
// we used to pass a pointer to a size_t into xdr_uint32_t, hence
// the following assertion. However, gcc 4.0 forbids that anyway,
// so we now do the cast and copy, and this assertion may be
// unnecessary. -- JMH 1/10/06
assert(sizeof(size_t) == sizeof(u_int32_t));
// Tuple size overall
u_int32_t ui;
xdr_uint32_t(x, &ui);
// Marshal the fields
size_t sz = ui;
for(size_t i=0; i < sz; i++) {
t->append(Value::xdr_unmarshal(x));
}
return t;
}
string
Tuple::toString() const
{
ostringstream sb;
sb << "<";
for(size_t i=0; i < fields.size(); i++) {
sb << fields[i]->toString();
if (i != fields.size() - 1) {
sb << ", ";
}
}
sb << ">";
return sb.str();
}
string
Tuple::toConfString() const
{
ostringstream sb;
sb << "<";
for(size_t i=0; i < fields.size(); i++) {
sb << fields[i]->toConfString();
if (i != fields.size() - 1) {
sb << ", ";
}
}
sb << ">";
return sb.str();
}
int
Tuple::compareTo(TuplePtr other) const
{
if (size() == other->size()) {
for (size_t i = 0;
i < size();
i++) {
ValuePtr mine = fields[i];
ValuePtr its = (*other)[i];
int result = mine->compareTo(its);
if (result != 0) {
// Found a field position for which we are different. Return
// the difference.
return result;
}
}
// All fields are equal.
return 0;
} else if (size() < other->size()) {
return -1;
} else {
return 1;
}
}
void
Tuple::tag(string key,
ValuePtr value)
{
assert(!frozen);
// Is the tag map created?
if (_tags == 0) {
// Create it
_tags = new std::map< string, ValuePtr >();
// We'd better still have memory for this
assert(_tags != 0);
}
_tags->insert(std::make_pair(key, value));
}
ValuePtr
Tuple::tag(string key)
{
// Do we have a tag map?
if (_tags == 0) {
// Nope, just say no
return ValuePtr();
} else {
// Find the pair for that map
std::map< string, ValuePtr >::iterator result = _tags->find(key);
// Did we get it?
if (result == _tags->end()) {
// Nope, no such tag
return ValuePtr();
} else {
return result->second;
}
}
}
TuplePtr
Tuple::EMPTY = Tuple::mk();
uint
Tuple::_tupleIDCounter = 0;
// Create an empty initializer object so that the EMPTY tuple is fully
// initialized.
Tuple::EmptyInitializer
_theEmptyInitializer;
void
Tuple::concat(TuplePtr tf)
{
assert(!frozen);
// Copy fields
for (size_t i = 0;
i < tf->size();
i++) {
append((*tf)[i]);
}
};
Tuple::~Tuple()
{
// std::cout << "Destroying tuple "
// << toString()
// << " with ID "
// << _ID
// << "\n";
if (_tags) {
delete _tags;
}
}
uint
Tuple::ID()
{
return _ID;
}
Tuple::Tuple()
: fields(),
frozen(false),
_tags(0),
_ID(_tupleIDCounter++)
{
// std::cout << "Creating tuple " << toString()
// << "with ID " << _ID
// << "\n";
}
TuplePtr
Tuple::mk()
{
TuplePtr p(new Tuple());
return p;
};
void
Tuple::append(ValuePtr tf)
{
assert(!frozen);
fields.push_back(tf);
}
void
Tuple::freeze()
{
frozen = true;
// std::cout << "Freezing tuple " << toString()
// << "with ID " << _ID << "\n";
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2018 jmjatlanta and contributors.
*
* The MIT License
*
* 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.
*/
#include <graphene/chain/protocol/htlc.hpp>
#define SECONDS_PER_DAY (60 * 60 * 24)
namespace graphene { namespace chain {
void htlc_create_operation::validate()const {
FC_ASSERT( fee.amount >= 0, "Fee amount should not be negative" );
FC_ASSERT( amount.amount > 0, "HTLC amount should be greater than zero" );
}
share_type htlc_create_operation::calculate_fee( const fee_parameters_type& fee_params )const
{
uint64_t days = ( claim_period_seconds + SECONDS_PER_DAY - 1 ) / SECONDS_PER_DAY;
// multiply with overflow check
uint64_t per_day_fee = fee_params.fee_per_day * days;
FC_ASSERT( days == 0 || per_day_fee / days == fee_params.fee_per_day, "Fee calculation overflow" );
return fee_params.fee + per_day_fee;
}
void htlc_redeem_operation::validate()const {
FC_ASSERT( fee.amount >= 0, "Fee amount should not be negative" );
}
share_type htlc_redeem_operation::calculate_fee( const fee_parameters_type& fee_params )const
{
if (fee_params.fee_per_kb == 0)
return fee_params.fee;
uint64_t product = 1024 * fee_params.fee_per_kb;
FC_ASSERT( product / 1024 == fee_params.fee_per_kb, "Fee calculation overflow");
return fee_params.fee
+ ( preimage.size() + 1023 ) / 1024 * fee_params.fee_per_kb;
}
void htlc_extend_operation::validate()const {
FC_ASSERT( fee.amount >= 0 , "Fee amount should not be negative");
}
share_type htlc_extend_operation::calculate_fee( const fee_parameters_type& fee_params )const
{
uint32_t days = ( seconds_to_add + SECONDS_PER_DAY - 1 ) / SECONDS_PER_DAY;
uint64_t per_day_fee = fee_params.fee_per_day * days;
FC_ASSERT( days == 0 || per_day_fee / days == fee_params.fee_per_day, "Fee calculation overflow" );
return fee_params.fee + per_day_fee;
}
} }
<commit_msg>fix bug in fee calculation<commit_after>/*
* Copyright (c) 2018 jmjatlanta and contributors.
*
* The MIT License
*
* 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.
*/
#include <graphene/chain/protocol/htlc.hpp>
#define SECONDS_PER_DAY (60 * 60 * 24)
namespace graphene { namespace chain {
void htlc_create_operation::validate()const {
FC_ASSERT( fee.amount >= 0, "Fee amount should not be negative" );
FC_ASSERT( amount.amount > 0, "HTLC amount should be greater than zero" );
}
share_type htlc_create_operation::calculate_fee( const fee_parameters_type& fee_params )const
{
uint64_t days = ( claim_period_seconds + SECONDS_PER_DAY - 1 ) / SECONDS_PER_DAY;
// multiply with overflow check
uint64_t per_day_fee = fee_params.fee_per_day * days;
FC_ASSERT( days == 0 || per_day_fee / days == fee_params.fee_per_day, "Fee calculation overflow" );
return fee_params.fee + per_day_fee;
}
void htlc_redeem_operation::validate()const {
FC_ASSERT( fee.amount >= 0, "Fee amount should not be negative" );
}
share_type htlc_redeem_operation::calculate_fee( const fee_parameters_type& fee_params )const
{
uint64_t kb = ( preimage.size() + 1023 ) / 1024;
uint64_t product = kb * fee_params.fee_per_kb;
FC_ASSERT( kb == 0 || product / kb == fee_params.fee_per_kb, "Fee calculation overflow");
return fee_params.fee + product;
}
void htlc_extend_operation::validate()const {
FC_ASSERT( fee.amount >= 0 , "Fee amount should not be negative");
}
share_type htlc_extend_operation::calculate_fee( const fee_parameters_type& fee_params )const
{
uint32_t days = ( seconds_to_add + SECONDS_PER_DAY - 1 ) / SECONDS_PER_DAY;
uint64_t per_day_fee = fee_params.fee_per_day * days;
FC_ASSERT( days == 0 || per_day_fee / days == fee_params.fee_per_day, "Fee calculation overflow" );
return fee_params.fee + per_day_fee;
}
} }
<|endoftext|>
|
<commit_before> /*
kopetechatwindowstylemanager.cpp - Manager all chat window styles
Copyright (c) 2005 by Michaël Larouche <michael.larouche@kdemail.net>
Kopete (c) 2002-2005 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program 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. *
* *
*************************************************************************
*/
#include "kopetechatwindowstylemanager.h"
// Qt includes
#include <QStack>
// KDE includes
#include <kstandarddirs.h>
#include <kdirlister.h>
#include <kdebug.h>
#include <kurl.h>
#include <kglobal.h>
#include <karchive.h>
#include <kzip.h>
#include <ktar.h>
#include <kmimetype.h>
#include <kio/netaccess.h>
#include <kstaticdeleter.h>
#include <kconfig.h>
#include <kglobal.h>
#include "kopetechatwindowstyle.h"
class ChatWindowStyleManager::Private
{
public:
Private()
: styleDirLister(0)
{}
~Private()
{
if(styleDirLister)
{
styleDirLister->deleteLater();
}
QMap<QString, ChatWindowStyle*>::Iterator styleIt, styleItEnd = stylePool.end();
for(styleIt = stylePool.begin(); styleIt != styleItEnd; ++styleIt)
{
delete styleIt.data();
}
}
KDirLister *styleDirLister;
StyleList availableStyles;
// key = style path, value = ChatWindowStyle instance
QMap<QString, ChatWindowStyle*> stylePool;
QStack<KURL> styleDirs;
};
static KStaticDeleter<ChatWindowStyleManager> ChatWindowStyleManagerstaticDeleter;
ChatWindowStyleManager *ChatWindowStyleManager::s_self = 0;
ChatWindowStyleManager *ChatWindowStyleManager::self()
{
if( !s_self )
{
ChatWindowStyleManagerstaticDeleter.setObject( s_self, new ChatWindowStyleManager() );
}
return s_self;
}
ChatWindowStyleManager::ChatWindowStyleManager(QObject *parent, const char *name)
: QObject(parent, name), d(new Private())
{
kdDebug(14000) << k_funcinfo << endl;
loadStyles();
}
ChatWindowStyleManager::~ChatWindowStyleManager()
{
kdDebug(14000) << k_funcinfo << endl;
delete d;
}
void ChatWindowStyleManager::loadStyles()
{
QStringList chatStyles = KGlobal::dirs()->findDirs( "appdata", QString::fromUtf8( "styles" ) );
QStringList::const_iterator it;
for(it = chatStyles.constBegin(); it != chatStyles.constEnd(); ++it)
{
kdDebug(14000) << k_funcinfo << *it << endl;
d->styleDirs.push( KURL(*it) );
}
d->styleDirLister = new KDirLister;
d->styleDirLister->setDirOnlyMode(true);
connect(d->styleDirLister, SIGNAL(newItems(const KFileItemList &)), this, SLOT(slotNewStyles(const KFileItemList &)));
connect(d->styleDirLister, SIGNAL(completed()), this, SLOT(slotDirectoryFinished()));
if( !d->styleDirs.isEmpty() )
d->styleDirLister->openURL(d->styleDirs.pop(), true);
}
ChatWindowStyleManager::StyleList ChatWindowStyleManager::getAvailableStyles()
{
return d->availableStyles;
}
int ChatWindowStyleManager::installStyle(const QString &styleBundlePath)
{
QString localStyleDir( locateLocal( "appdata", QString::fromUtf8("styles/") ) );
KArchiveEntry *currentEntry = 0L;
KArchiveDirectory* currentDir = 0L;
KArchive *archive = 0L;
if( localStyleDir.isEmpty() )
{
return StyleNoDirectoryValid;
}
// Find mimetype for current bundle. ZIP and KTar need separate constructor
QString currentBundleMimeType = KMimeType::findByPath(styleBundlePath, 0, false)->name();
if(currentBundleMimeType == "application/x-zip")
{
archive = new KZip(styleBundlePath);
}
else if( currentBundleMimeType == "application/x-tgz" || currentBundleMimeType == "application/x-tbz" || currentBundleMimeType == "application/x-gzip" || currentBundleMimeType == "application/x-bzip2" )
{
archive = new KTar(styleBundlePath);
}
else
{
return StyleCannotOpen;
}
if ( !archive->open(IO_ReadOnly) )
{
delete archive;
return StyleCannotOpen;
}
const KArchiveDirectory* rootDir = archive->directory();
// Ok where we go to check if the archive is valid.
// Each time we found a correspondance to a theme bundle, we add a point to validResult.
// A valid style bundle must have:
// -a Contents, Contents/Resources, Co/Res/Incoming, Co/Res/Outgoing dirs
// main.css, Footer.html, Header.html, Status.html files in Contents/Ressources.
// So for a style bundle to be valid, it must have a result greather than 8, because we test for 8 required entry.
int validResult = 0;
QStringList entries = rootDir->entries();
// Will be reused later.
QStringList::Iterator entriesIt, entriesItEnd = entries.end();
for(entriesIt = entries.begin(); entriesIt != entries.end(); ++entriesIt)
{
currentEntry = const_cast<KArchiveEntry*>(rootDir->entry(*entriesIt));
// kdDebug() << k_funcinfo << "Current entry name: " << currentEntry->name() << endl;
if (currentEntry->isDirectory())
{
currentDir = dynamic_cast<KArchiveDirectory*>( currentEntry );
if (currentDir)
{
if( currentDir->entry(QString::fromUtf8("Contents")) )
{
// kdDebug() << k_funcinfo << "Contents found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources/Incoming")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources/Incoming found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources/Outgoing")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources/Outgoing found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources/main.css")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources/main.css found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources/Footer.html")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources/Footer.html found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources/Status.html")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources/Status.html found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources/Header.html")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources/Header.html found" << endl;
validResult += 1;
}
}
}
}
// kdDebug() << k_funcinfo << "Valid result: " << QString::number(validResult) << endl;
// The archive is a valid style bundle.
if(validResult >= 8)
{
bool installOk = false;
for(entriesIt = entries.begin(); entriesIt != entries.end(); ++entriesIt)
{
currentEntry = const_cast<KArchiveEntry*>(rootDir->entry(*entriesIt));
if(currentEntry && currentEntry->isDirectory())
{
// Ignore this MacOS X "garbage" directory in zip.
if(currentEntry->name() == QString::fromUtf8("__MACOSX"))
{
continue;
}
else
{
currentDir = dynamic_cast<KArchiveDirectory*>(currentEntry);
if(currentDir)
{
currentDir->copyTo(localStyleDir + currentDir->name());
installOk = true;
}
}
}
}
archive->close();
delete archive;
if(installOk)
return StyleInstallOk;
else
return StyleUnknow;
}
else
{
archive->close();
delete archive;
return StyleNotValid;
}
if(archive)
{
archive->close();
delete archive;
}
return StyleUnknow;
}
bool ChatWindowStyleManager::removeStyle(const QString &stylePath)
{
// Find for the current style in avaiableStyles map.
StyleList::Iterator foundStyle = d->availableStyles.find(stylePath);
// QMap iterator return end() if it found no item.
if(foundStyle != d->availableStyles.end())
{
d->availableStyles.remove(foundStyle);
// Remove and delete style from pool if needed.
if( d->stylePool.contains(stylePath) )
{
ChatWindowStyle *deletedStyle = d->stylePool[stylePath];
d->stylePool.remove(stylePath);
delete deletedStyle;
}
// Do the actual deletion of the directory style.
return KIO::NetAccess::del( KURL(stylePath), 0 );
}
else
{
return false;
}
}
ChatWindowStyle *ChatWindowStyleManager::getStyleFromPool(const QString &stylePath)
{
if( d->stylePool.contains(stylePath) )
{
// NOTE: This is a hidden config switch for style developers
// Check in the config if the cache is disabled.
// if the cache is disabled, reload the style everytime it's getted.
KConfig *config = KGlobal::config();
config->setGroup("KopeteStyleDebug");
bool disableCache = config->readBoolEntry("disableStyleCache", false);
if(disableCache)
{
d->stylePool[stylePath]->reload();
}
return d->stylePool[stylePath];
}
else
{
// Build a chat window style and list its variants, then add it to the pool.
ChatWindowStyle *style = new ChatWindowStyle(stylePath, ChatWindowStyle::StyleBuildNormal);
d->stylePool.insert(stylePath, style);
return style;
}
return 0;
}
void ChatWindowStyleManager::slotNewStyles(const KFileItemList &dirList)
{
KFileItem *item;
QList<KFileItem*>::const_iterator it=dirList.begin();
while( it!=dirList.end() )
{
// Ignore data dir(from deprecated XSLT themes)
if( !(*it)->url().fileName().contains(QString::fromUtf8("data")) )
{
kdDebug(14000) << k_funcinfo << "Listing: " << item->url().fileName() << endl;
// If the style path is already in the pool, that's mean the style was updated on disk
// Reload the style
if( d->stylePool.contains(item->url().path()) )
{
kdDebug(14000) << k_funcinfo << "Updating style: " << item->url().path() << endl;
d->stylePool[item->url().path()]->reload();
// Add to avaialble if required.
if( !d->availableStyles.contains(item->url().fileName()) )
d->availableStyles.insert(item->url().fileName(), item->url().path());
}
else
{
// TODO: Use name from Info.plist
d->availableStyles.insert(item->url().fileName(), item->url().path());
}
}
++it;
}
}
void ChatWindowStyleManager::slotDirectoryFinished()
{
// Start another scanning if the directories stack is not empty
if( !d->styleDirs.isEmpty() )
{
kdDebug(14000) << k_funcinfo << "Starting another directory." << endl;
d->styleDirLister->openURL(d->styleDirs.pop(), true);
}
else
{
emit loadStylesFinished();
}
}
#include "kopetechatwindowstylemanager.moc"
<commit_msg>Crash--<commit_after> /*
kopetechatwindowstylemanager.cpp - Manager all chat window styles
Copyright (c) 2005 by Michaël Larouche <michael.larouche@kdemail.net>
Kopete (c) 2002-2005 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program 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. *
* *
*************************************************************************
*/
#include "kopetechatwindowstylemanager.h"
// Qt includes
#include <QStack>
// KDE includes
#include <kstandarddirs.h>
#include <kdirlister.h>
#include <kdebug.h>
#include <kurl.h>
#include <kglobal.h>
#include <karchive.h>
#include <kzip.h>
#include <ktar.h>
#include <kmimetype.h>
#include <kio/netaccess.h>
#include <kstaticdeleter.h>
#include <kconfig.h>
#include <kglobal.h>
#include "kopetechatwindowstyle.h"
class ChatWindowStyleManager::Private
{
public:
Private()
: styleDirLister(0)
{}
~Private()
{
if(styleDirLister)
{
styleDirLister->deleteLater();
}
QMap<QString, ChatWindowStyle*>::Iterator styleIt, styleItEnd = stylePool.end();
for(styleIt = stylePool.begin(); styleIt != styleItEnd; ++styleIt)
{
delete styleIt.data();
}
}
KDirLister *styleDirLister;
StyleList availableStyles;
// key = style path, value = ChatWindowStyle instance
QMap<QString, ChatWindowStyle*> stylePool;
QStack<KURL> styleDirs;
};
static KStaticDeleter<ChatWindowStyleManager> ChatWindowStyleManagerstaticDeleter;
ChatWindowStyleManager *ChatWindowStyleManager::s_self = 0;
ChatWindowStyleManager *ChatWindowStyleManager::self()
{
if( !s_self )
{
ChatWindowStyleManagerstaticDeleter.setObject( s_self, new ChatWindowStyleManager() );
}
return s_self;
}
ChatWindowStyleManager::ChatWindowStyleManager(QObject *parent, const char *name)
: QObject(parent, name), d(new Private())
{
kdDebug(14000) << k_funcinfo << endl;
loadStyles();
}
ChatWindowStyleManager::~ChatWindowStyleManager()
{
kdDebug(14000) << k_funcinfo << endl;
delete d;
}
void ChatWindowStyleManager::loadStyles()
{
QStringList chatStyles = KGlobal::dirs()->findDirs( "appdata", QString::fromUtf8( "styles" ) );
QStringList::const_iterator it;
for(it = chatStyles.constBegin(); it != chatStyles.constEnd(); ++it)
{
kdDebug(14000) << k_funcinfo << *it << endl;
d->styleDirs.push( KURL(*it) );
}
d->styleDirLister = new KDirLister;
d->styleDirLister->setDirOnlyMode(true);
connect(d->styleDirLister, SIGNAL(newItems(const KFileItemList &)), this, SLOT(slotNewStyles(const KFileItemList &)));
connect(d->styleDirLister, SIGNAL(completed()), this, SLOT(slotDirectoryFinished()));
if( !d->styleDirs.isEmpty() )
d->styleDirLister->openURL(d->styleDirs.pop(), true);
}
ChatWindowStyleManager::StyleList ChatWindowStyleManager::getAvailableStyles()
{
return d->availableStyles;
}
int ChatWindowStyleManager::installStyle(const QString &styleBundlePath)
{
QString localStyleDir( locateLocal( "appdata", QString::fromUtf8("styles/") ) );
KArchiveEntry *currentEntry = 0L;
KArchiveDirectory* currentDir = 0L;
KArchive *archive = 0L;
if( localStyleDir.isEmpty() )
{
return StyleNoDirectoryValid;
}
// Find mimetype for current bundle. ZIP and KTar need separate constructor
QString currentBundleMimeType = KMimeType::findByPath(styleBundlePath, 0, false)->name();
if(currentBundleMimeType == "application/x-zip")
{
archive = new KZip(styleBundlePath);
}
else if( currentBundleMimeType == "application/x-tgz" || currentBundleMimeType == "application/x-tbz" || currentBundleMimeType == "application/x-gzip" || currentBundleMimeType == "application/x-bzip2" )
{
archive = new KTar(styleBundlePath);
}
else
{
return StyleCannotOpen;
}
if ( !archive->open(IO_ReadOnly) )
{
delete archive;
return StyleCannotOpen;
}
const KArchiveDirectory* rootDir = archive->directory();
// Ok where we go to check if the archive is valid.
// Each time we found a correspondance to a theme bundle, we add a point to validResult.
// A valid style bundle must have:
// -a Contents, Contents/Resources, Co/Res/Incoming, Co/Res/Outgoing dirs
// main.css, Footer.html, Header.html, Status.html files in Contents/Ressources.
// So for a style bundle to be valid, it must have a result greather than 8, because we test for 8 required entry.
int validResult = 0;
QStringList entries = rootDir->entries();
// Will be reused later.
QStringList::Iterator entriesIt, entriesItEnd = entries.end();
for(entriesIt = entries.begin(); entriesIt != entries.end(); ++entriesIt)
{
currentEntry = const_cast<KArchiveEntry*>(rootDir->entry(*entriesIt));
// kdDebug() << k_funcinfo << "Current entry name: " << currentEntry->name() << endl;
if (currentEntry->isDirectory())
{
currentDir = dynamic_cast<KArchiveDirectory*>( currentEntry );
if (currentDir)
{
if( currentDir->entry(QString::fromUtf8("Contents")) )
{
// kdDebug() << k_funcinfo << "Contents found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources/Incoming")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources/Incoming found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources/Outgoing")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources/Outgoing found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources/main.css")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources/main.css found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources/Footer.html")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources/Footer.html found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources/Status.html")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources/Status.html found" << endl;
validResult += 1;
}
if( currentDir->entry(QString::fromUtf8("Contents/Resources/Header.html")) )
{
// kdDebug() << k_funcinfo << "Contents/Resources/Header.html found" << endl;
validResult += 1;
}
}
}
}
// kdDebug() << k_funcinfo << "Valid result: " << QString::number(validResult) << endl;
// The archive is a valid style bundle.
if(validResult >= 8)
{
bool installOk = false;
for(entriesIt = entries.begin(); entriesIt != entries.end(); ++entriesIt)
{
currentEntry = const_cast<KArchiveEntry*>(rootDir->entry(*entriesIt));
if(currentEntry && currentEntry->isDirectory())
{
// Ignore this MacOS X "garbage" directory in zip.
if(currentEntry->name() == QString::fromUtf8("__MACOSX"))
{
continue;
}
else
{
currentDir = dynamic_cast<KArchiveDirectory*>(currentEntry);
if(currentDir)
{
currentDir->copyTo(localStyleDir + currentDir->name());
installOk = true;
}
}
}
}
archive->close();
delete archive;
if(installOk)
return StyleInstallOk;
else
return StyleUnknow;
}
else
{
archive->close();
delete archive;
return StyleNotValid;
}
if(archive)
{
archive->close();
delete archive;
}
return StyleUnknow;
}
bool ChatWindowStyleManager::removeStyle(const QString &stylePath)
{
// Find for the current style in avaiableStyles map.
StyleList::Iterator foundStyle = d->availableStyles.find(stylePath);
// QMap iterator return end() if it found no item.
if(foundStyle != d->availableStyles.end())
{
d->availableStyles.remove(foundStyle);
// Remove and delete style from pool if needed.
if( d->stylePool.contains(stylePath) )
{
ChatWindowStyle *deletedStyle = d->stylePool[stylePath];
d->stylePool.remove(stylePath);
delete deletedStyle;
}
// Do the actual deletion of the directory style.
return KIO::NetAccess::del( KURL(stylePath), 0 );
}
else
{
return false;
}
}
ChatWindowStyle *ChatWindowStyleManager::getStyleFromPool(const QString &stylePath)
{
if( d->stylePool.contains(stylePath) )
{
// NOTE: This is a hidden config switch for style developers
// Check in the config if the cache is disabled.
// if the cache is disabled, reload the style everytime it's getted.
KConfig *config = KGlobal::config();
config->setGroup("KopeteStyleDebug");
bool disableCache = config->readBoolEntry("disableStyleCache", false);
if(disableCache)
{
d->stylePool[stylePath]->reload();
}
return d->stylePool[stylePath];
}
else
{
// Build a chat window style and list its variants, then add it to the pool.
ChatWindowStyle *style = new ChatWindowStyle(stylePath, ChatWindowStyle::StyleBuildNormal);
d->stylePool.insert(stylePath, style);
return style;
}
return 0;
}
void ChatWindowStyleManager::slotNewStyles(const KFileItemList &dirList)
{
QList<KFileItem*>::const_iterator it=dirList.begin();
while( it!=dirList.end() )
{
// Ignore data dir(from deprecated XSLT themes)
if( !(*it)->url().fileName().contains(QString::fromUtf8("data")) )
{
kdDebug(14000) << k_funcinfo << "Listing: " << (*it)->url().fileName() << endl;
// If the style path is already in the pool, that's mean the style was updated on disk
// Reload the style
if( d->stylePool.contains((*it)->url().path()) )
{
kdDebug(14000) << k_funcinfo << "Updating style: " << (*it)->url().path() << endl;
d->stylePool[(*it)->url().path()]->reload();
// Add to avaialble if required.
if( !d->availableStyles.contains((*it)->url().fileName()) )
d->availableStyles.insert((*it)->url().fileName(), (*it)->url().path());
}
else
{
// TODO: Use name from Info.plist
d->availableStyles.insert((*it)->url().fileName(), (*it)->url().path());
}
}
++it;
}
}
void ChatWindowStyleManager::slotDirectoryFinished()
{
// Start another scanning if the directories stack is not empty
if( !d->styleDirs.isEmpty() )
{
kdDebug(14000) << k_funcinfo << "Starting another directory." << endl;
d->styleDirLister->openURL(d->styleDirs.pop(), true);
}
else
{
emit loadStylesFinished();
}
}
#include "kopetechatwindowstylemanager.moc"
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2009, Image Engine Design 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 Image Engine Design nor the names of any
// other contributors to this software 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 "OpenEXR/ImathColor.h"
#include "boost/test/test_tools.hpp"
#include "boost/test/results_reporter.hpp"
#include "boost/test/unit_test_suite.hpp"
#include "boost/test/output_test_stream.hpp"
#include "boost/test/unit_test_log.hpp"
#include "boost/test/framework.hpp"
#include "boost/test/detail/unit_test_parameters.hpp"
#include "KDTreeTest.h"
#include "TypedDataTest.h"
#include "InterpolatorTest.h"
#include "IndexedIOTest.h"
#include "BoostUnitTestTest.h"
#include "MarchingCubesTest.h"
#include "DataConversionTest.h"
#include "DataConvertTest.h"
#include "DespatchTypedDataTest.h"
#include "CompilerTest.h"
#include "RadixSortTest.h"
#include "SweepAndPruneTest.h"
#include "ColorTransformTest.h"
#ifdef IECORE_WITH_BOOSTFACTORIAL
#include "AssociatedLegendreTest.h"
#include "SphericalHarmonicsTest.h"
#include "LevenbergMarquardtTest.h"
#endif
#include "SpaceTransformTest.h"
#include "LookupTest.h"
#include "StringAlgoTest.h"
using namespace boost::unit_test;
using boost::test_tools::output_test_stream;
using namespace IECore;
test_suite* init_unit_test_suite( int argc, char* argv[] )
{
test_suite* test = BOOST_TEST_SUITE( "IECore unit test" );
try
{
addBoostUnitTestTest(test);
addKDTreeTest(test);
addTypedDataTest(test);
addInterpolatorTest(test);
addIndexedIOTest(test);
addMarchingCubesTest(test);
addDataConversionTest(test);
addDataConvertTest(test);
addDespatchTypedDataTest(test);
addCompilerTest(test);
addRadixSortTest(test);
addSweepAndPruneTest(test);
addColorTransformTest(test);
#ifdef IECORE_WITH_BOOSTFACTORIAL
addAssociatedLegendreTest(test);
addSphericalHarmonicsTest(test);
addLevenbergMarquardtTest(test);
#endif
addSpaceTransformTest(test);
addLookupTest(test);
addStringAlgoTest(test);
}
catch (std::exception &ex)
{
std::cerr << "Failed to create test suite: " << ex.what() << std::endl;
throw;
}
return test;
}
<commit_msg>stupid extra white space<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2009, Image Engine Design 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 Image Engine Design nor the names of any
// other contributors to this software 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 "OpenEXR/ImathColor.h"
#include "boost/test/test_tools.hpp"
#include "boost/test/results_reporter.hpp"
#include "boost/test/unit_test_suite.hpp"
#include "boost/test/output_test_stream.hpp"
#include "boost/test/unit_test_log.hpp"
#include "boost/test/framework.hpp"
#include "boost/test/detail/unit_test_parameters.hpp"
#include "KDTreeTest.h"
#include "TypedDataTest.h"
#include "InterpolatorTest.h"
#include "IndexedIOTest.h"
#include "BoostUnitTestTest.h"
#include "MarchingCubesTest.h"
#include "DataConversionTest.h"
#include "DataConvertTest.h"
#include "DespatchTypedDataTest.h"
#include "CompilerTest.h"
#include "RadixSortTest.h"
#include "SweepAndPruneTest.h"
#include "ColorTransformTest.h"
#ifdef IECORE_WITH_BOOSTFACTORIAL
#include "AssociatedLegendreTest.h"
#include "SphericalHarmonicsTest.h"
#include "LevenbergMarquardtTest.h"
#endif
#include "SpaceTransformTest.h"
#include "LookupTest.h"
#include "StringAlgoTest.h"
using namespace boost::unit_test;
using boost::test_tools::output_test_stream;
using namespace IECore;
test_suite* init_unit_test_suite( int argc, char* argv[] )
{
test_suite* test = BOOST_TEST_SUITE( "IECore unit test" );
try
{
addBoostUnitTestTest(test);
addKDTreeTest(test);
addTypedDataTest(test);
addInterpolatorTest(test);
addIndexedIOTest(test);
addMarchingCubesTest(test);
addDataConversionTest(test);
addDataConvertTest(test);
addDespatchTypedDataTest(test);
addCompilerTest(test);
addRadixSortTest(test);
addSweepAndPruneTest(test);
addColorTransformTest(test);
#ifdef IECORE_WITH_BOOSTFACTORIAL
addAssociatedLegendreTest(test);
addSphericalHarmonicsTest(test);
addLevenbergMarquardtTest(test);
#endif
addSpaceTransformTest(test);
addLookupTest(test);
addStringAlgoTest(test);
}
catch (std::exception &ex)
{
std::cerr << "Failed to create test suite: " << ex.what() << std::endl;
throw;
}
return test;
}
<|endoftext|>
|
<commit_before>// This file is part of the Orbbec Astra SDK [https://orbbec3d.com]
// Copyright (c) 2015 Orbbec 3D
//
// 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.
//
// Be excellent to each other.
#ifndef ASTRA_PLUGIN_STREAM_HPP
#define ASTRA_PLUGIN_STREAM_HPP
#include <astra_core/astra_core.hpp>
#include <astra_core/plugins/astra_plugin_logging.hpp>
#include <astra_core/plugins/astra_pluginservice_proxy.hpp>
#include <astra_core/plugins/astra_stream_callback_listener.hpp>
#include <system_error>
#include <cassert>
#include <unordered_set>
namespace astra { namespace plugins {
class StreamHandleHash
{
public:
std::size_t operator()(const astra_stream_t streamHandle) const
{
return std::hash<astra_stream_t>()(streamHandle);
}
};
class StreamHandleEqualTo
{
public:
std::size_t operator()(const astra_stream_t& lhs,
const astra_stream_t& rhs) const
{
return lhs == rhs;
}
};
template<class T, class U>
T* make_stream(U&& u)
{
T* t = new T(std::forward<U>(u));
t->register_self();
return t;
}
template<class T, class... U>
T* make_stream(U&&... u)
{
T* t = new T(std::forward<U>(u)...);
t->register_self();
return t;
}
class stream : public stream_callback_listener
{
public:
stream(pluginservice_proxy& pluginService,
astra_streamset_t streamSet,
stream_description description)
: pluginService_(pluginService),
streamSet_(streamSet),
description_(description)
{
create_stream(description);
}
virtual ~stream()
{
pluginService_.destroy_stream(streamHandle_);
}
void register_self()
{
if (registered_)
return;
stream_callbacks_t pluginCallbacks = create_plugin_callbacks(this);
pluginService_.register_stream(streamHandle_, pluginCallbacks);
registered_ = true;
}
inline const stream_description& description() { return description_; }
inline astra_stream_t get_handle() { return streamHandle_; }
protected:
inline pluginservice_proxy& pluginService() const { return pluginService_; }
private:
virtual void connection_added(astra_stream_t stream,
astra_streamconnection_t connection) override final;
virtual void connection_removed(astra_stream_t stream,
astra_bin_t bin,
astra_streamconnection_t connection) override final;
virtual void connection_started(astra_stream_t stream,
astra_streamconnection_t connection) override final;
virtual void connection_stopped(astra_stream_t stream,
astra_streamconnection_t connection) override final;
virtual void set_parameter(astra_streamconnection_t connection,
astra_parameter_id id,
size_t inByteLength,
astra_parameter_data_t inData) override final;
virtual void get_parameter(astra_streamconnection_t connection,
astra_parameter_id id,
astra_parameter_bin_t& parameterBin) override final;
virtual void invoke(astra_streamconnection_t connection,
astra_command_id commandId,
size_t inByteLength,
astra_parameter_data_t inData,
astra_parameter_bin_t& parameterBin) override final;
virtual void on_connection_added(astra_streamconnection_t connection) {}
virtual void on_connection_removed(astra_bin_t bin,
astra_streamconnection_t connection) {}
virtual void on_connection_started(astra_streamconnection_t connection) {}
virtual void on_connection_stopped(astra_streamconnection_t connection) {}
virtual void on_set_parameter(astra_streamconnection_t connection,
astra_parameter_id id,
size_t inByteLength,
astra_parameter_data_t inData) {}
virtual void on_get_parameter(astra_streamconnection_t connection,
astra_parameter_id id,
astra_parameter_bin_t& parameterBin) {}
virtual void on_invoke(astra_streamconnection_t connection,
astra_command_id commandId,
size_t inByteLength,
astra_parameter_data_t inData,
astra_parameter_bin_t& parameterBin) {};
void create_stream(stream_description& description)
{
assert(streamHandle_ == nullptr);
astra_stream_desc_t* desc = static_cast<astra_stream_desc_t*>(description_);
LOG_INFO("astra.plugins.stream", "creating a %u, %u", desc->type, desc->subtype);
pluginService_.create_stream(streamSet_,
*desc,
&streamHandle_);
}
bool registered_{false};
pluginservice_proxy& pluginService_;
astra_streamset_t streamSet_{nullptr};
stream_description description_;
astra_stream_t streamHandle_{nullptr};
};
inline void stream::set_parameter(astra_streamconnection_t connection,
astra_parameter_id id,
size_t inByteLength,
astra_parameter_data_t inData)
{
on_set_parameter(connection, id, inByteLength, inData);
}
inline void stream::get_parameter(astra_streamconnection_t connection,
astra_parameter_id id,
astra_parameter_bin_t& parameterBin)
{
on_get_parameter(connection, id, parameterBin);
}
inline void stream::invoke(astra_streamconnection_t connection,
astra_command_id commandId,
size_t inByteLength,
astra_parameter_data_t inData,
astra_parameter_bin_t& parameterBin)
{
on_invoke(connection, commandId, inByteLength, inData, parameterBin);
}
inline void stream::connection_added(astra_stream_t stream,
astra_streamconnection_t connection)
{
assert(stream == streamHandle_);
LOG_INFO("astra.plugins.stream", "adding connection");
on_connection_added(connection);
}
inline void stream::connection_removed(astra_stream_t stream,
astra_bin_t bin,
astra_streamconnection_t connection)
{
assert(stream == streamHandle_);
LOG_INFO("astra.plugins.stream", "removing connection");
on_connection_removed(bin, connection);
}
inline void stream::connection_started(astra_stream_t stream,
astra_streamconnection_t connection)
{
assert(stream == streamHandle_);
on_connection_started(connection);
}
inline void stream::connection_stopped(astra_stream_t stream,
astra_streamconnection_t connection)
{
assert(stream == streamHandle_);
on_connection_stopped(connection);
}
}}
#endif /* ASTRA_PLUGIN_STREAM_HPP */
<commit_msg>remove excess whitespace in plugin stream<commit_after>// This file is part of the Orbbec Astra SDK [https://orbbec3d.com]
// Copyright (c) 2015 Orbbec 3D
//
// 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.
//
// Be excellent to each other.
#ifndef ASTRA_PLUGIN_STREAM_HPP
#define ASTRA_PLUGIN_STREAM_HPP
#include <astra_core/astra_core.hpp>
#include <astra_core/plugins/astra_plugin_logging.hpp>
#include <astra_core/plugins/astra_pluginservice_proxy.hpp>
#include <astra_core/plugins/astra_stream_callback_listener.hpp>
#include <system_error>
#include <cassert>
#include <unordered_set>
namespace astra { namespace plugins {
class StreamHandleHash
{
public:
std::size_t operator()(const astra_stream_t streamHandle) const
{
return std::hash<astra_stream_t>()(streamHandle);
}
};
class StreamHandleEqualTo
{
public:
std::size_t operator()(const astra_stream_t& lhs,
const astra_stream_t& rhs) const
{
return lhs == rhs;
}
};
template<class T, class U>
T* make_stream(U&& u)
{
T* t = new T(std::forward<U>(u));
t->register_self();
return t;
}
template<class T, class... U>
T* make_stream(U&&... u)
{
T* t = new T(std::forward<U>(u)...);
t->register_self();
return t;
}
class stream : public stream_callback_listener
{
public:
stream(pluginservice_proxy& pluginService,
astra_streamset_t streamSet,
stream_description description)
: pluginService_(pluginService),
streamSet_(streamSet),
description_(description)
{
create_stream(description);
}
virtual ~stream()
{
pluginService_.destroy_stream(streamHandle_);
}
void register_self()
{
if (registered_)
return;
stream_callbacks_t pluginCallbacks = create_plugin_callbacks(this);
pluginService_.register_stream(streamHandle_, pluginCallbacks);
registered_ = true;
}
inline const stream_description& description() { return description_; }
inline astra_stream_t get_handle() { return streamHandle_; }
protected:
inline pluginservice_proxy& pluginService() const { return pluginService_; }
private:
virtual void connection_added(astra_stream_t stream,
astra_streamconnection_t connection) override final;
virtual void connection_removed(astra_stream_t stream,
astra_bin_t bin,
astra_streamconnection_t connection) override final;
virtual void connection_started(astra_stream_t stream,
astra_streamconnection_t connection) override final;
virtual void connection_stopped(astra_stream_t stream,
astra_streamconnection_t connection) override final;
virtual void set_parameter(astra_streamconnection_t connection,
astra_parameter_id id,
size_t inByteLength,
astra_parameter_data_t inData) override final;
virtual void get_parameter(astra_streamconnection_t connection,
astra_parameter_id id,
astra_parameter_bin_t& parameterBin) override final;
virtual void invoke(astra_streamconnection_t connection,
astra_command_id commandId,
size_t inByteLength,
astra_parameter_data_t inData,
astra_parameter_bin_t& parameterBin) override final;
virtual void on_connection_added(astra_streamconnection_t connection) {}
virtual void on_connection_removed(astra_bin_t bin,
astra_streamconnection_t connection) {}
virtual void on_connection_started(astra_streamconnection_t connection) {}
virtual void on_connection_stopped(astra_streamconnection_t connection) {}
virtual void on_set_parameter(astra_streamconnection_t connection,
astra_parameter_id id,
size_t inByteLength,
astra_parameter_data_t inData) {}
virtual void on_get_parameter(astra_streamconnection_t connection,
astra_parameter_id id,
astra_parameter_bin_t& parameterBin) {}
virtual void on_invoke(astra_streamconnection_t connection,
astra_command_id commandId,
size_t inByteLength,
astra_parameter_data_t inData,
astra_parameter_bin_t& parameterBin) {};
void create_stream(stream_description& description)
{
assert(streamHandle_ == nullptr);
astra_stream_desc_t* desc = static_cast<astra_stream_desc_t*>(description_);
LOG_INFO("astra.plugins.stream", "creating a %u, %u", desc->type, desc->subtype);
pluginService_.create_stream(streamSet_,
*desc,
&streamHandle_);
}
bool registered_{false};
pluginservice_proxy& pluginService_;
astra_streamset_t streamSet_{nullptr};
stream_description description_;
astra_stream_t streamHandle_{nullptr};
};
inline void stream::set_parameter(astra_streamconnection_t connection,
astra_parameter_id id,
size_t inByteLength,
astra_parameter_data_t inData)
{
on_set_parameter(connection, id, inByteLength, inData);
}
inline void stream::get_parameter(astra_streamconnection_t connection,
astra_parameter_id id,
astra_parameter_bin_t& parameterBin)
{
on_get_parameter(connection, id, parameterBin);
}
inline void stream::invoke(astra_streamconnection_t connection,
astra_command_id commandId,
size_t inByteLength,
astra_parameter_data_t inData,
astra_parameter_bin_t& parameterBin)
{
on_invoke(connection, commandId, inByteLength, inData, parameterBin);
}
inline void stream::connection_added(astra_stream_t stream,
astra_streamconnection_t connection)
{
assert(stream == streamHandle_);
LOG_INFO("astra.plugins.stream", "adding connection");
on_connection_added(connection);
}
inline void stream::connection_removed(astra_stream_t stream,
astra_bin_t bin,
astra_streamconnection_t connection)
{
assert(stream == streamHandle_);
LOG_INFO("astra.plugins.stream", "removing connection");
on_connection_removed(bin, connection);
}
inline void stream::connection_started(astra_stream_t stream,
astra_streamconnection_t connection)
{
assert(stream == streamHandle_);
on_connection_started(connection);
}
inline void stream::connection_stopped(astra_stream_t stream,
astra_streamconnection_t connection)
{
assert(stream == streamHandle_);
on_connection_stopped(connection);
}
}}
#endif /* ASTRA_PLUGIN_STREAM_HPP */
<|endoftext|>
|
<commit_before>#ifndef CUKE_STEPMANAGER_HPP_
#define CUKE_STEPMANAGER_HPP_
#include <map>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
#include <boost/enable_shared_from_this.hpp>
#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
using boost::shared_ptr;
#include "../Table.hpp"
#include "../utils/Regex.hpp"
namespace cucumber {
namespace internal {
typedef unsigned int step_id_type;
class StepInfo;
class SingleStepMatch {
public:
typedef RegexMatch::submatches_type submatches_type;
operator const void *() const;
boost::shared_ptr<const StepInfo> stepInfo;
submatches_type submatches;
};
class MatchResult {
public:
typedef std::vector<SingleStepMatch> match_results_type;
const match_results_type& getResultSet();
void addMatch(SingleStepMatch match);
operator void *();
operator bool() const;
private:
match_results_type resultSet;
};
class InvokeArgs {
typedef std::vector<std::string> args_type;
public:
typedef args_type::size_type size_type;
InvokeArgs() { }
void addArg(const std::string arg);
Table & getVariableTableArg();
template<class T> T getInvokeArg(size_type i) const;
const Table & getTableArg() const;
private:
Table tableArg;
args_type args;
};
enum InvokeResultType {
SUCCESS,
FAILURE,
PENDING
};
class InvokeResult {
private:
InvokeResultType type;
std::string description;
InvokeResult(const InvokeResultType type, const char *description);
public:
InvokeResult();
InvokeResult(const InvokeResult &ir);
InvokeResult& operator= (const InvokeResult& rhs);
static InvokeResult success();
static InvokeResult failure(const char *description);
static InvokeResult failure(const std::string &description);
static InvokeResult pending(const char *description);
bool isSuccess() const;
bool isPending() const;
InvokeResultType getType() const;
const std::string &getDescription() const;
};
class StepInfo : public boost::enable_shared_from_this<StepInfo> {
public:
StepInfo(const std::string &stepMatcher, const std::string source);
SingleStepMatch matches(const std::string &stepDescription) const;
virtual InvokeResult invokeStep(const InvokeArgs * pArgs) const = 0;
step_id_type id;
Regex regex;
const std::string source;
private:
StepInfo& operator=(const StepInfo& other);
};
class BasicStep {
public:
InvokeResult invoke(const InvokeArgs *pArgs);
protected:
typedef const Table table_type;
typedef const Table::hashes_type table_hashes_type;
virtual const InvokeResult invokeStepBody() = 0;
virtual void body() = 0;
void pending(const char *description);
void pending();
template<class T> const T getInvokeArg();
const InvokeArgs *getArgs();
private:
// FIXME: awful hack because of Boost::Test
InvokeResult currentResult;
const InvokeArgs *pArgs;
InvokeArgs::size_type currentArgIndex;
};
template<class T>
class StepInvoker : public StepInfo {
public:
StepInvoker(const std::string &stepMatcher, const std::string source);
InvokeResult invokeStep(const InvokeArgs *args) const;
};
class StepManager {
protected:
typedef std::map<step_id_type, boost::shared_ptr<const StepInfo> > steps_type;
public:
virtual ~StepManager();
void addStep(const boost::shared_ptr<StepInfo>& stepInfo);
MatchResult stepMatches(const std::string &stepDescription) const;
const boost::shared_ptr<const StepInfo>& getStep(step_id_type id);
protected:
steps_type& steps() const;
};
static inline std::string toSourceString(const char *filePath, const int line) {
using namespace std;
stringstream s;
string file(filePath);
string::size_type pos = file.find_last_of("/\\");
if (pos == string::npos) {
s << file;
} else {
s << file.substr(++pos);
}
s << ":" << line;
return s.str();
}
template<class T>
static int registerStep(const std::string &stepMatcher, const char *file, const int line) {
StepManager s;
boost::shared_ptr<StepInfo> stepInfo(boost::make_shared< StepInvoker<T> >(stepMatcher, toSourceString(file, line)));
s.addStep(stepInfo);
return stepInfo->id;
}
template<typename T>
T fromString(const std::string& s) {
std::istringstream stream(s);
T t;
stream >> t;
if (stream.fail()) {
throw std::invalid_argument("Cannot convert parameter");
}
return t;
}
template<>
inline std::string fromString(const std::string& s) {
return s;
}
template<typename T>
std::string toString(T arg) {
std::stringstream s;
s << arg;
return s.str();
}
template<typename T>
T InvokeArgs::getInvokeArg(size_type i) const {
if (i >= args.size()) {
throw std::invalid_argument("Parameter not found");
}
return fromString<T>(args.at(i));
}
template<typename T>
const T BasicStep::getInvokeArg() {
return pArgs->getInvokeArg<T>(currentArgIndex++);
}
template<class T>
StepInvoker<T>::StepInvoker(const std::string &stepMatcher, const std::string source) :
StepInfo(stepMatcher, source) {
}
template<class T>
InvokeResult StepInvoker<T>::invokeStep(const InvokeArgs *pArgs) const {
T t;
return t.invoke(pArgs);
}
}
}
#endif /* CUKE_STEPMANAGER_HPP_ */
<commit_msg>Explain why StepInfo's assignment operator is deleted<commit_after>#ifndef CUKE_STEPMANAGER_HPP_
#define CUKE_STEPMANAGER_HPP_
#include <map>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
#include <boost/enable_shared_from_this.hpp>
#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
using boost::shared_ptr;
#include "../Table.hpp"
#include "../utils/Regex.hpp"
namespace cucumber {
namespace internal {
typedef unsigned int step_id_type;
class StepInfo;
class SingleStepMatch {
public:
typedef RegexMatch::submatches_type submatches_type;
operator const void *() const;
boost::shared_ptr<const StepInfo> stepInfo;
submatches_type submatches;
};
class MatchResult {
public:
typedef std::vector<SingleStepMatch> match_results_type;
const match_results_type& getResultSet();
void addMatch(SingleStepMatch match);
operator void *();
operator bool() const;
private:
match_results_type resultSet;
};
class InvokeArgs {
typedef std::vector<std::string> args_type;
public:
typedef args_type::size_type size_type;
InvokeArgs() { }
void addArg(const std::string arg);
Table & getVariableTableArg();
template<class T> T getInvokeArg(size_type i) const;
const Table & getTableArg() const;
private:
Table tableArg;
args_type args;
};
enum InvokeResultType {
SUCCESS,
FAILURE,
PENDING
};
class InvokeResult {
private:
InvokeResultType type;
std::string description;
InvokeResult(const InvokeResultType type, const char *description);
public:
InvokeResult();
InvokeResult(const InvokeResult &ir);
InvokeResult& operator= (const InvokeResult& rhs);
static InvokeResult success();
static InvokeResult failure(const char *description);
static InvokeResult failure(const std::string &description);
static InvokeResult pending(const char *description);
bool isSuccess() const;
bool isPending() const;
InvokeResultType getType() const;
const std::string &getDescription() const;
};
class StepInfo : public boost::enable_shared_from_this<StepInfo> {
public:
StepInfo(const std::string &stepMatcher, const std::string source);
SingleStepMatch matches(const std::string &stepDescription) const;
virtual InvokeResult invokeStep(const InvokeArgs * pArgs) const = 0;
step_id_type id;
Regex regex;
const std::string source;
private:
// Shut up MSVC warning C4512: assignment operator could not be generated
StepInfo& operator=(const StepInfo& other);
};
class BasicStep {
public:
InvokeResult invoke(const InvokeArgs *pArgs);
protected:
typedef const Table table_type;
typedef const Table::hashes_type table_hashes_type;
virtual const InvokeResult invokeStepBody() = 0;
virtual void body() = 0;
void pending(const char *description);
void pending();
template<class T> const T getInvokeArg();
const InvokeArgs *getArgs();
private:
// FIXME: awful hack because of Boost::Test
InvokeResult currentResult;
const InvokeArgs *pArgs;
InvokeArgs::size_type currentArgIndex;
};
template<class T>
class StepInvoker : public StepInfo {
public:
StepInvoker(const std::string &stepMatcher, const std::string source);
InvokeResult invokeStep(const InvokeArgs *args) const;
};
class StepManager {
protected:
typedef std::map<step_id_type, boost::shared_ptr<const StepInfo> > steps_type;
public:
virtual ~StepManager();
void addStep(const boost::shared_ptr<StepInfo>& stepInfo);
MatchResult stepMatches(const std::string &stepDescription) const;
const boost::shared_ptr<const StepInfo>& getStep(step_id_type id);
protected:
steps_type& steps() const;
};
static inline std::string toSourceString(const char *filePath, const int line) {
using namespace std;
stringstream s;
string file(filePath);
string::size_type pos = file.find_last_of("/\\");
if (pos == string::npos) {
s << file;
} else {
s << file.substr(++pos);
}
s << ":" << line;
return s.str();
}
template<class T>
static int registerStep(const std::string &stepMatcher, const char *file, const int line) {
StepManager s;
boost::shared_ptr<StepInfo> stepInfo(boost::make_shared< StepInvoker<T> >(stepMatcher, toSourceString(file, line)));
s.addStep(stepInfo);
return stepInfo->id;
}
template<typename T>
T fromString(const std::string& s) {
std::istringstream stream(s);
T t;
stream >> t;
if (stream.fail()) {
throw std::invalid_argument("Cannot convert parameter");
}
return t;
}
template<>
inline std::string fromString(const std::string& s) {
return s;
}
template<typename T>
std::string toString(T arg) {
std::stringstream s;
s << arg;
return s.str();
}
template<typename T>
T InvokeArgs::getInvokeArg(size_type i) const {
if (i >= args.size()) {
throw std::invalid_argument("Parameter not found");
}
return fromString<T>(args.at(i));
}
template<typename T>
const T BasicStep::getInvokeArg() {
return pArgs->getInvokeArg<T>(currentArgIndex++);
}
template<class T>
StepInvoker<T>::StepInvoker(const std::string &stepMatcher, const std::string source) :
StepInfo(stepMatcher, source) {
}
template<class T>
InvokeResult StepInvoker<T>::invokeStep(const InvokeArgs *pArgs) const {
T t;
return t.invoke(pArgs);
}
}
}
#endif /* CUKE_STEPMANAGER_HPP_ */
<|endoftext|>
|
<commit_before>#include <gtest/gtest.h>
#include "cyclus.h"
namespace mbmore {
namespace InteractRegionTests {
/*
TEST(StateInstTests, DeployProto) {
std::string config =
"<declared_protos> <val>source</val> </declared_protos>"
"<secret_protos> <val>secret_sink</val> </secret_protos>"
;
int simdur = 6;
cyclus::MockSim sim(cyclus::AgentSpec(":mbmore:StateInst"), config, simdur);
sim.AddSource("source")
.capacity(1)
.Finalize();
sim.AddSink("secret_sink")
.capacity(1)
.Finalize();
int id = sim.Run();
cyclus::SqlStatement::Ptr stmt = sim.db().db().Prepare(
// "SELECT COUNT(*) FROM AgentEntry WHERE Prototype = 'foobar' AND EnterTime = 1;"
"SELECT COUNT(*) FROM AgentEntry WHERE Prototype = 'secret_sink';"
);
stmt->Step();
EXPECT_EQ(1, stmt->GetInt(0));
stmt = sim.db().db().Prepare(
"SELECT COUNT(*) FROM AgentEntry WHERE Prototype = 'secret_sink' AND EnterTime = 4;"
);
stmt->Step();
EXPECT_EQ(1, stmt->GetInt(0));
}
*/
} // namespace InteractRegionTests
} // namespace mbmore<commit_msg>some commented out ideas for tests but I think the right soln is integration tests.<commit_after>#include <gtest/gtest.h>
#include "cyclus.h"
#include "agent_tests.h"
#include "context.h"
#include "facility_tests.h"
namespace mbmore {
namespace InteractRegionTests {
TEST(InteractRegionTests, DeployProto) {
/*
std::string config =
"<pursuit_weights>"
" <item><factor>Enrich</factor> <weight>0.5</weight> </item>"
" <item><factor>Conflict</factor><weight>0.5</weight> </item>"
" </pursuit_weights>"
"<likely_converter> "
" <item>"
" <phase>Pursuit</phase>"
" <function>"
" <name>power</name>"
" <params>"
" <val>3</val>"
" </params>"
" </function>"
" </item>"
"</likely_converter>"
"<p_conflict_relations>"
" <item>"
" <primary_state>StateA</primary_state>"
" <pair_state>"
" <item>"
" <name>StateB</name>"
" <relation>1</relation>"
" </item>"
" </pair_state>"
" </item>"
" <item>"
" <primary_state>StateB</primary_state>"
" <pair_state>"
" <item>"
" <name>StateA</name>"
" <relation>1</relation>"
" </item>"
" </pair_state>"
" </item>"
"</p_conflict_relations>";
int simdur = 1;
cyclus::MockSim sim(cyclus::AgentSpec(":mbmore:StateInst"), config, simdur);
}
*/
/*
TEST(InteractRegionTests, DeployProto) {
std::string config =
"<declared_protos> <val>source</val> </declared_protos>"
"<secret_protos> <val>secret_sink</val> </secret_protos>"
;
int simdur = 6;
cyclus::MockSim sim(cyclus::AgentSpec(":mbmore:StateInst"), config, simdur);
sim.AddSource("source")
.capacity(1)
.Finalize();
sim.AddSink("secret_sink")
.capacity(1)
.Finalize();
int id = sim.Run();
cyclus::SqlStatement::Ptr stmt = sim.db().db().Prepare(
// "SELECT COUNT(*) FROM AgentEntry WHERE Prototype = 'foobar' AND EnterTime = 1;"
"SELECT COUNT(*) FROM AgentEntry WHERE Prototype = 'secret_sink';"
);
stmt->Step();
EXPECT_EQ(1, stmt->GetInt(0));
stmt = sim.db().db().Prepare(
"SELECT COUNT(*) FROM AgentEntry WHERE Prototype = 'secret_sink' AND EnterTime = 4;"
);
stmt->Step();
EXPECT_EQ(1, stmt->GetInt(0));
}
*/
} // namespace InteractRegionTests
} // namespace mbmore<|endoftext|>
|
<commit_before>#pragma once
#ifndef OPENGM_SPACE_BASE_HXX
#define OPENGM_SPACE_BASE_HXX
#include <vector>
#include <limits>
#include <typeinfo>
#include "opengm/opengm.hxx"
namespace opengm {
/// Interface of label spaces
template<class SPACE, class I = std::size_t, class L = std::size_t>
class SpaceBase {
public:
typedef I IndexType;
typedef L LabelType;
IndexType numberOfVariables() const; // must be implemented in Space
LabelType numberOfLabels(const IndexType) const; // must be implemented in Space
template<class Iterator> void assignDense(Iterator, Iterator);
IndexType addVariable(const LabelType);
bool isSimpleSpace() const;
};
template<class SPACE, class I, class L>
inline bool
SpaceBase<SPACE, I, L>::isSimpleSpace() const {
const IndexType numVar = static_cast<SPACE const*>(this)->numberOfVariables();
const IndexType l = static_cast<SPACE const*>(this)->numberOfLabels(0);
for(size_t i=1;i<numVar;++i) {
if(l!=static_cast<SPACE const *>(this)->numberOfLabels(i)) {
return false;
}
}
return true;
}
template<class SPACE, class I, class L>
template<class Iterator>
inline void
SpaceBase<SPACE, I, L>::assignDense
(
Iterator begin,
Iterator end
) {
throw RuntimeError(std::string("assignDense(begin, end) is not implemented in ")+typeid(SPACE).name());
}
template<class SPACE, class I, class L>
inline typename SpaceBase<SPACE, I, L>::IndexType
SpaceBase<SPACE, I, L>::addVariable
(
const LabelType numberOfLabels
) {
throw RuntimeError(std::string("assignDense(begin, end) is not implemented in ")+typeid(SPACE).name());
return IndexType();
}
} // namespace opengm
#endif // #ifndef OPENGM_SPACE_BASE_HXX
<commit_msg>Update space_base.hxx<commit_after>#pragma once
#ifndef OPENGM_SPACE_BASE_HXX
#define OPENGM_SPACE_BASE_HXX
#include <vector>
#include <limits>
#include <typeinfo>
#include "opengm/opengm.hxx"
namespace opengm {
/// Interface of label spaces
template<class SPACE, class I = std::size_t, class L = std::size_t>
class SpaceBase {
public:
typedef I IndexType;
typedef L LabelType;
IndexType numberOfVariables() const; // must be implemented in Space
LabelType numberOfLabels(const IndexType) const; // must be implemented in Space
template<class Iterator> void assignDense(Iterator, Iterator);
IndexType addVariable(const LabelType);
bool isSimpleSpace() const;
};
template<class SPACE, class I, class L>
inline bool
SpaceBase<SPACE, I, L>::isSimpleSpace() const {
const IndexType numVar = static_cast<SPACE const*>(this)->numberOfVariables();
const IndexType l = static_cast<SPACE const*>(this)->numberOfLabels(0);
for(size_t i=1;i<numVar;++i) {
if(l!=static_cast<SPACE const *>(this)->numberOfLabels(i)) {
return false;
}
}
return true;
}
template<class SPACE, class I, class L>
template<class Iterator>
inline void
SpaceBase<SPACE, I, L>::assignDense
(
Iterator begin,
Iterator end
) {
throw RuntimeError(std::string("assignDense(begin, end) is not implemented in ")+typeid(SPACE).name());
}
template<class SPACE, class I, class L>
inline typename SpaceBase<SPACE, I, L>::IndexType
SpaceBase<SPACE, I, L>::addVariable
(
const LabelType numberOfLabels
) {
throw RuntimeError(std::string("addVariable(numberOfLabels) is not implemented in ")+typeid(SPACE).name());
return IndexType();
}
} // namespace opengm
#endif // #ifndef OPENGM_SPACE_BASE_HXX
<|endoftext|>
|
<commit_before>// File: Message_Msg.cxx
// Created: 27.04.01 19:44:52
// Author: OCC Team
// Copyright: Open CASCADE S.A. 2005
#include <Message_Msg.hxx>
#include <Message_MsgFile.hxx>
#include <TCollection_AsciiString.hxx>
#include <stdio.h>
typedef enum
{
Msg_IntegerType,
Msg_RealType,
Msg_StringType,
Msg_IndefiniteType
} FormatType;
//=======================================================================
//function : Message_Msg()
//purpose : Constructor
//=======================================================================
Message_Msg::Message_Msg ()
{}
//=======================================================================
//function : Message_Msg()
//purpose : Constructor
//=======================================================================
Message_Msg::Message_Msg (const Message_Msg& theMsg)
{
myMessageBody = theMsg.myMessageBody;
myOriginal = theMsg.myOriginal;
for ( Standard_Integer i = 1, n = theMsg.mySeqOfFormats.Length(); i <=n; i++ )
mySeqOfFormats.Append ( theMsg.mySeqOfFormats.Value(i) );
}
//=======================================================================
//function : Message_Msg()
//purpose : Constructor
//=======================================================================
Message_Msg::Message_Msg (const Standard_CString theMsgCode)
{
TCollection_AsciiString aKey((char*)theMsgCode);
Set ( Message_MsgFile::Msg(aKey) );
}
//=======================================================================
//function : Message_Msg()
//purpose : Constructor
//=======================================================================
Message_Msg::Message_Msg (const TCollection_ExtendedString& theMsgCode)
{
Set ( Message_MsgFile::Msg(theMsgCode) );
}
//=======================================================================
//function : Set
//purpose :
//=======================================================================
void Message_Msg::Set (const Standard_CString theMsg)
{
TCollection_AsciiString aMsg((char*)theMsg);
Set ( aMsg );
}
//=======================================================================
//function : Set
//purpose :
//=======================================================================
void Message_Msg::Set (const TCollection_ExtendedString& theMsg)
{
myMessageBody = theMsg;
const Standard_ExtString anExtString = myMessageBody.ToExtString();
Standard_Integer anMsgLength = myMessageBody.Length();
for (Standard_Integer i = 0; i < anMsgLength; i++)
{
// Search for '%' character starting a format specification
if (ToCharacter (anExtString[i]) == '%')
{
Standard_Integer aStart = i++;
Standard_Character aChar = ToCharacter (anExtString[i]);
// Check for format '%%'
if (aChar == '%')
{
myMessageBody.Remove (i+1);
if (i >= --anMsgLength) break;
aChar = ToCharacter (anExtString[i]);
}
// Skip flags, field width and precision
while (i < anMsgLength)
{
if (aChar == '-' || aChar == '+' || aChar == ' ' ||
aChar == '#' || (aChar >= '0' && aChar <= '9') || aChar == '.')
i++;
else break;
aChar = ToCharacter (anExtString[i]);
}
if (i >= anMsgLength) break;
FormatType aFormatType;
if (aChar == 'h' || aChar == 'l') aChar = ToCharacter (anExtString[++i]);
switch (aChar) // detect the type of format spec
{
case 'd':
case 'i':
case 'o':
case 'u':
case 'x':
case 'X':
aFormatType = Msg_IntegerType;
break;
case 'f':
case 'e':
case 'E':
case 'g':
case 'G':
aFormatType = Msg_RealType;
break;
case 's':
aFormatType = Msg_StringType;
break;
default:
aFormatType = Msg_IndefiniteType;
continue;
}
mySeqOfFormats.Append (Standard_Integer(aFormatType)); // type
mySeqOfFormats.Append (aStart); // beginning pos
mySeqOfFormats.Append (i + 1 - aStart); // length
}
}
myOriginal = myMessageBody;
}
//=======================================================================
//function : Arg (Standard_CString)
//purpose :
//=======================================================================
Message_Msg& Message_Msg::Arg (const Standard_CString theString)
{
// get location and format
TCollection_AsciiString aFormat;
Standard_Integer aFirst = getFormat ( Msg_StringType, aFormat );
if ( !aFirst )
return *this;
// print string according to format
char * sStringBuffer = new char [Max (strlen(theString)+1, 1024)];
sprintf (sStringBuffer, aFormat.ToCString(), theString);
TCollection_ExtendedString aStr ( sStringBuffer );
delete sStringBuffer;
sStringBuffer = 0;
// replace the format placeholder by the actual string
replaceText ( aFirst, aFormat.Length(), aStr );
return *this;
}
//=======================================================================
//function : Arg (TCollection_ExtendedString)
//purpose :
//remark : This type of string is inserted without conversion (i.e. like %s)
//=======================================================================
Message_Msg& Message_Msg::Arg (const TCollection_ExtendedString& theString)
{
// get location and format
TCollection_AsciiString aFormat;
Standard_Integer aFirst = getFormat ( Msg_StringType, aFormat );
if ( !aFirst )
return *this;
// replace the format placeholder by the actual string
replaceText ( aFirst, aFormat.Length(), theString );
return *this;
}
//=======================================================================
//function : Arg (Standard_Integer)
//purpose :
//=======================================================================
Message_Msg& Message_Msg::Arg (const Standard_Integer theValue)
{
// get location and format
TCollection_AsciiString aFormat;
Standard_Integer aFirst = getFormat ( Msg_IntegerType, aFormat );
if ( !aFirst )
return *this;
// print string according to format
char sStringBuffer [64];
sprintf (sStringBuffer, aFormat.ToCString(), theValue);
TCollection_ExtendedString aStr ( sStringBuffer );
// replace the format placeholder by the actual string
replaceText ( aFirst, aFormat.Length(), aStr );
return *this;
}
//=======================================================================
//function : Arg (Standard_Real)
//purpose :
//=======================================================================
Message_Msg& Message_Msg::Arg (const Standard_Real theValue)
{
// get location and format
TCollection_AsciiString aFormat;
Standard_Integer aFirst = getFormat ( Msg_RealType, aFormat );
if ( !aFirst )
return *this;
// print string according to format
char sStringBuffer [64];
sprintf (sStringBuffer, aFormat.ToCString(), theValue);
TCollection_ExtendedString aStr ( sStringBuffer );
// replace the format placeholder by the actual string
replaceText ( aFirst, aFormat.Length(), aStr );
return *this;
}
//=======================================================================
//function : Get
//purpose : used when the message is dispatched in Message_Messenger
//=======================================================================
const TCollection_ExtendedString& Message_Msg::Get ()
{
// remove all non-initialised format specifications
Standard_Integer i, anIncrement = 0;
static const TCollection_ExtendedString anUnknown ("UNKNOWN");
for (i = 1; i < mySeqOfFormats.Length(); i += 3)
{
TCollection_ExtendedString aRightPart =
myMessageBody.Split(mySeqOfFormats(i+1) + anIncrement);
aRightPart.Remove(1, mySeqOfFormats(i+2));
myMessageBody += anUnknown;
myMessageBody += aRightPart;
anIncrement += (anUnknown.Length() - mySeqOfFormats(i+2));
}
return myMessageBody;
}
//=======================================================================
//function : getFormat
//purpose : Find placeholder in the string where to put next value of
// specified type, return its starting position in the string
// and relevant format string (located at that position).
// The information on returned placeholder is deleted immediately,
// so it will not be found further
// If failed (no placeholder with relevant type found), returns 0
//=======================================================================
Standard_Integer Message_Msg::getFormat (const Standard_Integer theType,
TCollection_AsciiString &theFormat)
{
for (Standard_Integer i = 1; i <= mySeqOfFormats.Length(); i += 3)
if (mySeqOfFormats(i) == theType)
{
// Extract format
Standard_Integer aFirst = mySeqOfFormats(i+1);
Standard_Integer aLen = mySeqOfFormats(i+2);
theFormat = TCollection_AsciiString ( aLen, ' ' );
for ( Standard_Integer j=1; j <= aLen; j++ )
if ( IsAnAscii ( myMessageBody.Value ( aFirst + j ) ) )
theFormat.SetValue ( j, (Standard_Character)myMessageBody.Value ( aFirst + j ) );
// delete information on this placeholder
mySeqOfFormats.Remove (i, i+2);
// return start position
return aFirst + 1;
}
return 0;
}
//=======================================================================
//function : replaceText
//purpose : Replace format text in myMessageBody (theNb chars from theFirst)
// by string theStr
//=======================================================================
void Message_Msg::replaceText (const Standard_Integer theFirst,
const Standard_Integer theNb,
const TCollection_ExtendedString &theStr)
{
myMessageBody.Remove ( theFirst, theNb );
myMessageBody.Insert ( theFirst, theStr );
// update information on remaining format placeholders
Standard_Integer anIncrement = theStr.Length() - theNb;
if ( ! anIncrement ) return;
for ( Standard_Integer i = 1; i <= mySeqOfFormats.Length(); i += 3 )
if ( mySeqOfFormats(i+1) > theFirst )
mySeqOfFormats(i+1) += anIncrement;
}
<commit_msg>[cppcheck-error-fix][mismatch-allocation-deallocation]<commit_after>// File: Message_Msg.cxx
// Created: 27.04.01 19:44:52
// Author: OCC Team
// Copyright: Open CASCADE S.A. 2005
#include <Message_Msg.hxx>
#include <Message_MsgFile.hxx>
#include <TCollection_AsciiString.hxx>
#include <stdio.h>
typedef enum
{
Msg_IntegerType,
Msg_RealType,
Msg_StringType,
Msg_IndefiniteType
} FormatType;
//=======================================================================
//function : Message_Msg()
//purpose : Constructor
//=======================================================================
Message_Msg::Message_Msg ()
{}
//=======================================================================
//function : Message_Msg()
//purpose : Constructor
//=======================================================================
Message_Msg::Message_Msg (const Message_Msg& theMsg)
{
myMessageBody = theMsg.myMessageBody;
myOriginal = theMsg.myOriginal;
for ( Standard_Integer i = 1, n = theMsg.mySeqOfFormats.Length(); i <=n; i++ )
mySeqOfFormats.Append ( theMsg.mySeqOfFormats.Value(i) );
}
//=======================================================================
//function : Message_Msg()
//purpose : Constructor
//=======================================================================
Message_Msg::Message_Msg (const Standard_CString theMsgCode)
{
TCollection_AsciiString aKey((char*)theMsgCode);
Set ( Message_MsgFile::Msg(aKey) );
}
//=======================================================================
//function : Message_Msg()
//purpose : Constructor
//=======================================================================
Message_Msg::Message_Msg (const TCollection_ExtendedString& theMsgCode)
{
Set ( Message_MsgFile::Msg(theMsgCode) );
}
//=======================================================================
//function : Set
//purpose :
//=======================================================================
void Message_Msg::Set (const Standard_CString theMsg)
{
TCollection_AsciiString aMsg((char*)theMsg);
Set ( aMsg );
}
//=======================================================================
//function : Set
//purpose :
//=======================================================================
void Message_Msg::Set (const TCollection_ExtendedString& theMsg)
{
myMessageBody = theMsg;
const Standard_ExtString anExtString = myMessageBody.ToExtString();
Standard_Integer anMsgLength = myMessageBody.Length();
for (Standard_Integer i = 0; i < anMsgLength; i++)
{
// Search for '%' character starting a format specification
if (ToCharacter (anExtString[i]) == '%')
{
Standard_Integer aStart = i++;
Standard_Character aChar = ToCharacter (anExtString[i]);
// Check for format '%%'
if (aChar == '%')
{
myMessageBody.Remove (i+1);
if (i >= --anMsgLength) break;
aChar = ToCharacter (anExtString[i]);
}
// Skip flags, field width and precision
while (i < anMsgLength)
{
if (aChar == '-' || aChar == '+' || aChar == ' ' ||
aChar == '#' || (aChar >= '0' && aChar <= '9') || aChar == '.')
i++;
else break;
aChar = ToCharacter (anExtString[i]);
}
if (i >= anMsgLength) break;
FormatType aFormatType;
if (aChar == 'h' || aChar == 'l') aChar = ToCharacter (anExtString[++i]);
switch (aChar) // detect the type of format spec
{
case 'd':
case 'i':
case 'o':
case 'u':
case 'x':
case 'X':
aFormatType = Msg_IntegerType;
break;
case 'f':
case 'e':
case 'E':
case 'g':
case 'G':
aFormatType = Msg_RealType;
break;
case 's':
aFormatType = Msg_StringType;
break;
default:
aFormatType = Msg_IndefiniteType;
continue;
}
mySeqOfFormats.Append (Standard_Integer(aFormatType)); // type
mySeqOfFormats.Append (aStart); // beginning pos
mySeqOfFormats.Append (i + 1 - aStart); // length
}
}
myOriginal = myMessageBody;
}
//=======================================================================
//function : Arg (Standard_CString)
//purpose :
//=======================================================================
Message_Msg& Message_Msg::Arg (const Standard_CString theString)
{
// get location and format
TCollection_AsciiString aFormat;
Standard_Integer aFirst = getFormat ( Msg_StringType, aFormat );
if ( !aFirst )
return *this;
// print string according to format
char * sStringBuffer = new char [Max (strlen(theString)+1, 1024)];
sprintf (sStringBuffer, aFormat.ToCString(), theString);
TCollection_ExtendedString aStr ( sStringBuffer );
delete [] sStringBuffer;
sStringBuffer = 0;
// replace the format placeholder by the actual string
replaceText ( aFirst, aFormat.Length(), aStr );
return *this;
}
//=======================================================================
//function : Arg (TCollection_ExtendedString)
//purpose :
//remark : This type of string is inserted without conversion (i.e. like %s)
//=======================================================================
Message_Msg& Message_Msg::Arg (const TCollection_ExtendedString& theString)
{
// get location and format
TCollection_AsciiString aFormat;
Standard_Integer aFirst = getFormat ( Msg_StringType, aFormat );
if ( !aFirst )
return *this;
// replace the format placeholder by the actual string
replaceText ( aFirst, aFormat.Length(), theString );
return *this;
}
//=======================================================================
//function : Arg (Standard_Integer)
//purpose :
//=======================================================================
Message_Msg& Message_Msg::Arg (const Standard_Integer theValue)
{
// get location and format
TCollection_AsciiString aFormat;
Standard_Integer aFirst = getFormat ( Msg_IntegerType, aFormat );
if ( !aFirst )
return *this;
// print string according to format
char sStringBuffer [64];
sprintf (sStringBuffer, aFormat.ToCString(), theValue);
TCollection_ExtendedString aStr ( sStringBuffer );
// replace the format placeholder by the actual string
replaceText ( aFirst, aFormat.Length(), aStr );
return *this;
}
//=======================================================================
//function : Arg (Standard_Real)
//purpose :
//=======================================================================
Message_Msg& Message_Msg::Arg (const Standard_Real theValue)
{
// get location and format
TCollection_AsciiString aFormat;
Standard_Integer aFirst = getFormat ( Msg_RealType, aFormat );
if ( !aFirst )
return *this;
// print string according to format
char sStringBuffer [64];
sprintf (sStringBuffer, aFormat.ToCString(), theValue);
TCollection_ExtendedString aStr ( sStringBuffer );
// replace the format placeholder by the actual string
replaceText ( aFirst, aFormat.Length(), aStr );
return *this;
}
//=======================================================================
//function : Get
//purpose : used when the message is dispatched in Message_Messenger
//=======================================================================
const TCollection_ExtendedString& Message_Msg::Get ()
{
// remove all non-initialised format specifications
Standard_Integer i, anIncrement = 0;
static const TCollection_ExtendedString anUnknown ("UNKNOWN");
for (i = 1; i < mySeqOfFormats.Length(); i += 3)
{
TCollection_ExtendedString aRightPart =
myMessageBody.Split(mySeqOfFormats(i+1) + anIncrement);
aRightPart.Remove(1, mySeqOfFormats(i+2));
myMessageBody += anUnknown;
myMessageBody += aRightPart;
anIncrement += (anUnknown.Length() - mySeqOfFormats(i+2));
}
return myMessageBody;
}
//=======================================================================
//function : getFormat
//purpose : Find placeholder in the string where to put next value of
// specified type, return its starting position in the string
// and relevant format string (located at that position).
// The information on returned placeholder is deleted immediately,
// so it will not be found further
// If failed (no placeholder with relevant type found), returns 0
//=======================================================================
Standard_Integer Message_Msg::getFormat (const Standard_Integer theType,
TCollection_AsciiString &theFormat)
{
for (Standard_Integer i = 1; i <= mySeqOfFormats.Length(); i += 3)
if (mySeqOfFormats(i) == theType)
{
// Extract format
Standard_Integer aFirst = mySeqOfFormats(i+1);
Standard_Integer aLen = mySeqOfFormats(i+2);
theFormat = TCollection_AsciiString ( aLen, ' ' );
for ( Standard_Integer j=1; j <= aLen; j++ )
if ( IsAnAscii ( myMessageBody.Value ( aFirst + j ) ) )
theFormat.SetValue ( j, (Standard_Character)myMessageBody.Value ( aFirst + j ) );
// delete information on this placeholder
mySeqOfFormats.Remove (i, i+2);
// return start position
return aFirst + 1;
}
return 0;
}
//=======================================================================
//function : replaceText
//purpose : Replace format text in myMessageBody (theNb chars from theFirst)
// by string theStr
//=======================================================================
void Message_Msg::replaceText (const Standard_Integer theFirst,
const Standard_Integer theNb,
const TCollection_ExtendedString &theStr)
{
myMessageBody.Remove ( theFirst, theNb );
myMessageBody.Insert ( theFirst, theStr );
// update information on remaining format placeholders
Standard_Integer anIncrement = theStr.Length() - theNb;
if ( ! anIncrement ) return;
for ( Standard_Integer i = 1; i <= mySeqOfFormats.Length(); i += 3 )
if ( mySeqOfFormats(i+1) > theFirst )
mySeqOfFormats(i+1) += anIncrement;
}
<|endoftext|>
|
<commit_before>#include <iostream>
using namespace std;
class robot {
public:
Robot() {
}
~Robot() {
}
}
<commit_msg>added robot class<commit_after>#include <iostream>
using namespace std;
class Robot {
public:
Robot(int start_x, int start_y, char start_heading) {
x = start_x;
y = start_y;
heading = start_heading;
}
int getX() {
return x;
}
int getY() {
return y;
}
char getHeading() {
return heading;
}
void setX(int new_x) {
x = new_x;
}
void setY(int new_y) {
y = new_y;
}
void setHeading(char new_heading) {
heading = new_heading;
}
void turnLeft() {
if (heading == 'N') {
heading = 'W';
}
}
void turnRight() {
if (heading == 'N') {
heading = 'E';
}
else if (heading == 'E') {
heading = 'S';
}
}
void moveForward() {
if (heading == 'N') {
y++;
}
else if (heading == 'S') {
y--;
}
}
int x;
int y;
char heading;
};
<|endoftext|>
|
<commit_before>#include <QSettings>
#include <QTranslator>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/project.h>
#include <projectexplorer/target.h>
#include <projectexplorer/task.h>
#include <projectexplorer/buildconfiguration.h>
#include <projectexplorer/buildsteplist.h>
#include <extensionsystem/pluginmanager.h>
#include <projectexplorer/buildmanager.h>
#include <coreplugin/icore.h>
#include "QtcPaneEncodePlugin.h"
#include "OptionsPage.h"
#include "Utils.h"
#include "Constants.h"
using namespace QtcPaneEncode::Internal;
using namespace QtcPaneEncode::Constants;
using namespace Core;
using namespace ProjectExplorer;
using namespace ExtensionSystem;
namespace {
const QString appOutputPaneClassName =
QLatin1String("ProjectExplorer::Internal::AppOutputPane");
}
QtcPaneEncodePlugin::QtcPaneEncodePlugin():
IPlugin()
{
// Create your members
}
QtcPaneEncodePlugin::~QtcPaneEncodePlugin() {
// Unregister objects from the plugin manager's object pool
// Delete members
}
bool QtcPaneEncodePlugin::initialize(const QStringList &arguments, QString *errorString) {
// Register objects in the plugin manager's object pool
// Load settings
// Add actions to menus
// Connect to other plugins' signals
// In the initialize function, a plugin can be sure that the plugins it
// depends on have initialized their members.
Q_UNUSED(arguments)
Q_UNUSED(errorString)
initLanguage();
updateSettings();
OptionsPage *optionsPage = new OptionsPage;
connect(optionsPage, SIGNAL(settingsChanged()), SLOT(updateSettings()));
addAutoReleasedObject(optionsPage);
return true;
}
void QtcPaneEncodePlugin::initLanguage() {
const QString& language = Core::ICore::userInterfaceLanguage();
if (!language.isEmpty()) {
QStringList paths;
paths << ICore::resourcePath () << ICore::userResourcePath();
const QString& trFile = QLatin1String ("QtcPaneEncode_") + language;
QTranslator* translator = new QTranslator (this);
foreach (const QString& path, paths) {
if (translator->load (trFile, path + QLatin1String ("/translations"))) {
qApp->installTranslator (translator);
break;
}
}
}
}
void QtcPaneEncodePlugin::updateSettings() {
Q_ASSERT(Core::ICore::settings() != NULL);
QSettings& settings = *(Core::ICore::settings());
settings.beginGroup(SETTINGS_GROUP);
if(settings.value(SETTINGS_BUILD_ENABLED, false).toBool()) {
buildEncoding_ = settings.value(SETTINGS_BUILD_ENCODING, AUTO_ENCODING).toByteArray();
}
else {
buildEncoding_.clear();
}
if(settings.value(SETTINGS_APP_ENABLED, false).toBool()) {
appEncoding_ = settings.value(SETTINGS_APP_ENCODING, AUTO_ENCODING).toByteArray();
}
else {
appEncoding_.clear();
}
settings.endGroup();
}
void QtcPaneEncodePlugin::extensionsInitialized() {
// Retrieve objects from the plugin manager's object pool
// In the extensionsInitialized function, a plugin can be sure that all
// plugins that depend on it are completely initialized.
// Compiler output
connect(BuildManager::instance(), SIGNAL(buildStateChanged(ProjectExplorer::Project*)),
this, SLOT(handleBuild(ProjectExplorer::Project*)));
connect(this, SIGNAL(newOutput(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)),
BuildManager::instance(), SLOT(addToOutputWindow(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)));
connect(this, SIGNAL(newTask(ProjectExplorer::Task)),
BuildManager::instance(), SLOT(addToTaskWindow(ProjectExplorer::Task)));
// Run control output
QObject *appOutputPane = PluginManager::getObjectByClassName(appOutputPaneClassName);
if(appOutputPane != NULL) {
connect(ProjectExplorerPlugin::instance(), SIGNAL(runControlStarted(ProjectExplorer::RunControl *)),
this, SLOT(handleRunStart(ProjectExplorer::RunControl *)));
connect(this, SIGNAL(newMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)),
appOutputPane, SLOT(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)));
}
else {
qCritical() << "Failed to find appOutputPane";
}
}
ExtensionSystem::IPlugin::ShutdownFlag QtcPaneEncodePlugin::aboutToShutdown() {
// Save settings
// Disconnect from signals that are not needed during shutdown
// Hide UI(if you add UI that is not in the main window directly)
this->disconnect();
return SynchronousShutdown;
}
void QtcPaneEncodePlugin::handleBuild(ProjectExplorer::Project *project) {
if(!BuildManager::isBuilding()) {
return;
}
Target *target = project->activeTarget();
if(target == NULL) {
return;
}
BuildConfiguration* buildCOnfiguration = target->activeBuildConfiguration();
if(buildCOnfiguration == NULL) {
return;
}
QList<Core::Id> stepsIds = buildCOnfiguration->knownStepLists();
foreach(const Core::Id &id, stepsIds) {
BuildStepList *steps = buildCOnfiguration->stepList(id);
if(steps == NULL) {
continue;
}
for(int i = 0, end = steps->count(); i < end; ++i) {
BuildStep *step = steps->at(i);
connect(step, SIGNAL(addOutput(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)),
this, SLOT(addOutput(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)),
Qt::UniqueConnection);
disconnect(step, SIGNAL(addOutput(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)),
BuildManager::instance(), SLOT(addToOutputWindow(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)));
connect(step, SIGNAL(addTask(ProjectExplorer::Task)),
this, SLOT(addTask(ProjectExplorer::Task)),
Qt::UniqueConnection);
disconnect(step, SIGNAL(addTask(ProjectExplorer::Task)),
BuildManager::instance(), SLOT(addToTaskWindow(ProjectExplorer::Task)));
}
}
}
void QtcPaneEncodePlugin::addTask(const Task &task) {
if (buildEncoding_.isEmpty ()) {
emit newTask(task);
return;
}
Task convertedTask = task;
// Unknown charset will be handled like auto-detection request
convertedTask.description = reencode(task.description,
QTextCodec::codecForName(buildEncoding_));
emit newTask(convertedTask);
}
void QtcPaneEncodePlugin::addOutput(const QString &string, BuildStep::OutputFormat format, BuildStep::OutputNewlineSetting newlineSetting) {
if (buildEncoding_.isEmpty ()) {
emit newOutput(string, format, newlineSetting);
return;
}
QString convertedString = reencode(string,
QTextCodec::codecForName(buildEncoding_));
emit newOutput(convertedString, format, newlineSetting);
}
void QtcPaneEncodePlugin::handleRunStart(RunControl *runControl) {
QObject *appOutputPane = PluginManager::getObjectByClassName(appOutputPaneClassName);
if(appOutputPane != NULL) {
connect(runControl, SIGNAL(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)),
this, SLOT(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)),
Qt::UniqueConnection);
disconnect(runControl, SIGNAL(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)),
appOutputPane, SLOT(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)));
}
}
void QtcPaneEncodePlugin::appendMessage(RunControl *rc, const QString &out, Utils::OutputFormat format) {
if (appEncoding_.isEmpty ()) {
emit newMessage(rc, out, format);
return;
}
QString convertedOut = reencode(out, QTextCodec::codecForName(appEncoding_));
emit newMessage(rc, convertedOut, format);
}
Q_EXPORT_PLUGIN2(QtcPaneEncode, QtcPaneEncodePlugin)
<commit_msg>Plugin include added<commit_after>#include <QSettings>
#include <QTranslator>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/project.h>
#include <projectexplorer/target.h>
#include <projectexplorer/task.h>
#include <projectexplorer/buildconfiguration.h>
#include <projectexplorer/buildsteplist.h>
#include <extensionsystem/pluginmanager.h>
#include <projectexplorer/buildmanager.h>
#include <coreplugin/icore.h>
#include <QtPlugin>
#include "QtcPaneEncodePlugin.h"
#include "OptionsPage.h"
#include "Utils.h"
#include "Constants.h"
using namespace QtcPaneEncode::Internal;
using namespace QtcPaneEncode::Constants;
using namespace Core;
using namespace ProjectExplorer;
using namespace ExtensionSystem;
namespace {
const QString appOutputPaneClassName =
QLatin1String("ProjectExplorer::Internal::AppOutputPane");
}
QtcPaneEncodePlugin::QtcPaneEncodePlugin():
IPlugin()
{
// Create your members
}
QtcPaneEncodePlugin::~QtcPaneEncodePlugin() {
// Unregister objects from the plugin manager's object pool
// Delete members
}
bool QtcPaneEncodePlugin::initialize(const QStringList &arguments, QString *errorString) {
// Register objects in the plugin manager's object pool
// Load settings
// Add actions to menus
// Connect to other plugins' signals
// In the initialize function, a plugin can be sure that the plugins it
// depends on have initialized their members.
Q_UNUSED(arguments)
Q_UNUSED(errorString)
initLanguage();
updateSettings();
OptionsPage *optionsPage = new OptionsPage;
connect(optionsPage, SIGNAL(settingsChanged()), SLOT(updateSettings()));
addAutoReleasedObject(optionsPage);
return true;
}
void QtcPaneEncodePlugin::initLanguage() {
const QString& language = Core::ICore::userInterfaceLanguage();
if (!language.isEmpty()) {
QStringList paths;
paths << ICore::resourcePath () << ICore::userResourcePath();
const QString& trFile = QLatin1String ("QtcPaneEncode_") + language;
QTranslator* translator = new QTranslator (this);
foreach (const QString& path, paths) {
if (translator->load (trFile, path + QLatin1String ("/translations"))) {
qApp->installTranslator (translator);
break;
}
}
}
}
void QtcPaneEncodePlugin::updateSettings() {
Q_ASSERT(Core::ICore::settings() != NULL);
QSettings& settings = *(Core::ICore::settings());
settings.beginGroup(SETTINGS_GROUP);
if(settings.value(SETTINGS_BUILD_ENABLED, false).toBool()) {
buildEncoding_ = settings.value(SETTINGS_BUILD_ENCODING, AUTO_ENCODING).toByteArray();
}
else {
buildEncoding_.clear();
}
if(settings.value(SETTINGS_APP_ENABLED, false).toBool()) {
appEncoding_ = settings.value(SETTINGS_APP_ENCODING, AUTO_ENCODING).toByteArray();
}
else {
appEncoding_.clear();
}
settings.endGroup();
}
void QtcPaneEncodePlugin::extensionsInitialized() {
// Retrieve objects from the plugin manager's object pool
// In the extensionsInitialized function, a plugin can be sure that all
// plugins that depend on it are completely initialized.
// Compiler output
connect(BuildManager::instance(), SIGNAL(buildStateChanged(ProjectExplorer::Project*)),
this, SLOT(handleBuild(ProjectExplorer::Project*)));
connect(this, SIGNAL(newOutput(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)),
BuildManager::instance(), SLOT(addToOutputWindow(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)));
connect(this, SIGNAL(newTask(ProjectExplorer::Task)),
BuildManager::instance(), SLOT(addToTaskWindow(ProjectExplorer::Task)));
// Run control output
QObject *appOutputPane = PluginManager::getObjectByClassName(appOutputPaneClassName);
if(appOutputPane != NULL) {
connect(ProjectExplorerPlugin::instance(), SIGNAL(runControlStarted(ProjectExplorer::RunControl *)),
this, SLOT(handleRunStart(ProjectExplorer::RunControl *)));
connect(this, SIGNAL(newMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)),
appOutputPane, SLOT(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)));
}
else {
qCritical() << "Failed to find appOutputPane";
}
}
ExtensionSystem::IPlugin::ShutdownFlag QtcPaneEncodePlugin::aboutToShutdown() {
// Save settings
// Disconnect from signals that are not needed during shutdown
// Hide UI(if you add UI that is not in the main window directly)
this->disconnect();
return SynchronousShutdown;
}
void QtcPaneEncodePlugin::handleBuild(ProjectExplorer::Project *project) {
if(!BuildManager::isBuilding()) {
return;
}
Target *target = project->activeTarget();
if(target == NULL) {
return;
}
BuildConfiguration* buildCOnfiguration = target->activeBuildConfiguration();
if(buildCOnfiguration == NULL) {
return;
}
QList<Core::Id> stepsIds = buildCOnfiguration->knownStepLists();
foreach(const Core::Id &id, stepsIds) {
BuildStepList *steps = buildCOnfiguration->stepList(id);
if(steps == NULL) {
continue;
}
for(int i = 0, end = steps->count(); i < end; ++i) {
BuildStep *step = steps->at(i);
connect(step, SIGNAL(addOutput(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)),
this, SLOT(addOutput(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)),
Qt::UniqueConnection);
disconnect(step, SIGNAL(addOutput(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)),
BuildManager::instance(), SLOT(addToOutputWindow(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)));
connect(step, SIGNAL(addTask(ProjectExplorer::Task)),
this, SLOT(addTask(ProjectExplorer::Task)),
Qt::UniqueConnection);
disconnect(step, SIGNAL(addTask(ProjectExplorer::Task)),
BuildManager::instance(), SLOT(addToTaskWindow(ProjectExplorer::Task)));
}
}
}
void QtcPaneEncodePlugin::addTask(const Task &task) {
if (buildEncoding_.isEmpty ()) {
emit newTask(task);
return;
}
Task convertedTask = task;
// Unknown charset will be handled like auto-detection request
convertedTask.description = reencode(task.description,
QTextCodec::codecForName(buildEncoding_));
emit newTask(convertedTask);
}
void QtcPaneEncodePlugin::addOutput(const QString &string, BuildStep::OutputFormat format, BuildStep::OutputNewlineSetting newlineSetting) {
if (buildEncoding_.isEmpty ()) {
emit newOutput(string, format, newlineSetting);
return;
}
QString convertedString = reencode(string,
QTextCodec::codecForName(buildEncoding_));
emit newOutput(convertedString, format, newlineSetting);
}
void QtcPaneEncodePlugin::handleRunStart(RunControl *runControl) {
QObject *appOutputPane = PluginManager::getObjectByClassName(appOutputPaneClassName);
if(appOutputPane != NULL) {
connect(runControl, SIGNAL(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)),
this, SLOT(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)),
Qt::UniqueConnection);
disconnect(runControl, SIGNAL(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)),
appOutputPane, SLOT(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)));
}
}
void QtcPaneEncodePlugin::appendMessage(RunControl *rc, const QString &out, Utils::OutputFormat format) {
if (appEncoding_.isEmpty ()) {
emit newMessage(rc, out, format);
return;
}
QString convertedOut = reencode(out, QTextCodec::codecForName(appEncoding_));
emit newMessage(rc, convertedOut, format);
}
Q_EXPORT_PLUGIN2(QtcPaneEncode, QtcPaneEncodePlugin)
<|endoftext|>
|
<commit_before>#ifndef Magnum_SceneGraph_Animable_hpp
#define Magnum_SceneGraph_Animable_hpp
/*
Copyright © 2010, 2011, 2012 Vladimír Vondruš <mosra@centrum.cz>
This file is part of Magnum.
Magnum is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License version 3
only, as published by the Free Software Foundation.
Magnum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License version 3 for more details.
*/
/** @file
* @brief @ref compilation-speedup-hpp "Template implementation" for Animable.h and AnimableGroup.h
*/
#include "AnimableGroup.h"
#include "Animable.h"
#include "Timeline.h"
namespace Magnum { namespace SceneGraph {
template<std::uint8_t dimensions, class T> Animable<dimensions, T>::Animable(AbstractObject<dimensions, T>* object, GLfloat duration, AnimableGroup<dimensions, T>* group): AbstractGroupedFeature<dimensions, Animable<dimensions, T>, T>(object, group), _duration(duration), startTime(std::numeric_limits<GLfloat>::infinity()), pauseTime(-std::numeric_limits<GLfloat>::infinity()), previousState(AnimationState::Stopped), currentState(AnimationState::Stopped), _repeated(false), _repeatCount(0), repeats(0) {}
template<std::uint8_t dimensions, class T> Animable<dimensions, T>* Animable<dimensions, T>::setState(AnimationState state) {
if(currentState == state) return this;
/* Not allowed (for sanity) */
if(previousState == AnimationState::Stopped && state == AnimationState::Paused)
return this;
/* Wake up the group in case no animations are running */
group()->wakeUp = true;
currentState = state;
return this;
}
template<std::uint8_t dimensions, class T> AnimableGroup<dimensions, T>* Animable<dimensions, T>::group() {
return static_cast<AnimableGroup<dimensions, T>*>(AbstractGroupedFeature<dimensions, Animable<dimensions, T>, T>::group());
}
template<std::uint8_t dimensions, class T> const AnimableGroup<dimensions, T>* Animable<dimensions, T>::group() const {
return static_cast<const AnimableGroup<dimensions, T>*>(AbstractGroupedFeature<dimensions, Animable<dimensions, T>, T>::group());
}
template<std::uint8_t dimensions, class T> void AnimableGroup<dimensions, T>::step(const GLfloat time, const GLfloat delta) {
if(!_runningCount && !wakeUp) return;
wakeUp = false;
for(std::size_t i = 0; i != this->size(); ++i) {
Animable<dimensions, T>* animable = (*this)[i];
/* The animation was stopped recently, just decrease count of running
animations if the animation was running before */
if(animable->previousState != AnimationState::Stopped && animable->currentState == AnimationState::Stopped) {
if(animable->previousState == AnimationState::Running)
--_runningCount;
animable->previousState = AnimationState::Stopped;
animable->animationStopped();
continue;
/* The animation was paused recently, set pause time to previous frame time */
} else if(animable->previousState == AnimationState::Running && animable->currentState == AnimationState::Paused) {
animable->previousState = AnimationState::Paused;
animable->pauseTime = time;
--_runningCount;
animable->animationPaused();
continue;
/* Skip the rest for not running animations */
} else if(animable->currentState != AnimationState::Running) {
CORRADE_INTERNAL_ASSERT(animable->previousState == animable->currentState);
continue;
/* The animation was started recently, set start time to previous frame time */
} else if(animable->previousState == AnimationState::Stopped) {
animable->previousState = AnimationState::Running;
animable->startTime = time;
++_runningCount;
animable->animationStarted();
/* The animation was resumed recently, add pause duration to start time */
} else if(animable->previousState == AnimationState::Paused) {
animable->previousState = AnimationState::Running;
animable->startTime += time - animable->pauseTime;
++_runningCount;
animable->animationResumed();
}
CORRADE_INTERNAL_ASSERT(animable->previousState == AnimationState::Running);
/* Animation time exceeded duration */
if(animable->_duration != 0.0f && time-animable->startTime > animable->_duration) {
/* Not repeated or repeat count exceeded, stop */
if(!animable->_repeated || animable->repeats+1 == animable->_repeatCount) {
animable->previousState = AnimationState::Stopped;
animable->currentState = AnimationState::Stopped;
--_runningCount;
continue;
}
/* Increase repeat count and add duration to startTime */
++animable->repeats;
animable->startTime += animable->_duration;
}
/* Animation is still running, perform animation step */
CORRADE_ASSERT(time-animable->startTime >= 0.0f,
"SceneGraph::AnimableGroup::step(): animation was started in future - probably wrong time passed", );
CORRADE_ASSERT(delta >= 0.0f,
"SceneGraph::AnimableGroup::step(): negative delta passed", );
animable->animationStep(time - animable->startTime, delta);
}
CORRADE_INTERNAL_ASSERT(_runningCount <= this->size());
}
}}
#endif
<commit_msg>SceneGraph: actually call animationStopped() after duration is exceeded.<commit_after>#ifndef Magnum_SceneGraph_Animable_hpp
#define Magnum_SceneGraph_Animable_hpp
/*
Copyright © 2010, 2011, 2012 Vladimír Vondruš <mosra@centrum.cz>
This file is part of Magnum.
Magnum is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License version 3
only, as published by the Free Software Foundation.
Magnum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License version 3 for more details.
*/
/** @file
* @brief @ref compilation-speedup-hpp "Template implementation" for Animable.h and AnimableGroup.h
*/
#include "AnimableGroup.h"
#include "Animable.h"
#include "Timeline.h"
namespace Magnum { namespace SceneGraph {
template<std::uint8_t dimensions, class T> Animable<dimensions, T>::Animable(AbstractObject<dimensions, T>* object, GLfloat duration, AnimableGroup<dimensions, T>* group): AbstractGroupedFeature<dimensions, Animable<dimensions, T>, T>(object, group), _duration(duration), startTime(std::numeric_limits<GLfloat>::infinity()), pauseTime(-std::numeric_limits<GLfloat>::infinity()), previousState(AnimationState::Stopped), currentState(AnimationState::Stopped), _repeated(false), _repeatCount(0), repeats(0) {}
template<std::uint8_t dimensions, class T> Animable<dimensions, T>* Animable<dimensions, T>::setState(AnimationState state) {
if(currentState == state) return this;
/* Not allowed (for sanity) */
if(previousState == AnimationState::Stopped && state == AnimationState::Paused)
return this;
/* Wake up the group in case no animations are running */
group()->wakeUp = true;
currentState = state;
return this;
}
template<std::uint8_t dimensions, class T> AnimableGroup<dimensions, T>* Animable<dimensions, T>::group() {
return static_cast<AnimableGroup<dimensions, T>*>(AbstractGroupedFeature<dimensions, Animable<dimensions, T>, T>::group());
}
template<std::uint8_t dimensions, class T> const AnimableGroup<dimensions, T>* Animable<dimensions, T>::group() const {
return static_cast<const AnimableGroup<dimensions, T>*>(AbstractGroupedFeature<dimensions, Animable<dimensions, T>, T>::group());
}
template<std::uint8_t dimensions, class T> void AnimableGroup<dimensions, T>::step(const GLfloat time, const GLfloat delta) {
if(!_runningCount && !wakeUp) return;
wakeUp = false;
for(std::size_t i = 0; i != this->size(); ++i) {
Animable<dimensions, T>* animable = (*this)[i];
/* The animation was stopped recently, just decrease count of running
animations if the animation was running before */
if(animable->previousState != AnimationState::Stopped && animable->currentState == AnimationState::Stopped) {
if(animable->previousState == AnimationState::Running)
--_runningCount;
animable->previousState = AnimationState::Stopped;
animable->animationStopped();
continue;
/* The animation was paused recently, set pause time to previous frame time */
} else if(animable->previousState == AnimationState::Running && animable->currentState == AnimationState::Paused) {
animable->previousState = AnimationState::Paused;
animable->pauseTime = time;
--_runningCount;
animable->animationPaused();
continue;
/* Skip the rest for not running animations */
} else if(animable->currentState != AnimationState::Running) {
CORRADE_INTERNAL_ASSERT(animable->previousState == animable->currentState);
continue;
/* The animation was started recently, set start time to previous frame time */
} else if(animable->previousState == AnimationState::Stopped) {
animable->previousState = AnimationState::Running;
animable->startTime = time;
++_runningCount;
animable->animationStarted();
/* The animation was resumed recently, add pause duration to start time */
} else if(animable->previousState == AnimationState::Paused) {
animable->previousState = AnimationState::Running;
animable->startTime += time - animable->pauseTime;
++_runningCount;
animable->animationResumed();
}
CORRADE_INTERNAL_ASSERT(animable->previousState == AnimationState::Running);
/* Animation time exceeded duration */
if(animable->_duration != 0.0f && time-animable->startTime > animable->_duration) {
/* Not repeated or repeat count exceeded, stop */
if(!animable->_repeated || animable->repeats+1 == animable->_repeatCount) {
animable->previousState = AnimationState::Stopped;
animable->currentState = AnimationState::Stopped;
--_runningCount;
animable->animationStopped();
continue;
}
/* Increase repeat count and add duration to startTime */
++animable->repeats;
animable->startTime += animable->_duration;
}
/* Animation is still running, perform animation step */
CORRADE_ASSERT(time-animable->startTime >= 0.0f,
"SceneGraph::AnimableGroup::step(): animation was started in future - probably wrong time passed", );
CORRADE_ASSERT(delta >= 0.0f,
"SceneGraph::AnimableGroup::step(): negative delta passed", );
animable->animationStep(time - animable->startTime, delta);
}
CORRADE_INTERNAL_ASSERT(_runningCount <= this->size());
}
}}
#endif
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <queue>
#include <vector>
#include <utility>
#include <iostream>
#include <string>
#include <stack>
using namespace std;
stack<string> lv1;
stack<string> lv2;
stack<string> lv3;
string temp;
int templv;
int temptime=0;
int usernum;
int users=0;
int read(int now){
if(now < temptime || users>usernum) return 0;
do{
printf("test\n");
if(temp.empty()){
}else{
switch(templv){
case 1:
lv1.push(temp);break;
case 2:
lv2.push(temp);break;
case 3:
lv3.push(temp);break;
}
}
users++;
if(users<=usernum){
cin >>temptime>>templv>>temp;
}
else
return 0;
}while(temptime<=now);
}
int main(int argc, char const *argv[])
{
int time;
scanf("%d%d",&usernum,&time);
for (int i = 0; i < time; ++i)
{
read(i);
cout<<i<<"\n"<<lv1.size()<<lv2.size()<<lv3.size()<<endl;
}
return 0;
}<commit_msg>update uoj2254<commit_after>#include <stdio.h>
#include <queue>
#include <vector>
#include <utility>
#include <iostream>
#include <string>
#include <stack>
#include <queue>
using namespace std;
queue<string> lv1;
queue<string> lv2;
queue<string> lv3;
string temp;
int templv;
int temptime=0;
int usernum;
int users=0;
int read(int now){
if(now < temptime || users>usernum) return 0;
do{
printf("test\n");
if(temp.empty()){
}else{
switch(templv){
case 1:
lv1.push(temp);break;
case 2:
lv2.push(temp);break;
case 3:
lv3.push(temp);break;
}
}
users++;
if(users<=usernum){
cin >>temptime>>templv>>temp;
}
else
return 0;
}while(temptime<=now);
}
int main(int argc, char const *argv[])
{
int time;
scanf("%d%d",&usernum,&time);
for (int i = 0; i < time; ++i)
{
read(i);
cout<<i<<"\n"<<lv1.size()<<lv2.size()<<lv3.size()<<endl;
}
return 0;
}<|endoftext|>
|
<commit_before>#include "stdio.h"
#include "stdlib.h"
#include <iostream>
#define MAXSTRLEN 255 // 用户可在255以内定义最大串长
typedef unsigned char SString[MAXSTRLEN+1]; // 0号单元存放串的长度
void get_next(SString T,int next[]){
int i,j;
next[1]=0;
j=0;
while(i<T[0]){
if(j == 0 || T[i]==T[j]){
++i;
++j;
next[i]=j;}
else{
j=next[j];
}
}
}
int main(){
int next[MAXSTRLEN];
SString S;
int n,i,j;
char ch;
scanf("%d",&n); // 指定要验证NEXT值的字符串个数
ch=getchar();
for(i=1;i<=n;i++)
{
ch=getchar();
for(j=1;j<=MAXSTRLEN&&(ch!='\n');j++) // 录入字符串
{
S[j]=ch;
ch=getchar();
}
S[0]=j-1; // S[0]用于存储字符串中字符个数
//printf("%s",S+1);
get_next(S,next);
printf("NEXT J is:");
for(j=1;j<=S[0];j++)
printf("%d",next[j]);
printf("\n");
}
}
<commit_msg>update uoj8591<commit_after>#include "stdio.h"
#include "stdlib.h"
#include <iostream>
#define MAXSTRLEN 255 // 用户可在255以内定义最大串长
typedef unsigned char SString[MAXSTRLEN+1]; // 0号单元存放串的长度
void get_next(SString T,int next[]){
int i,j;
next[1]=0;
j=0;
while(i<T[0]){
if(j == 0 || T[i]==T[j]){
++i;
++j;
next[i]=j;}
else{
j=next[j];
printf("%d\n ??",j); }
}
}
int main(){
int next[MAXSTRLEN];
SString S;
int n,i,j;
char ch;
scanf("%d",&n); // 指定要验证NEXT值的字符串个数
ch=getchar();
for(i=1;i<=n;i++)
{
ch=getchar();
for(j=1;j<=MAXSTRLEN&&(ch!='\n');j++) // 录入字符串
{
S[j]=ch;
ch=getchar();
}
S[0]=j-1; // S[0]用于存储字符串中字符个数
//printf("%s",S+1);
get_next(S,next);
printf("NEXT J is:");
for(j=1;j<=S[0];j++)
printf("%d",next[j]);
printf("\n");
}
}
<|endoftext|>
|
<commit_before>#include "upgrade.h"
#include "util.h"
#include "init.h"
#include <algorithm>
#include <univalue.h>
#include <vector>
#include <boost/thread.hpp>
#include <boost/filesystem.hpp>
#include <boost/exception/exception.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <ostream>
#include <iostream>
#include <zip.h>
#include <fstream>
#include <openssl/sha.h>
struct_SnapshotExtractStatus ExtractStatus;
bool fCancelOperation = false;
Upgrade::Upgrade()
{
// Clear the structs
DownloadStatus.SnapshotDownloadSize = 0;
DownloadStatus.SnapshotDownloadSpeed = 0;
DownloadStatus.SnapshotDownloadAmount = 0;
DownloadStatus.SnapshotDownloadFailed = false;
DownloadStatus.SnapshotDownloadComplete = false;
DownloadStatus.SnapshotDownloadProgress = 0;
ExtractStatus.SnapshotExtractFailed = false;
ExtractStatus.SnapshotExtractComplete = false;
ExtractStatus.SnapshotExtractProgress = 0;
}
void Upgrade::CheckForLatestUpdate()
{
// If testnet skip this || If the user changes this to disable while wallet running just drop out of here now. (need a way to remove items from scheduler)
if (fTestNet || GetBoolArg("-disableupdatecheck", false))
return;
Http VersionPull;
std::string GithubResponse = "";
std::string VersionResponse = "";
// We receive the response and it's in a json reply
UniValue Response(UniValue::VOBJ);
try
{
VersionResponse = VersionPull.GetLatestVersionResponse();
}
catch (const std::runtime_error& e)
{
LogPrintf("Update Checker: Exception occured while checking for latest update. (%s)", e.what());
return;
}
if (VersionResponse.empty())
{
LogPrintf("Update Checker: No Response from github");
return;
}
std::string GithubReleaseData = "";
std::string GithubReleaseTypeData = "";
std::string GithubReleaseBody = "";
std::string GithubReleaseType = "";
try
{
Response.read(VersionResponse);
// Get the information we need:
// 'body' for information about changes
// 'tag_name' for version
// 'name' for checking if its a mandatory or leisure
GithubReleaseData = find_value(Response, "tag_name").get_str();
GithubReleaseTypeData = find_value(Response, "name").get_str();
GithubReleaseBody = find_value(Response, "body").get_str();
}
catch (std::exception& ex)
{
LogPrintf("Update Checker: Exception occured while parsing json response (%s)", ex.what());
return;
}
if (GithubReleaseTypeData.find("leisure"))
GithubReleaseType = _("leisure");
else if (GithubReleaseTypeData.find("mandatory"))
GithubReleaseType = _("mandatory");
else
GithubReleaseType = _("unknown");
// Parse version data
std::vector<std::string> GithubVersion;
std::vector<int> LocalVersion;
ParseString(GithubReleaseData, '.', GithubVersion);
LocalVersion.push_back(CLIENT_VERSION_MAJOR);
LocalVersion.push_back(CLIENT_VERSION_MINOR);
LocalVersion.push_back(CLIENT_VERSION_REVISION);
if (GithubVersion.size() != 4)
{
LogPrintf("Update Check: Got malformed version (%s)", GithubReleaseData);
return;
}
bool NewVersion = false;
try {
// Left to right version numbers.
// 3 numbers to check for production.
for (unsigned int x = 0; x < 3; x++)
{
if (NewVersion)
break;
if (std::stoi(GithubVersion[x]) > LocalVersion[x])
NewVersion = true;
}
}
catch (std::exception& ex)
{
LogPrintf("Update Check: Exception occured checking client version against github version (%s)", ToString(ex.what()));
return;
}
if (!NewVersion)
return;
// New version was found
std::string ClientMessage = _("Local version: ") + strprintf("%d.%d.%d.%d", CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) + "\r\n";
ClientMessage.append(_("Github version: ") + GithubReleaseData + "\r\n");
ClientMessage.append(_("This update is ") + GithubReleaseType + "\r\n\r\n");
std::string ChangeLog = GithubReleaseBody;
uiInterface.UpdateMessageBox(ClientMessage, ChangeLog);
return;
}
void Upgrade::SnapshotMain()
{
std::cout << std::endl;
std::cout << _("Snapshot Process Has Begun.") << std::endl;
std::cout << _("Warning: Ending this process after Stage 2 will result in syncing from 0 or an incomplete/corrupted blockchain.") << std::endl << std::endl;
// Create a thread for snapshot to be downloaded
boost::thread SnapshotDownloadThread(std::bind(&Upgrade::DownloadSnapshot, this));
Progress Prog;
Prog.SetType(0);
while (!DownloadStatus.SnapshotDownloadComplete)
{
if (DownloadStatus.SnapshotDownloadFailed)
throw std::runtime_error("Failed to download snapshot.zip; See debug.log");
if (Prog.Update(DownloadStatus.SnapshotDownloadProgress, DownloadStatus.SnapshotDownloadSpeed, DownloadStatus.SnapshotDownloadAmount, DownloadStatus.SnapshotDownloadSize))
std::cout << Prog.Status() << std::flush;
MilliSleep(1000);
}
// This is needed in some spots as the download can complete before the next progress update occurs so just 100% here as it was successful
if (Prog.Update(100, -1, DownloadStatus.SnapshotDownloadSize, DownloadStatus.SnapshotDownloadSize))
std::cout << Prog.Status() << std::flush;
std::cout << std::endl;
Prog.SetType(1);
if (VerifySHA256SUM())
{
Prog.Update(100);
std::cout << Prog.Status() << std::flush;
}
else
throw std::runtime_error("Failed to verify SHA256SUM of snapshot.zip; See debug.log");
std::cout << std::endl;
Prog.SetType(2);
if (CleanupBlockchainData())
{
Prog.Update(100);
std::cout << Prog.Status() << std::flush;
}
else
throw std::runtime_error("Failed to Cleanup previous blockchain data; See debug.log");
std::cout << std::endl;
Prog.SetType(3);
// Create a thread for snapshot to be extracted
boost::thread SnapshotExtractThread(std::bind(&Upgrade::ExtractSnapshot, this));
while (!ExtractStatus.SnapshotExtractComplete)
{
if (ExtractStatus.SnapshotExtractFailed)
{
// Do this without checking on sucess, If it passed in stage 3 it will pass here.
CleanupBlockchainData();
throw std::runtime_error("Failed to extract snapshot.zip; See debug.log");
}
if (Prog.Update(ExtractStatus.SnapshotExtractProgress))
std::cout << Prog.Status() << std::flush;
MilliSleep(1000);
}
if (Prog.Update(100))
std::cout << Prog.Status() << std::flush;
std::cout << std::endl;
std::cout << _("Snapshot Process Complete!") << std::endl;
return;
}
void Upgrade::DownloadSnapshot()
{
// Download the snapshot.zip
Http HTTPHandler;
try
{
HTTPHandler.DownloadSnapshot();
}
catch(std::runtime_error& e)
{
LogPrintf("Snapshot Downloader: Exception occured while attempting to download snapshot (%s)", e.what());
DownloadStatus.SnapshotDownloadFailed = true;
}
return;
}
bool Upgrade::VerifySHA256SUM()
{
Http HTTPHandler;
std::string ServerSHA256SUM = "";
try
{
ServerSHA256SUM = HTTPHandler.GetSnapshotSHA256();
}
catch (std::runtime_error& e)
{
LogPrintf("Snapshot (VerifySHA256SUM): Exception occured while attempting to retrieve snapshot SHA256SUM (%s)", e.what());
}
if (ServerSHA256SUM.empty())
{
LogPrintf("Snapshot (VerifySHA256SUM): Empty sha256sum returned from server");
return false;
}
unsigned char digest[SHA256_DIGEST_LENGTH];
SHA256_CTX ctx;
SHA256_Init(&ctx);
boost::filesystem::path fileloc = GetDataDir() / "snapshot.zip";
unsigned char *buffer[32768];
int bytesread = 0;
FILE *file = fsbridge::fopen(fileloc, "rb");
if (!file)
{
LogPrintf("Snapshot (VerifySHA256SUM): Failed to open snapshot.zip");
return false;
}
while ((bytesread = fread(buffer, 1, sizeof(buffer), file)))
SHA256_Update(&ctx, buffer, bytesread);
SHA256_Final(digest, &ctx);
char mdString[SHA256_DIGEST_LENGTH*2+1];
for (int i = 0; i < SHA256_DIGEST_LENGTH; i++)
sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]);
std::string FileSHA256SUM = {mdString};
fclose(file);
if (ServerSHA256SUM == FileSHA256SUM)
return true;
else
{
LogPrintf("Snapshot (VerifySHA256SUM): Mismatch of sha256sum of snapshot.zip (Server = %s / File = %s)", ServerSHA256SUM, FileSHA256SUM);
return false;
}
}
bool Upgrade::CleanupBlockchainData()
{
boost::filesystem::path CleanupPath = GetDataDir();
// We must delete previous blockchain data
// txleveldb
// blk*.dat
boost::filesystem::directory_iterator IterEnd;
try
{
// Remove the files. We iterate as we know blk* will exist more and more in future as well
for (boost::filesystem::directory_iterator Iter(CleanupPath); Iter != IterEnd; ++Iter)
{
if (boost::filesystem::is_directory(Iter->path()))
{
size_t DirLoc = Iter->path().string().find("txleveldb");
if (DirLoc != std::string::npos)
if (!boost::filesystem::remove_all(*Iter))
return false;
continue;
}
else if (boost::filesystem::is_regular_file(*Iter))
{
size_t FileLoc = Iter->path().filename().string().find("blk");
if (FileLoc != std::string::npos)
{
std::string filetocheck = Iter->path().filename().string();
// Check it ends with .dat and starts with blk
if (filetocheck.substr(0, 3) == "blk" && filetocheck.substr(filetocheck.length() - 4, 4) == ".dat")
if (!boost::filesystem::remove(*Iter))
return false;
}
continue;
}
}
}
catch (boost::filesystem::filesystem_error &ex)
{
LogPrintf("Snapshot (CleanupBlockchainData): Exception occured: %s", ex.what());
return false;
}
return true;
}
bool Upgrade::ExtractSnapshot()
{
std::string ArchiveFileString = GetDataDir().string() + "/snapshot.zip";
const char* ArchiveFile = ArchiveFileString.c_str();
boost::filesystem::path ExtractPath = GetDataDir();
struct zip* ZipArchive;
struct zip_file* ZipFile;
struct zip_stat ZipStat;
char Buf[1024*1024];
int err;
uint64_t i, j;
int64_t entries, len, sum;
long long totaluncompressedsize = 0;
long long currentuncompressedsize = 0;
int64_t lastupdated = GetAdjustedTime();
try
{
ZipArchive = zip_open(ArchiveFile, 0, &err);
if (ZipArchive == nullptr)
{
zip_error_to_str(Buf, sizeof(Buf), err, errno);
ExtractStatus.SnapshotExtractFailed = true;
LogPrintf("Snapshot (ExtractSnapshot): Error opening snapshot.zip: %s", Buf);
return false;
}
entries = zip_get_num_entries(ZipArchive, 0);
// Lets scan for total size uncompressed so we can do a detailed progress for the watching user
for (j = 0; j < (uint64_t)entries; j++)
{
if (zip_stat_index(ZipArchive, j, 0, &ZipStat) == 0)
{
if (ZipStat.name[strlen(ZipStat.name) - 1] != '/')
totaluncompressedsize += ZipStat.size;
}
}
// Now extract
for (i = 0; i < (uint64_t)entries; i++)
{
if (zip_stat_index(ZipArchive, i, 0, &ZipStat) == 0)
{
// Does this require a directory
if (ZipStat.name[strlen(ZipStat.name) - 1] == '/')
boost::filesystem::create_directory(ExtractPath / ZipStat.name);
else
{
ZipFile = zip_fopen_index(ZipArchive, i, 0);
if (!ZipFile)
{
ExtractStatus.SnapshotExtractFailed = true;
LogPrintf("Snapshot (ExtractSnapshot): Error opening file %s within snapshot.zip", ZipStat.name);
return false;
}
boost::filesystem::path ExtractFileString = ExtractPath / ZipStat.name;
FILE* ExtractFile = fsbridge::fopen(ExtractFileString, "wb");
if (!ExtractFile)
{
ExtractStatus.SnapshotExtractFailed = true;
LogPrintf("Snapshot (ExtractSnapshot): Error opening file %s on filesystem", ZipStat.name);
return false;
}
sum = 0;
while ((uint64_t)sum != ZipStat.size)
{
boost::this_thread::interruption_point();
len = zip_fread(ZipFile, Buf, 1024*1024);
if (len < 0)
{
ExtractStatus.SnapshotExtractFailed = true;
LogPrintf("Snapshot (ExtractSnapshot): Failed to read zip buffer");
return false;
}
fwrite(Buf, 1, (uint64_t)len, ExtractFile);
sum += len;
currentuncompressedsize += len;
// Update Progress every 1 second
if (GetAdjustedTime() > lastupdated)
{
lastupdated = GetAdjustedTime();
ExtractStatus.SnapshotExtractProgress = ((currentuncompressedsize / (double)totaluncompressedsize) * 100);
}
}
fclose(ExtractFile);
zip_fclose(ZipFile);
}
}
}
if (zip_close(ZipArchive) == -1)
{
ExtractStatus.SnapshotExtractFailed = true;
LogPrintf("Sanpshot (ExtractSnapshot): Failed to close snapshot.zip");
return false;
}
ExtractStatus.SnapshotExtractComplete = true;
}
catch (boost::thread_interrupted&)
{
return false;
}
return true;
}
void Upgrade::DeleteSnapshot()
{
// File is out of scope now check if it exists and if so delete it.
// This covers partial downloaded files or a http response downloaded into file.
std::string snapshotfile = GetArg("-snapshoturl", "https://download.gridcoin.us/download/downloadstake/signed/snapshot.zip");
size_t pos = snapshotfile.find_last_of("/");
snapshotfile = snapshotfile.substr(pos + 1, (snapshotfile.length() - pos - 1));
try
{
boost::filesystem::path snapshotpath = GetDataDir() / snapshotfile;
if (boost::filesystem::exists(snapshotpath))
if (boost::filesystem::is_regular_file(snapshotpath))
boost::filesystem::remove(snapshotpath);
}
catch (boost::filesystem::filesystem_error& e)
{
LogPrintf("Snapshot Downloader: Exception occured while attempting to delete snapshot (%s)", e.code().message());
}
}
<commit_msg>Delete snapshot.zip<commit_after>#include "upgrade.h"
#include "util.h"
#include "init.h"
#include <algorithm>
#include <univalue.h>
#include <vector>
#include <boost/thread.hpp>
#include <boost/filesystem.hpp>
#include <boost/exception/exception.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <ostream>
#include <iostream>
#include <zip.h>
#include <fstream>
#include <openssl/sha.h>
struct_SnapshotExtractStatus ExtractStatus;
bool fCancelOperation = false;
Upgrade::Upgrade()
{
// Clear the structs
DownloadStatus.SnapshotDownloadSize = 0;
DownloadStatus.SnapshotDownloadSpeed = 0;
DownloadStatus.SnapshotDownloadAmount = 0;
DownloadStatus.SnapshotDownloadFailed = false;
DownloadStatus.SnapshotDownloadComplete = false;
DownloadStatus.SnapshotDownloadProgress = 0;
ExtractStatus.SnapshotExtractFailed = false;
ExtractStatus.SnapshotExtractComplete = false;
ExtractStatus.SnapshotExtractProgress = 0;
}
void Upgrade::CheckForLatestUpdate()
{
// If testnet skip this || If the user changes this to disable while wallet running just drop out of here now. (need a way to remove items from scheduler)
if (fTestNet || GetBoolArg("-disableupdatecheck", false))
return;
Http VersionPull;
std::string GithubResponse = "";
std::string VersionResponse = "";
// We receive the response and it's in a json reply
UniValue Response(UniValue::VOBJ);
try
{
VersionResponse = VersionPull.GetLatestVersionResponse();
}
catch (const std::runtime_error& e)
{
LogPrintf("Update Checker: Exception occured while checking for latest update. (%s)", e.what());
return;
}
if (VersionResponse.empty())
{
LogPrintf("Update Checker: No Response from github");
return;
}
std::string GithubReleaseData = "";
std::string GithubReleaseTypeData = "";
std::string GithubReleaseBody = "";
std::string GithubReleaseType = "";
try
{
Response.read(VersionResponse);
// Get the information we need:
// 'body' for information about changes
// 'tag_name' for version
// 'name' for checking if its a mandatory or leisure
GithubReleaseData = find_value(Response, "tag_name").get_str();
GithubReleaseTypeData = find_value(Response, "name").get_str();
GithubReleaseBody = find_value(Response, "body").get_str();
}
catch (std::exception& ex)
{
LogPrintf("Update Checker: Exception occured while parsing json response (%s)", ex.what());
return;
}
if (GithubReleaseTypeData.find("leisure"))
GithubReleaseType = _("leisure");
else if (GithubReleaseTypeData.find("mandatory"))
GithubReleaseType = _("mandatory");
else
GithubReleaseType = _("unknown");
// Parse version data
std::vector<std::string> GithubVersion;
std::vector<int> LocalVersion;
ParseString(GithubReleaseData, '.', GithubVersion);
LocalVersion.push_back(CLIENT_VERSION_MAJOR);
LocalVersion.push_back(CLIENT_VERSION_MINOR);
LocalVersion.push_back(CLIENT_VERSION_REVISION);
if (GithubVersion.size() != 4)
{
LogPrintf("Update Check: Got malformed version (%s)", GithubReleaseData);
return;
}
bool NewVersion = false;
try {
// Left to right version numbers.
// 3 numbers to check for production.
for (unsigned int x = 0; x < 3; x++)
{
if (NewVersion)
break;
if (std::stoi(GithubVersion[x]) > LocalVersion[x])
NewVersion = true;
}
}
catch (std::exception& ex)
{
LogPrintf("Update Check: Exception occured checking client version against github version (%s)", ToString(ex.what()));
return;
}
if (!NewVersion)
return;
// New version was found
std::string ClientMessage = _("Local version: ") + strprintf("%d.%d.%d.%d", CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) + "\r\n";
ClientMessage.append(_("Github version: ") + GithubReleaseData + "\r\n");
ClientMessage.append(_("This update is ") + GithubReleaseType + "\r\n\r\n");
std::string ChangeLog = GithubReleaseBody;
uiInterface.UpdateMessageBox(ClientMessage, ChangeLog);
return;
}
void Upgrade::SnapshotMain()
{
std::cout << std::endl;
std::cout << _("Snapshot Process Has Begun.") << std::endl;
std::cout << _("Warning: Ending this process after Stage 2 will result in syncing from 0 or an incomplete/corrupted blockchain.") << std::endl << std::endl;
// Create a thread for snapshot to be downloaded
boost::thread SnapshotDownloadThread(std::bind(&Upgrade::DownloadSnapshot, this));
Progress Prog;
Prog.SetType(0);
while (!DownloadStatus.SnapshotDownloadComplete)
{
if (DownloadStatus.SnapshotDownloadFailed)
throw std::runtime_error("Failed to download snapshot.zip; See debug.log");
if (Prog.Update(DownloadStatus.SnapshotDownloadProgress, DownloadStatus.SnapshotDownloadSpeed, DownloadStatus.SnapshotDownloadAmount, DownloadStatus.SnapshotDownloadSize))
std::cout << Prog.Status() << std::flush;
MilliSleep(1000);
}
// This is needed in some spots as the download can complete before the next progress update occurs so just 100% here as it was successful
if (Prog.Update(100, -1, DownloadStatus.SnapshotDownloadSize, DownloadStatus.SnapshotDownloadSize))
std::cout << Prog.Status() << std::flush;
std::cout << std::endl;
Prog.SetType(1);
if (VerifySHA256SUM())
{
Prog.Update(100);
std::cout << Prog.Status() << std::flush;
}
else
throw std::runtime_error("Failed to verify SHA256SUM of snapshot.zip; See debug.log");
std::cout << std::endl;
Prog.SetType(2);
if (CleanupBlockchainData())
{
Prog.Update(100);
std::cout << Prog.Status() << std::flush;
}
else
throw std::runtime_error("Failed to Cleanup previous blockchain data; See debug.log");
std::cout << std::endl;
Prog.SetType(3);
// Create a thread for snapshot to be extracted
boost::thread SnapshotExtractThread(std::bind(&Upgrade::ExtractSnapshot, this));
while (!ExtractStatus.SnapshotExtractComplete)
{
if (ExtractStatus.SnapshotExtractFailed)
{
// Do this without checking on sucess, If it passed in stage 3 it will pass here.
CleanupBlockchainData();
throw std::runtime_error("Failed to extract snapshot.zip; See debug.log");
}
if (Prog.Update(ExtractStatus.SnapshotExtractProgress))
std::cout << Prog.Status() << std::flush;
MilliSleep(1000);
}
if (Prog.Update(100))
std::cout << Prog.Status() << std::flush;
std::cout << std::endl;
std::cout << _("Snapshot Process Complete!") << std::endl;
return;
}
void Upgrade::DownloadSnapshot()
{
// Download the snapshot.zip
Http HTTPHandler;
try
{
HTTPHandler.DownloadSnapshot();
}
catch(std::runtime_error& e)
{
LogPrintf("Snapshot Downloader: Exception occured while attempting to download snapshot (%s)", e.what());
DownloadStatus.SnapshotDownloadFailed = true;
}
return;
}
bool Upgrade::VerifySHA256SUM()
{
Http HTTPHandler;
std::string ServerSHA256SUM = "";
try
{
ServerSHA256SUM = HTTPHandler.GetSnapshotSHA256();
}
catch (std::runtime_error& e)
{
LogPrintf("Snapshot (VerifySHA256SUM): Exception occured while attempting to retrieve snapshot SHA256SUM (%s)", e.what());
}
if (ServerSHA256SUM.empty())
{
LogPrintf("Snapshot (VerifySHA256SUM): Empty sha256sum returned from server");
return false;
}
unsigned char digest[SHA256_DIGEST_LENGTH];
SHA256_CTX ctx;
SHA256_Init(&ctx);
boost::filesystem::path fileloc = GetDataDir() / "snapshot.zip";
unsigned char *buffer[32768];
int bytesread = 0;
FILE *file = fsbridge::fopen(fileloc, "rb");
if (!file)
{
LogPrintf("Snapshot (VerifySHA256SUM): Failed to open snapshot.zip");
return false;
}
while ((bytesread = fread(buffer, 1, sizeof(buffer), file)))
SHA256_Update(&ctx, buffer, bytesread);
SHA256_Final(digest, &ctx);
char mdString[SHA256_DIGEST_LENGTH*2+1];
for (int i = 0; i < SHA256_DIGEST_LENGTH; i++)
sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]);
std::string FileSHA256SUM = {mdString};
fclose(file);
if (ServerSHA256SUM == FileSHA256SUM)
return true;
else
{
LogPrintf("Snapshot (VerifySHA256SUM): Mismatch of sha256sum of snapshot.zip (Server = %s / File = %s)", ServerSHA256SUM, FileSHA256SUM);
return false;
}
}
bool Upgrade::CleanupBlockchainData()
{
boost::filesystem::path CleanupPath = GetDataDir();
// We must delete previous blockchain data
// txleveldb
// blk*.dat
boost::filesystem::directory_iterator IterEnd;
try
{
// Remove the files. We iterate as we know blk* will exist more and more in future as well
for (boost::filesystem::directory_iterator Iter(CleanupPath); Iter != IterEnd; ++Iter)
{
if (boost::filesystem::is_directory(Iter->path()))
{
size_t DirLoc = Iter->path().string().find("txleveldb");
if (DirLoc != std::string::npos)
if (!boost::filesystem::remove_all(*Iter))
return false;
continue;
}
else if (boost::filesystem::is_regular_file(*Iter))
{
size_t FileLoc = Iter->path().filename().string().find("blk");
if (FileLoc != std::string::npos)
{
std::string filetocheck = Iter->path().filename().string();
// Check it ends with .dat and starts with blk
if (filetocheck.substr(0, 3) == "blk" && filetocheck.substr(filetocheck.length() - 4, 4) == ".dat")
if (!boost::filesystem::remove(*Iter))
return false;
}
continue;
}
}
}
catch (boost::filesystem::filesystem_error &ex)
{
LogPrintf("Snapshot (CleanupBlockchainData): Exception occured: %s", ex.what());
return false;
}
return true;
}
bool Upgrade::ExtractSnapshot()
{
std::string ArchiveFileString = GetDataDir().string() + "/snapshot.zip";
const char* ArchiveFile = ArchiveFileString.c_str();
boost::filesystem::path ExtractPath = GetDataDir();
struct zip* ZipArchive;
struct zip_file* ZipFile;
struct zip_stat ZipStat;
char Buf[1024*1024];
int err;
uint64_t i, j;
int64_t entries, len, sum;
long long totaluncompressedsize = 0;
long long currentuncompressedsize = 0;
int64_t lastupdated = GetAdjustedTime();
try
{
ZipArchive = zip_open(ArchiveFile, 0, &err);
if (ZipArchive == nullptr)
{
zip_error_to_str(Buf, sizeof(Buf), err, errno);
ExtractStatus.SnapshotExtractFailed = true;
LogPrintf("Snapshot (ExtractSnapshot): Error opening snapshot.zip: %s", Buf);
return false;
}
entries = zip_get_num_entries(ZipArchive, 0);
// Lets scan for total size uncompressed so we can do a detailed progress for the watching user
for (j = 0; j < (uint64_t)entries; j++)
{
if (zip_stat_index(ZipArchive, j, 0, &ZipStat) == 0)
{
if (ZipStat.name[strlen(ZipStat.name) - 1] != '/')
totaluncompressedsize += ZipStat.size;
}
}
// Now extract
for (i = 0; i < (uint64_t)entries; i++)
{
if (zip_stat_index(ZipArchive, i, 0, &ZipStat) == 0)
{
// Does this require a directory
if (ZipStat.name[strlen(ZipStat.name) - 1] == '/')
boost::filesystem::create_directory(ExtractPath / ZipStat.name);
else
{
ZipFile = zip_fopen_index(ZipArchive, i, 0);
if (!ZipFile)
{
ExtractStatus.SnapshotExtractFailed = true;
LogPrintf("Snapshot (ExtractSnapshot): Error opening file %s within snapshot.zip", ZipStat.name);
return false;
}
boost::filesystem::path ExtractFileString = ExtractPath / ZipStat.name;
FILE* ExtractFile = fsbridge::fopen(ExtractFileString, "wb");
if (!ExtractFile)
{
ExtractStatus.SnapshotExtractFailed = true;
LogPrintf("Snapshot (ExtractSnapshot): Error opening file %s on filesystem", ZipStat.name);
return false;
}
sum = 0;
while ((uint64_t)sum != ZipStat.size)
{
boost::this_thread::interruption_point();
len = zip_fread(ZipFile, Buf, 1024*1024);
if (len < 0)
{
ExtractStatus.SnapshotExtractFailed = true;
LogPrintf("Snapshot (ExtractSnapshot): Failed to read zip buffer");
return false;
}
fwrite(Buf, 1, (uint64_t)len, ExtractFile);
sum += len;
currentuncompressedsize += len;
// Update Progress every 1 second
if (GetAdjustedTime() > lastupdated)
{
lastupdated = GetAdjustedTime();
ExtractStatus.SnapshotExtractProgress = ((currentuncompressedsize / (double)totaluncompressedsize) * 100);
}
}
fclose(ExtractFile);
zip_fclose(ZipFile);
}
}
}
if (zip_close(ZipArchive) == -1)
{
ExtractStatus.SnapshotExtractFailed = true;
LogPrintf("Sanpshot (ExtractSnapshot): Failed to close snapshot.zip");
return false;
}
ExtractStatus.SnapshotExtractComplete = true;
}
catch (boost::thread_interrupted&)
{
return false;
}
return true;
}
void Upgrade::DeleteSnapshot()
{
// File is out of scope now check if it exists and if so delete it.
try
{
boost::filesystem::path snapshotpath = GetDataDir() / "snapshot.zip";
if (boost::filesystem::exists(snapshotpath))
if (boost::filesystem::is_regular_file(snapshotpath))
boost::filesystem::remove(snapshotpath);
}
catch (boost::filesystem::filesystem_error& e)
{
LogPrintf("Snapshot Downloader: Exception occured while attempting to delete snapshot (%s)", e.code().message());
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: bulmaper.cxx,v $
* $Revision: 1.9 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#ifdef SD_DLLIMPLEMENTATION
#undef SD_DLLIMPLEMENTATION
#endif
#ifndef _SVX_SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
//-> Fonts & Items
#include <vcl/font.hxx>
#include <svx/fontitem.hxx>
#include <svx/fhgtitem.hxx>
#include <svx/wghtitem.hxx>
#include <svx/udlnitem.hxx>
#include <svx/crsditem.hxx>
#include <svx/postitem.hxx>
#include <svx/cntritem.hxx>
#include <svx/shdditem.hxx>
//<- Fonts & Items
#include <svx/bulitem.hxx>
#include <svx/brshitem.hxx>
#include <vcl/graph.hxx>
#include <svtools/itemset.hxx>
#include <svtools/itempool.hxx>
#include <svx/numitem.hxx>
#include <svx/eeitem.hxx>
#include "bulmaper.hxx"
#define GetWhich(nSlot) rSet.GetPool()->GetWhich( nSlot )
void SdBulletMapper::PreMapNumBulletForDialog( SfxItemSet& rSet )
{
if( SFX_ITEM_SET == rSet.GetItemState( EE_PARA_NUMBULLET, FALSE ) )
{
SvxNumRule* pRule = ((SvxNumBulletItem*)rSet.GetItem( EE_PARA_NUMBULLET ))->GetNumRule();
if(pRule && pRule->GetNumRuleType() == SVX_RULETYPE_PRESENTATION_NUMBERING)
{
// 10er Bullet Item auf 9er Item mappen
SvxNumRule aNewRule( pRule->GetFeatureFlags(), 9, FALSE, SVX_RULETYPE_PRESENTATION_NUMBERING );
for( USHORT i = 0; i < 9; i++ )
aNewRule.SetLevel(i, pRule->GetLevel(i+1));
rSet.Put( SvxNumBulletItem( aNewRule, EE_PARA_NUMBULLET ) );
}
}
}
void SdBulletMapper::PostMapNumBulletForDialog( SfxItemSet& rSet )
{
if( SFX_ITEM_SET == rSet.GetItemState( EE_PARA_NUMBULLET, FALSE ) )
{
SvxNumRule* pRule = ((SvxNumBulletItem*)rSet.GetItem( EE_PARA_NUMBULLET ))->GetNumRule();
if(pRule)
{
pRule->UnLinkGraphics();
if(pRule->GetNumRuleType() == SVX_RULETYPE_PRESENTATION_NUMBERING)
{
// 9er Bullet Item auf 10er Item mappen
SvxNumRule aNewRule( pRule->GetFeatureFlags(), 10, FALSE, SVX_RULETYPE_PRESENTATION_NUMBERING );
for( USHORT i = 0; i < 9; i++ )
aNewRule.SetLevel(i+1, pRule->GetLevel(i));
rSet.Put( SvxNumBulletItem( aNewRule, EE_PARA_NUMBULLET ) );
}
}
}
}
void SdBulletMapper::MapFontsInNumRule( SvxNumRule& aNumRule, const SfxItemSet& rSet )
{
const USHORT nCount = aNumRule.GetLevelCount();
for( USHORT nLevel = 0; nLevel < nCount; nLevel++ )
{
const SvxNumberFormat& rSrcLevel = aNumRule.GetLevel(nLevel);
SvxNumberFormat aNewLevel( rSrcLevel );
if(rSrcLevel.GetNumberingType() != com::sun::star::style::NumberingType::CHAR_SPECIAL &&
rSrcLevel.GetNumberingType() != com::sun::star::style::NumberingType::NUMBER_NONE )
{
// wenn Aufzaehlung statt Bullet gewaehlt wurde, wird der Bullet-Font
// dem Vorlagen-Font angeglichen
// to be implemented if module supports CJK
long nFontID = SID_ATTR_CHAR_FONT;
long nFontHeightID = SID_ATTR_CHAR_FONTHEIGHT;
long nWeightID = SID_ATTR_CHAR_WEIGHT;
long nPostureID = SID_ATTR_CHAR_POSTURE;
if( 0 )
{
nFontID = EE_CHAR_FONTINFO_CJK;
nFontHeightID = EE_CHAR_FONTHEIGHT_CJK;
nWeightID = EE_CHAR_WEIGHT_CJK;
nPostureID = EE_CHAR_ITALIC_CJK;
}
else if( 0 )
{
nFontID = EE_CHAR_FONTINFO_CTL;
nFontHeightID = EE_CHAR_FONTHEIGHT_CTL;
nWeightID = EE_CHAR_WEIGHT_CTL;
nPostureID = EE_CHAR_ITALIC_CTL;
}
Font aMyFont;
const SvxFontItem& rFItem =
(SvxFontItem&)rSet.Get(GetWhich( (USHORT)nFontID ));
aMyFont.SetFamily(rFItem.GetFamily());
aMyFont.SetName(rFItem.GetFamilyName());
aMyFont.SetCharSet(rFItem.GetCharSet());
aMyFont.SetPitch(rFItem.GetPitch());
const SvxFontHeightItem& rFHItem =
(SvxFontHeightItem&)rSet.Get(GetWhich( (USHORT)nFontHeightID ));
aMyFont.SetSize(Size(0, rFHItem.GetHeight()));
const SvxWeightItem& rWItem =
(SvxWeightItem&)rSet.Get(GetWhich( (USHORT)nWeightID ));
aMyFont.SetWeight(rWItem.GetWeight());
const SvxPostureItem& rPItem =
(SvxPostureItem&)rSet.Get(GetWhich( (USHORT)nPostureID ));
aMyFont.SetItalic(rPItem.GetPosture());
const SvxUnderlineItem& rUItem = (SvxUnderlineItem&)rSet.Get(GetWhich(SID_ATTR_CHAR_UNDERLINE));
aMyFont.SetUnderline(rUItem.GetUnderline());
const SvxCrossedOutItem& rCOItem = (SvxCrossedOutItem&)rSet.Get(GetWhich(SID_ATTR_CHAR_STRIKEOUT));
aMyFont.SetStrikeout(rCOItem.GetStrikeout());
const SvxContourItem& rCItem = (SvxContourItem&)rSet.Get(GetWhich(SID_ATTR_CHAR_CONTOUR));
aMyFont.SetOutline(rCItem.GetValue());
const SvxShadowedItem& rSItem = (SvxShadowedItem&)rSet.Get(GetWhich(SID_ATTR_CHAR_SHADOWED));
aMyFont.SetShadow(rSItem.GetValue());
aNewLevel.SetBulletFont(&aMyFont);
// aNewLevel.SetBulletRelSize( 75 );
aNumRule.SetLevel(nLevel, aNewLevel );
}
else if( rSrcLevel.GetNumberingType() == com::sun::star::style::NumberingType::CHAR_SPECIAL )
{
String aEmpty;
aNewLevel.SetPrefix( aEmpty );
aNewLevel.SetSuffix( aEmpty );
aNumRule.SetLevel(nLevel, aNewLevel );
}
}
}
<commit_msg>INTEGRATION: CWS impressodf12 (1.8.210); FILE MERGED 2008/04/25 08:53:06 cl 1.8.210.3: RESYNC: (1.8-1.9); FILE MERGED 2008/04/13 19:05:19 cl 1.8.210.2: #i35937# allow paragraph depth of -1 to switch of numbering 2008/04/10 17:07:45 cl 1.8.210.1: #i35937# allow paragraph depth of -1 to switch of numbering<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: bulmaper.cxx,v $
* $Revision: 1.10 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#ifdef SD_DLLIMPLEMENTATION
#undef SD_DLLIMPLEMENTATION
#endif
#ifndef _SVX_SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
//-> Fonts & Items
#include <vcl/font.hxx>
#include <svx/fontitem.hxx>
#include <svx/fhgtitem.hxx>
#include <svx/wghtitem.hxx>
#include <svx/udlnitem.hxx>
#include <svx/crsditem.hxx>
#include <svx/postitem.hxx>
#include <svx/cntritem.hxx>
#include <svx/shdditem.hxx>
//<- Fonts & Items
#include <svx/bulitem.hxx>
#include <svx/brshitem.hxx>
#include <vcl/graph.hxx>
#include <svtools/itemset.hxx>
#include <svtools/itempool.hxx>
#include <svx/numitem.hxx>
#include <svx/eeitem.hxx>
#include "bulmaper.hxx"
#define GetWhich(nSlot) rSet.GetPool()->GetWhich( nSlot )
/* #i35937#
void SdBulletMapper::PreMapNumBulletForDialog( SfxItemSet& rSet )
{
if( SFX_ITEM_SET == rSet.GetItemState( EE_PARA_NUMBULLET, FALSE ) )
{
SvxNumRule* pRule = ((SvxNumBulletItem*)rSet.GetItem( EE_PARA_NUMBULLET ))->GetNumRule();
if(pRule && pRule->GetNumRuleType() == SVX_RULETYPE_PRESENTATION_NUMBERING)
{
// 10er Bullet Item auf 9er Item mappen
SvxNumRule aNewRule( pRule->GetFeatureFlags(), 9, FALSE, SVX_RULETYPE_PRESENTATION_NUMBERING );
for( USHORT i = 0; i < 9; i++ )
aNewRule.SetLevel(i, pRule->GetLevel(i));
rSet.Put( SvxNumBulletItem( aNewRule, EE_PARA_NUMBULLET ) );
}
}
}
void SdBulletMapper::PostMapNumBulletForDialog( SfxItemSet& rSet )
{
if( SFX_ITEM_SET == rSet.GetItemState( EE_PARA_NUMBULLET, FALSE ) )
{
SvxNumRule* pRule = ((SvxNumBulletItem*)rSet.GetItem( EE_PARA_NUMBULLET ))->GetNumRule();
if(pRule)
{
pRule->UnLinkGraphics();
if(pRule->GetNumRuleType() == SVX_RULETYPE_PRESENTATION_NUMBERING)
{
// 9er Bullet Item auf 10er Item mappen
SvxNumRule aNewRule( pRule->GetFeatureFlags(), 10, FALSE, SVX_RULETYPE_PRESENTATION_NUMBERING );
for( USHORT i = 0; i < 9; i++ )
aNewRule.SetLevel(i, pRule->GetLevel(i));
rSet.Put( SvxNumBulletItem( aNewRule, EE_PARA_NUMBULLET ) );
}
}
}
}
*/
void SdBulletMapper::MapFontsInNumRule( SvxNumRule& aNumRule, const SfxItemSet& rSet )
{
const USHORT nCount = aNumRule.GetLevelCount();
for( USHORT nLevel = 0; nLevel < nCount; nLevel++ )
{
const SvxNumberFormat& rSrcLevel = aNumRule.GetLevel(nLevel);
SvxNumberFormat aNewLevel( rSrcLevel );
if(rSrcLevel.GetNumberingType() != com::sun::star::style::NumberingType::CHAR_SPECIAL &&
rSrcLevel.GetNumberingType() != com::sun::star::style::NumberingType::NUMBER_NONE )
{
// wenn Aufzaehlung statt Bullet gewaehlt wurde, wird der Bullet-Font
// dem Vorlagen-Font angeglichen
// to be implemented if module supports CJK
long nFontID = SID_ATTR_CHAR_FONT;
long nFontHeightID = SID_ATTR_CHAR_FONTHEIGHT;
long nWeightID = SID_ATTR_CHAR_WEIGHT;
long nPostureID = SID_ATTR_CHAR_POSTURE;
if( 0 )
{
nFontID = EE_CHAR_FONTINFO_CJK;
nFontHeightID = EE_CHAR_FONTHEIGHT_CJK;
nWeightID = EE_CHAR_WEIGHT_CJK;
nPostureID = EE_CHAR_ITALIC_CJK;
}
else if( 0 )
{
nFontID = EE_CHAR_FONTINFO_CTL;
nFontHeightID = EE_CHAR_FONTHEIGHT_CTL;
nWeightID = EE_CHAR_WEIGHT_CTL;
nPostureID = EE_CHAR_ITALIC_CTL;
}
Font aMyFont;
const SvxFontItem& rFItem =
(SvxFontItem&)rSet.Get(GetWhich( (USHORT)nFontID ));
aMyFont.SetFamily(rFItem.GetFamily());
aMyFont.SetName(rFItem.GetFamilyName());
aMyFont.SetCharSet(rFItem.GetCharSet());
aMyFont.SetPitch(rFItem.GetPitch());
const SvxFontHeightItem& rFHItem =
(SvxFontHeightItem&)rSet.Get(GetWhich( (USHORT)nFontHeightID ));
aMyFont.SetSize(Size(0, rFHItem.GetHeight()));
const SvxWeightItem& rWItem =
(SvxWeightItem&)rSet.Get(GetWhich( (USHORT)nWeightID ));
aMyFont.SetWeight(rWItem.GetWeight());
const SvxPostureItem& rPItem =
(SvxPostureItem&)rSet.Get(GetWhich( (USHORT)nPostureID ));
aMyFont.SetItalic(rPItem.GetPosture());
const SvxUnderlineItem& rUItem = (SvxUnderlineItem&)rSet.Get(GetWhich(SID_ATTR_CHAR_UNDERLINE));
aMyFont.SetUnderline(rUItem.GetUnderline());
const SvxCrossedOutItem& rCOItem = (SvxCrossedOutItem&)rSet.Get(GetWhich(SID_ATTR_CHAR_STRIKEOUT));
aMyFont.SetStrikeout(rCOItem.GetStrikeout());
const SvxContourItem& rCItem = (SvxContourItem&)rSet.Get(GetWhich(SID_ATTR_CHAR_CONTOUR));
aMyFont.SetOutline(rCItem.GetValue());
const SvxShadowedItem& rSItem = (SvxShadowedItem&)rSet.Get(GetWhich(SID_ATTR_CHAR_SHADOWED));
aMyFont.SetShadow(rSItem.GetValue());
aNewLevel.SetBulletFont(&aMyFont);
// aNewLevel.SetBulletRelSize( 75 );
aNumRule.SetLevel(nLevel, aNewLevel );
}
else if( rSrcLevel.GetNumberingType() == com::sun::star::style::NumberingType::CHAR_SPECIAL )
{
String aEmpty;
aNewLevel.SetPrefix( aEmpty );
aNewLevel.SetSuffix( aEmpty );
aNumRule.SetLevel(nLevel, aNewLevel );
}
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: bulmaper.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-09 04:33:09 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifdef SD_DLLIMPLEMENTATION
#undef SD_DLLIMPLEMENTATION
#endif
#ifndef _SVX_SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
#define ITEMID_FONT SID_ATTR_CHAR_FONT
#define ITEMID_FONTHEIGHT SID_ATTR_CHAR_FONTHEIGHT
#define ITEMID_COLOR SID_ATTR_CHAR_COLOR
#define ITEMID_POSTURE SID_ATTR_CHAR_POSTURE
#define ITEMID_WEIGHT SID_ATTR_CHAR_WEIGHT
#define ITEMID_SHADOWED SID_ATTR_CHAR_SHADOWED
#define ITEMID_CONTOUR SID_ATTR_CHAR_CONTOUR
#define ITEMID_CROSSEDOUT SID_ATTR_CHAR_STRIKEOUT
#define ITEMID_UNDERLINE SID_ATTR_CHAR_UNDERLINE
//-> Fonts & Items
#ifndef _SV_FONT_HXX
#include <vcl/font.hxx>
#endif
#ifndef _SVX_FONTITEM_HXX
#include <svx/fontitem.hxx>
#endif
#ifndef _SVX_FHGTITEM_HXX //autogen
#include <svx/fhgtitem.hxx>
#endif
#ifndef _SVX_WGHTITEM_HXX //autogen
#include <svx/wghtitem.hxx>
#endif
#ifndef _SVX_UDLNITEM_HXX //autogen
#include <svx/udlnitem.hxx>
#endif
#ifndef _SVX_CRSDITEM_HXX //autogen
#include <svx/crsditem.hxx>
#endif
#ifndef _SVX_POSTITEM_HXX //autogen
#include <svx/postitem.hxx>
#endif
#ifndef _SVX_ITEM_HXX //autogen
#include <svx/cntritem.hxx>
#endif
#ifndef _SVX_SHDDITEM_HXX //autogen
#include <svx/shdditem.hxx>
#endif
//<- Fonts & Items
#ifndef _SVX_BULITEM_HXX
#include <svx/bulitem.hxx>
#endif
#define ITEMID_BRUSH 0
#ifndef _SVX_BRSHITEM_HXX
#include <svx/brshitem.hxx>
#endif
#ifndef _SV_GRAPH_HXX
#include <vcl/graph.hxx>
#endif
#ifndef _SFXITEMSET_HXX //autogen
#include <svtools/itemset.hxx>
#endif
#ifndef _SFXITEMPOOL_HXX //autogen
#include <svtools/itempool.hxx>
#endif
#include <svx/numitem.hxx>
#ifndef _EEITEM_HXX //autogen
#include <svx/eeitem.hxx>
#endif
#include "bulmaper.hxx"
#define GetWhich(nSlot) rSet.GetPool()->GetWhich( nSlot )
void SdBulletMapper::PreMapNumBulletForDialog( SfxItemSet& rSet )
{
if( SFX_ITEM_SET == rSet.GetItemState( EE_PARA_NUMBULLET, FALSE ) )
{
SvxNumRule* pRule = ((SvxNumBulletItem*)rSet.GetItem( EE_PARA_NUMBULLET ))->GetNumRule();
if(pRule && pRule->GetNumRuleType() == SVX_RULETYPE_PRESENTATION_NUMBERING)
{
// 10er Bullet Item auf 9er Item mappen
SvxNumRule aNewRule( pRule->GetFeatureFlags(), 9, FALSE, SVX_RULETYPE_PRESENTATION_NUMBERING );
for( USHORT i = 0; i < 9; i++ )
aNewRule.SetLevel(i, pRule->GetLevel(i+1));
rSet.Put( SvxNumBulletItem( aNewRule, EE_PARA_NUMBULLET ) );
}
}
}
void SdBulletMapper::PostMapNumBulletForDialog( SfxItemSet& rSet )
{
if( SFX_ITEM_SET == rSet.GetItemState( EE_PARA_NUMBULLET, FALSE ) )
{
SvxNumRule* pRule = ((SvxNumBulletItem*)rSet.GetItem( EE_PARA_NUMBULLET ))->GetNumRule();
if(pRule)
{
pRule->UnLinkGraphics();
if(pRule->GetNumRuleType() == SVX_RULETYPE_PRESENTATION_NUMBERING)
{
// 9er Bullet Item auf 10er Item mappen
SvxNumRule aNewRule( pRule->GetFeatureFlags(), 10, FALSE, SVX_RULETYPE_PRESENTATION_NUMBERING );
for( USHORT i = 0; i < 9; i++ )
aNewRule.SetLevel(i+1, pRule->GetLevel(i));
rSet.Put( SvxNumBulletItem( aNewRule, EE_PARA_NUMBULLET ) );
}
}
}
}
void SdBulletMapper::MapFontsInNumRule( SvxNumRule& aNumRule, const SfxItemSet& rSet )
{
const USHORT nCount = aNumRule.GetLevelCount();
for( USHORT nLevel = 0; nLevel < nCount; nLevel++ )
{
const SvxNumberFormat& rSrcLevel = aNumRule.GetLevel(nLevel);
SvxNumberFormat aNewLevel( rSrcLevel );
if(rSrcLevel.GetNumberingType() != com::sun::star::style::NumberingType::CHAR_SPECIAL &&
rSrcLevel.GetNumberingType() != com::sun::star::style::NumberingType::NUMBER_NONE )
{
// wenn Aufzaehlung statt Bullet gewaehlt wurde, wird der Bullet-Font
// dem Vorlagen-Font angeglichen
// to be implemented if module supports CJK
long nFontID = ITEMID_FONT;
long nFontHeightID = ITEMID_FONTHEIGHT;
long nWeightID = ITEMID_WEIGHT;
long nPostureID = ITEMID_POSTURE;
if( 0 )
{
nFontID = EE_CHAR_FONTINFO_CJK;
nFontHeightID = EE_CHAR_FONTHEIGHT_CJK;
nWeightID = EE_CHAR_WEIGHT_CJK;
nPostureID = EE_CHAR_ITALIC_CJK;
}
else if( 0 )
{
nFontID = EE_CHAR_FONTINFO_CTL;
nFontHeightID = EE_CHAR_FONTHEIGHT_CTL;
nWeightID = EE_CHAR_WEIGHT_CTL;
nPostureID = EE_CHAR_ITALIC_CTL;
}
Font aMyFont;
const SvxFontItem& rFItem =
(SvxFontItem&)rSet.Get(GetWhich( nFontID ));
aMyFont.SetFamily(rFItem.GetFamily());
aMyFont.SetName(rFItem.GetFamilyName());
aMyFont.SetCharSet(rFItem.GetCharSet());
aMyFont.SetPitch(rFItem.GetPitch());
const SvxFontHeightItem& rFHItem =
(SvxFontHeightItem&)rSet.Get(GetWhich( nFontHeightID ));
aMyFont.SetSize(Size(0, rFHItem.GetHeight()));
const SvxWeightItem& rWItem =
(SvxWeightItem&)rSet.Get(GetWhich( nWeightID ));
aMyFont.SetWeight(rWItem.GetWeight());
const SvxPostureItem& rPItem =
(SvxPostureItem&)rSet.Get(GetWhich( nPostureID ));
aMyFont.SetItalic(rPItem.GetPosture());
const SvxUnderlineItem& rUItem = (SvxUnderlineItem&)rSet.Get(GetWhich(SID_ATTR_CHAR_UNDERLINE));
aMyFont.SetUnderline(rUItem.GetUnderline());
const SvxCrossedOutItem& rCOItem = (SvxCrossedOutItem&)rSet.Get(GetWhich(SID_ATTR_CHAR_STRIKEOUT));
aMyFont.SetStrikeout(rCOItem.GetStrikeout());
const SvxContourItem& rCItem = (SvxContourItem&)rSet.Get(GetWhich(SID_ATTR_CHAR_CONTOUR));
aMyFont.SetOutline(rCItem.GetValue());
const SvxShadowedItem& rSItem = (SvxShadowedItem&)rSet.Get(GetWhich(SID_ATTR_CHAR_SHADOWED));
aMyFont.SetShadow(rSItem.GetValue());
aNewLevel.SetBulletFont(&aMyFont);
// aNewLevel.SetBulletRelSize( 75 );
aNumRule.SetLevel(nLevel, aNewLevel );
}
else if( rSrcLevel.GetNumberingType() == com::sun::star::style::NumberingType::CHAR_SPECIAL )
{
String aEmpty;
aNewLevel.SetPrefix( aEmpty );
aNewLevel.SetSuffix( aEmpty );
aNumRule.SetLevel(nLevel, aNewLevel );
}
}
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.5.282); FILE MERGED 2006/09/01 17:37:04 kaib 1.5.282.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: bulmaper.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2006-09-16 18:46:20 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#ifdef SD_DLLIMPLEMENTATION
#undef SD_DLLIMPLEMENTATION
#endif
#ifndef _SVX_SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
#define ITEMID_FONT SID_ATTR_CHAR_FONT
#define ITEMID_FONTHEIGHT SID_ATTR_CHAR_FONTHEIGHT
#define ITEMID_COLOR SID_ATTR_CHAR_COLOR
#define ITEMID_POSTURE SID_ATTR_CHAR_POSTURE
#define ITEMID_WEIGHT SID_ATTR_CHAR_WEIGHT
#define ITEMID_SHADOWED SID_ATTR_CHAR_SHADOWED
#define ITEMID_CONTOUR SID_ATTR_CHAR_CONTOUR
#define ITEMID_CROSSEDOUT SID_ATTR_CHAR_STRIKEOUT
#define ITEMID_UNDERLINE SID_ATTR_CHAR_UNDERLINE
//-> Fonts & Items
#ifndef _SV_FONT_HXX
#include <vcl/font.hxx>
#endif
#ifndef _SVX_FONTITEM_HXX
#include <svx/fontitem.hxx>
#endif
#ifndef _SVX_FHGTITEM_HXX //autogen
#include <svx/fhgtitem.hxx>
#endif
#ifndef _SVX_WGHTITEM_HXX //autogen
#include <svx/wghtitem.hxx>
#endif
#ifndef _SVX_UDLNITEM_HXX //autogen
#include <svx/udlnitem.hxx>
#endif
#ifndef _SVX_CRSDITEM_HXX //autogen
#include <svx/crsditem.hxx>
#endif
#ifndef _SVX_POSTITEM_HXX //autogen
#include <svx/postitem.hxx>
#endif
#ifndef _SVX_ITEM_HXX //autogen
#include <svx/cntritem.hxx>
#endif
#ifndef _SVX_SHDDITEM_HXX //autogen
#include <svx/shdditem.hxx>
#endif
//<- Fonts & Items
#ifndef _SVX_BULITEM_HXX
#include <svx/bulitem.hxx>
#endif
#define ITEMID_BRUSH 0
#ifndef _SVX_BRSHITEM_HXX
#include <svx/brshitem.hxx>
#endif
#ifndef _SV_GRAPH_HXX
#include <vcl/graph.hxx>
#endif
#ifndef _SFXITEMSET_HXX //autogen
#include <svtools/itemset.hxx>
#endif
#ifndef _SFXITEMPOOL_HXX //autogen
#include <svtools/itempool.hxx>
#endif
#include <svx/numitem.hxx>
#ifndef _EEITEM_HXX //autogen
#include <svx/eeitem.hxx>
#endif
#include "bulmaper.hxx"
#define GetWhich(nSlot) rSet.GetPool()->GetWhich( nSlot )
void SdBulletMapper::PreMapNumBulletForDialog( SfxItemSet& rSet )
{
if( SFX_ITEM_SET == rSet.GetItemState( EE_PARA_NUMBULLET, FALSE ) )
{
SvxNumRule* pRule = ((SvxNumBulletItem*)rSet.GetItem( EE_PARA_NUMBULLET ))->GetNumRule();
if(pRule && pRule->GetNumRuleType() == SVX_RULETYPE_PRESENTATION_NUMBERING)
{
// 10er Bullet Item auf 9er Item mappen
SvxNumRule aNewRule( pRule->GetFeatureFlags(), 9, FALSE, SVX_RULETYPE_PRESENTATION_NUMBERING );
for( USHORT i = 0; i < 9; i++ )
aNewRule.SetLevel(i, pRule->GetLevel(i+1));
rSet.Put( SvxNumBulletItem( aNewRule, EE_PARA_NUMBULLET ) );
}
}
}
void SdBulletMapper::PostMapNumBulletForDialog( SfxItemSet& rSet )
{
if( SFX_ITEM_SET == rSet.GetItemState( EE_PARA_NUMBULLET, FALSE ) )
{
SvxNumRule* pRule = ((SvxNumBulletItem*)rSet.GetItem( EE_PARA_NUMBULLET ))->GetNumRule();
if(pRule)
{
pRule->UnLinkGraphics();
if(pRule->GetNumRuleType() == SVX_RULETYPE_PRESENTATION_NUMBERING)
{
// 9er Bullet Item auf 10er Item mappen
SvxNumRule aNewRule( pRule->GetFeatureFlags(), 10, FALSE, SVX_RULETYPE_PRESENTATION_NUMBERING );
for( USHORT i = 0; i < 9; i++ )
aNewRule.SetLevel(i+1, pRule->GetLevel(i));
rSet.Put( SvxNumBulletItem( aNewRule, EE_PARA_NUMBULLET ) );
}
}
}
}
void SdBulletMapper::MapFontsInNumRule( SvxNumRule& aNumRule, const SfxItemSet& rSet )
{
const USHORT nCount = aNumRule.GetLevelCount();
for( USHORT nLevel = 0; nLevel < nCount; nLevel++ )
{
const SvxNumberFormat& rSrcLevel = aNumRule.GetLevel(nLevel);
SvxNumberFormat aNewLevel( rSrcLevel );
if(rSrcLevel.GetNumberingType() != com::sun::star::style::NumberingType::CHAR_SPECIAL &&
rSrcLevel.GetNumberingType() != com::sun::star::style::NumberingType::NUMBER_NONE )
{
// wenn Aufzaehlung statt Bullet gewaehlt wurde, wird der Bullet-Font
// dem Vorlagen-Font angeglichen
// to be implemented if module supports CJK
long nFontID = ITEMID_FONT;
long nFontHeightID = ITEMID_FONTHEIGHT;
long nWeightID = ITEMID_WEIGHT;
long nPostureID = ITEMID_POSTURE;
if( 0 )
{
nFontID = EE_CHAR_FONTINFO_CJK;
nFontHeightID = EE_CHAR_FONTHEIGHT_CJK;
nWeightID = EE_CHAR_WEIGHT_CJK;
nPostureID = EE_CHAR_ITALIC_CJK;
}
else if( 0 )
{
nFontID = EE_CHAR_FONTINFO_CTL;
nFontHeightID = EE_CHAR_FONTHEIGHT_CTL;
nWeightID = EE_CHAR_WEIGHT_CTL;
nPostureID = EE_CHAR_ITALIC_CTL;
}
Font aMyFont;
const SvxFontItem& rFItem =
(SvxFontItem&)rSet.Get(GetWhich( nFontID ));
aMyFont.SetFamily(rFItem.GetFamily());
aMyFont.SetName(rFItem.GetFamilyName());
aMyFont.SetCharSet(rFItem.GetCharSet());
aMyFont.SetPitch(rFItem.GetPitch());
const SvxFontHeightItem& rFHItem =
(SvxFontHeightItem&)rSet.Get(GetWhich( nFontHeightID ));
aMyFont.SetSize(Size(0, rFHItem.GetHeight()));
const SvxWeightItem& rWItem =
(SvxWeightItem&)rSet.Get(GetWhich( nWeightID ));
aMyFont.SetWeight(rWItem.GetWeight());
const SvxPostureItem& rPItem =
(SvxPostureItem&)rSet.Get(GetWhich( nPostureID ));
aMyFont.SetItalic(rPItem.GetPosture());
const SvxUnderlineItem& rUItem = (SvxUnderlineItem&)rSet.Get(GetWhich(SID_ATTR_CHAR_UNDERLINE));
aMyFont.SetUnderline(rUItem.GetUnderline());
const SvxCrossedOutItem& rCOItem = (SvxCrossedOutItem&)rSet.Get(GetWhich(SID_ATTR_CHAR_STRIKEOUT));
aMyFont.SetStrikeout(rCOItem.GetStrikeout());
const SvxContourItem& rCItem = (SvxContourItem&)rSet.Get(GetWhich(SID_ATTR_CHAR_CONTOUR));
aMyFont.SetOutline(rCItem.GetValue());
const SvxShadowedItem& rSItem = (SvxShadowedItem&)rSet.Get(GetWhich(SID_ATTR_CHAR_SHADOWED));
aMyFont.SetShadow(rSItem.GetValue());
aNewLevel.SetBulletFont(&aMyFont);
// aNewLevel.SetBulletRelSize( 75 );
aNumRule.SetLevel(nLevel, aNewLevel );
}
else if( rSrcLevel.GetNumberingType() == com::sun::star::style::NumberingType::CHAR_SPECIAL )
{
String aEmpty;
aNewLevel.SetPrefix( aEmpty );
aNewLevel.SetSuffix( aEmpty );
aNumRule.SetLevel(nLevel, aNewLevel );
}
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: grviewsh.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: ihi $ $Date: 2006-11-14 14:44:55 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "GraphicViewShell.hxx"
#include "LayerTabBar.hxx"
#include "FrameView.hxx"
#include <sfx2/objsh.hxx>
#include <sfx2/viewfrm.hxx>
#include <vcl/scrbar.hxx>
#ifndef _SV_SALBTYPE_HXX
#include <vcl/salbtype.hxx> // FRound
#endif
namespace sd {
static const int TABCONTROL_INITIAL_SIZE = 350;
/*************************************************************************
|*
|* Standard-Konstruktor
|*
\************************************************************************/
GraphicViewShell::GraphicViewShell (
SfxViewFrame* pFrame,
ViewShellBase& rViewShellBase,
::Window* pParentWindow,
FrameView* pFrameView)
: DrawViewShell (
pFrame,
rViewShellBase,
pParentWindow,
PK_STANDARD,
pFrameView)
{
Construct ();
}
/*************************************************************************
|*
|* Copy-Konstruktor
|*
\************************************************************************/
GraphicViewShell::GraphicViewShell (
SfxViewFrame* pFrame,
::Window* pParentWindow,
const DrawViewShell& rShell)
: DrawViewShell (pFrame, pParentWindow, rShell)
{
Construct ();
}
GraphicViewShell::~GraphicViewShell (void)
{
}
void GraphicViewShell::Construct (void)
{
meShellType = ST_DRAW;
mpLayerTabBar.reset (new LayerTabBar(this,GetParentWindow()));
mpLayerTabBar->SetSplitHdl(LINK(this,GraphicViewShell,TabBarSplitHandler));
// pb: #i67363# no layer tabbar on preview mode
if ( !GetObjectShell()->IsPreview() )
mpLayerTabBar->Show();
}
void GraphicViewShell::ChangeEditMode (
EditMode eMode,
bool bIsLayerModeActive)
{
// There is no page tab that could be shown instead of the layer tab.
// Therefore we have it allways visible regardless of what the caller
// said. (We have to change the callers behaviour, of course.)
DrawViewShell::ChangeEditMode (eMode, true);
}
void GraphicViewShell::ArrangeGUIElements (void)
{
if (mpLayerTabBar.get()!=NULL && mpLayerTabBar->IsVisible())
{
Size aSize = mpLayerTabBar->GetSizePixel();
const Size aFrameSize (
GetViewFrame()->GetWindow().GetOutputSizePixel());
if (aSize.Width() == 0)
{
if (pFrameView->GetTabCtrlPercent() == 0.0)
aSize.Width() = TABCONTROL_INITIAL_SIZE;
else
aSize.Width() = FRound(aFrameSize.Width()
* pFrameView->GetTabCtrlPercent());
}
aSize.Height() = GetParentWindow()->GetSettings().GetStyleSettings()
.GetScrollBarSize();
Point aPos (0, aViewSize.Height() - aSize.Height());
mpLayerTabBar->SetPosSizePixel (aPos, aSize);
if (aFrameSize.Width() > 0)
pFrameView->SetTabCtrlPercent (
(double) aTabControl.GetSizePixel().Width()
/ aFrameSize.Width());
else
pFrameView->SetTabCtrlPercent( 0.0 );
}
DrawViewShell::ArrangeGUIElements();
}
IMPL_LINK(GraphicViewShell, TabBarSplitHandler, TabBar*, pTabBar)
{
const long int nMax = aViewSize.Width()
- aScrBarWH.Width()
- pTabBar->GetPosPixel().X();
Size aTabSize = pTabBar->GetSizePixel();
aTabSize.Width() = Min(pTabBar->GetSplitSize(), (long)(nMax-1));
pTabBar->SetSizePixel (aTabSize);
Point aPos = pTabBar->GetPosPixel();
aPos.X() += aTabSize.Width();
Size aScrSize (nMax - aTabSize.Width(), aScrBarWH.Height());
mpHorizontalScrollBar->SetPosSizePixel(aPos, aScrSize);
return 0;
}
} // end of namespace sd
<commit_msg>INTEGRATION: CWS sdwarningsbegone (1.7.36); FILE MERGED 2006/11/27 13:48:19 cl 1.7.36.3: #i69285# warning free code changes for sd project 2006/11/22 15:15:48 cl 1.7.36.2: RESYNC: (1.7-1.8); FILE MERGED 2006/11/22 12:42:29 cl 1.7.36.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: grviewsh.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: kz $ $Date: 2006-12-12 19:18:03 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "GraphicViewShell.hxx"
#include "LayerTabBar.hxx"
#include "FrameView.hxx"
#include <sfx2/objsh.hxx>
#include <sfx2/viewfrm.hxx>
#include <vcl/scrbar.hxx>
#ifndef _SV_SALBTYPE_HXX
#include <vcl/salbtype.hxx> // FRound
#endif
namespace sd {
static const int TABCONTROL_INITIAL_SIZE = 350;
/*************************************************************************
|*
|* Standard-Konstruktor
|*
\************************************************************************/
GraphicViewShell::GraphicViewShell (
SfxViewFrame* pFrame,
ViewShellBase& rViewShellBase,
::Window* pParentWindow,
FrameView* pFrameView)
: DrawViewShell (
pFrame,
rViewShellBase,
pParentWindow,
PK_STANDARD,
pFrameView)
{
ConstructGraphicViewShell();
}
/*************************************************************************
|*
|* Copy-Konstruktor
|*
\************************************************************************/
GraphicViewShell::GraphicViewShell (
SfxViewFrame* pFrame,
::Window* pParentWindow,
const DrawViewShell& rShell)
: DrawViewShell (pFrame, pParentWindow, rShell)
{
ConstructGraphicViewShell();
}
GraphicViewShell::~GraphicViewShell (void)
{
}
void GraphicViewShell::ConstructGraphicViewShell(void)
{
meShellType = ST_DRAW;
mpLayerTabBar.reset (new LayerTabBar(this,GetParentWindow()));
mpLayerTabBar->SetSplitHdl(LINK(this,GraphicViewShell,TabBarSplitHandler));
// pb: #i67363# no layer tabbar on preview mode
if ( !GetObjectShell()->IsPreview() )
mpLayerTabBar->Show();
}
void GraphicViewShell::ChangeEditMode (
EditMode eMode,
bool )
{
// There is no page tab that could be shown instead of the layer tab.
// Therefore we have it allways visible regardless of what the caller
// said. (We have to change the callers behaviour, of course.)
DrawViewShell::ChangeEditMode (eMode, true);
}
void GraphicViewShell::ArrangeGUIElements (void)
{
if (mpLayerTabBar.get()!=NULL && mpLayerTabBar->IsVisible())
{
Size aSize = mpLayerTabBar->GetSizePixel();
const Size aFrameSize (
GetViewFrame()->GetWindow().GetOutputSizePixel());
if (aSize.Width() == 0)
{
if (mpFrameView->GetTabCtrlPercent() == 0.0)
aSize.Width() = TABCONTROL_INITIAL_SIZE;
else
aSize.Width() = FRound(aFrameSize.Width()
* mpFrameView->GetTabCtrlPercent());
}
aSize.Height() = GetParentWindow()->GetSettings().GetStyleSettings()
.GetScrollBarSize();
Point aPos (0, maViewSize.Height() - aSize.Height());
mpLayerTabBar->SetPosSizePixel (aPos, aSize);
if (aFrameSize.Width() > 0)
mpFrameView->SetTabCtrlPercent (
(double) maTabControl.GetSizePixel().Width()
/ aFrameSize.Width());
else
mpFrameView->SetTabCtrlPercent( 0.0 );
}
DrawViewShell::ArrangeGUIElements();
}
IMPL_LINK(GraphicViewShell, TabBarSplitHandler, TabBar*, pTabBar)
{
const long int nMax = maViewSize.Width()
- maScrBarWH.Width()
- pTabBar->GetPosPixel().X();
Size aTabSize = pTabBar->GetSizePixel();
aTabSize.Width() = Min(pTabBar->GetSplitSize(), (long)(nMax-1));
pTabBar->SetSizePixel (aTabSize);
Point aPos = pTabBar->GetPosPixel();
aPos.X() += aTabSize.Width();
Size aScrSize (nMax - aTabSize.Width(), maScrBarWH.Height());
mpHorizontalScrollBar->SetPosSizePixel(aPos, aScrSize);
return 0;
}
} // end of namespace sd
<|endoftext|>
|
<commit_before>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "ShardSplitter.h"
#include <folly/dynamic.h>
#include "mcrouter/lib/fbi/cpp/globals.h"
#include "mcrouter/lib/fbi/cpp/util.h"
#include "mcrouter/routes/ShardHashFunc.h"
namespace facebook {
namespace memcache {
namespace mcrouter {
namespace {
constexpr size_t kMaxSplits = 26 * 26 + 1;
constexpr size_t kHostIdModulo = 16384;
size_t checkShardSplitSize(
const folly::StringPiece shardId,
const folly::dynamic& splitValue,
folly::StringPiece name) {
checkLogic(
splitValue.isInt(),
"ShardSplitter: {} is not an int for {}",
name,
shardId);
auto split = splitValue.asInt();
checkLogic(
split > 0, "ShardSplitter: {} value is <= 0 for {}", name, shardId);
if (static_cast<size_t>(split) > kMaxSplits) {
LOG(ERROR) << "ShardSplitter: " << name << " value is greater than "
<< kMaxSplits << " for " << shardId;
return kMaxSplits;
}
return static_cast<size_t>(split);
}
ShardSplitter::ShardSplitInfo parseSplit(
const folly::dynamic& json,
folly::StringPiece id,
std::chrono::system_clock::time_point now) {
checkLogic(
json.isInt() || json.isObject(),
"ShardSplitter: split config for {} is not an int or object",
id);
if (json.isInt()) {
auto splitCnt = checkShardSplitSize(id, json, "shard_splits");
return ShardSplitter::ShardSplitInfo(splitCnt);
} else if (json.isObject()) {
auto oldSplitJson = json.getDefault("old_split_size", 1);
auto oldSplit = checkShardSplitSize(id, oldSplitJson, "old_split_size");
auto newSplitJson = json.getDefault("new_split_size", 1);
auto newSplit = checkShardSplitSize(id, newSplitJson, "new_split_size");
auto startTimeJson = json.getDefault("split_start", 0);
checkLogic(
startTimeJson.isInt(),
"ShardSplitter: split_start is not an int for {}",
id);
checkLogic(
startTimeJson.asInt() >= 0,
"ShardSplitter: split_start is negative for {}",
id);
std::chrono::system_clock::time_point startTime(
std::chrono::seconds(startTimeJson.asInt()));
auto migrationPeriodJson = json.getDefault("migration_period", 0);
checkLogic(
migrationPeriodJson.isInt(),
"ShardSplitter: migration_period is not an int for {}",
id);
checkLogic(
migrationPeriodJson.asInt() >= 0,
"ShardSplitter: migration_period is negative for {}",
id);
std::chrono::duration<double> migrationPeriod(migrationPeriodJson.asInt());
auto fanoutDeletesJson = json.getDefault("fanout_deletes", false);
checkLogic(
fanoutDeletesJson.isBool(),
"ShardSplitter: fanout_deletes is not bool for {}",
id);
if (now > startTime + migrationPeriod || newSplit == oldSplit) {
return ShardSplitter::ShardSplitInfo(
newSplit, fanoutDeletesJson.asBool());
} else {
return ShardSplitter::ShardSplitInfo(
oldSplit,
newSplit,
startTime,
migrationPeriod,
fanoutDeletesJson.asBool());
}
}
// Should never reach here
throwLogic("Invalid json type, not an int or object for {}", id);
return ShardSplitter::ShardSplitInfo(1);
}
} // namespace
size_t ShardSplitter::ShardSplitInfo::getSplitSizeForCurrentHost() const {
if (migrating_) {
auto now = std::chrono::system_clock::now();
if (now < startTime_) {
return oldSplitSize_;
} else if (now > startTime_ + migrationPeriod_) {
migrating_ = false;
return newSplitSize_;
} else {
double point = std::chrono::duration_cast<std::chrono::duration<double>>(
now - startTime_)
.count() /
migrationPeriod_.count();
return globals::hostid() % kHostIdModulo /
static_cast<double>(kHostIdModulo) <
point
? newSplitSize_
: oldSplitSize_;
}
}
return newSplitSize_;
}
ShardSplitter::ShardSplitter(
const folly::dynamic& json,
const folly::dynamic& defaultSplitJson,
bool enablePrefixMatching)
: defaultShardSplit_(parseSplit(
defaultSplitJson,
"default",
std::chrono::system_clock::now())),
enablePrefixMatching_(enablePrefixMatching) {
checkLogic(json.isObject(), "ShardSplitter: config is not an object");
auto now = std::chrono::system_clock::now();
for (const auto& it : json.items()) {
checkLogic(
it.first.isString(),
"ShardSplitter: expected string for key in shard split config, "
"but got {}",
it.first.typeName());
folly::StringPiece shardId = it.first.getString();
const auto split = parseSplit(it.second, shardId, now);
// Only store if different than the default or is is migrating
if (split.hasMigrationConfigured() ||
split.getNewSplitSize() != defaultShardSplit_.getNewSplitSize()) {
shardSplits_.emplace(shardId, split);
}
}
}
const ShardSplitter::ShardSplitInfo& ShardSplitter::getShardSplit(
folly::StringPiece shard) const {
for (;;) {
auto splitIt = shardSplits_.find(shard);
if (splitIt != shardSplits_.end()) {
return splitIt->second;
}
if (!enablePrefixMatching_) {
break;
}
// No match, lop off the last section and try again
auto pos = shard.rfind('.');
if (pos == std::string::npos) {
break;
}
shard = shard.subpiece(0, pos);
}
return defaultShardSplit_;
}
const ShardSplitter::ShardSplitInfo* ShardSplitter::getShardSplit(
folly::StringPiece routingKey,
folly::StringPiece& shard) const {
if (!getShardId(routingKey, shard)) {
return nullptr;
}
return &getShardSplit(shard);
}
} // namespace mcrouter
} // namespace memcache
} // namespace facebook
<commit_msg>Don't rehash / reallocate in ShardSplitter<commit_after>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "ShardSplitter.h"
#include <folly/dynamic.h>
#include "mcrouter/lib/fbi/cpp/globals.h"
#include "mcrouter/lib/fbi/cpp/util.h"
#include "mcrouter/routes/ShardHashFunc.h"
namespace facebook {
namespace memcache {
namespace mcrouter {
namespace {
constexpr size_t kMaxSplits = 26 * 26 + 1;
constexpr size_t kHostIdModulo = 16384;
size_t checkShardSplitSize(
const folly::StringPiece shardId,
const folly::dynamic& splitValue,
folly::StringPiece name) {
checkLogic(
splitValue.isInt(),
"ShardSplitter: {} is not an int for {}",
name,
shardId);
auto split = splitValue.asInt();
checkLogic(
split > 0, "ShardSplitter: {} value is <= 0 for {}", name, shardId);
if (static_cast<size_t>(split) > kMaxSplits) {
LOG(ERROR) << "ShardSplitter: " << name << " value is greater than "
<< kMaxSplits << " for " << shardId;
return kMaxSplits;
}
return static_cast<size_t>(split);
}
ShardSplitter::ShardSplitInfo parseSplit(
const folly::dynamic& json,
folly::StringPiece id,
std::chrono::system_clock::time_point now) {
checkLogic(
json.isInt() || json.isObject(),
"ShardSplitter: split config for {} is not an int or object",
id);
if (json.isInt()) {
auto splitCnt = checkShardSplitSize(id, json, "shard_splits");
return ShardSplitter::ShardSplitInfo(splitCnt);
} else if (json.isObject()) {
auto oldSplitJson = json.getDefault("old_split_size", 1);
auto oldSplit = checkShardSplitSize(id, oldSplitJson, "old_split_size");
auto newSplitJson = json.getDefault("new_split_size", 1);
auto newSplit = checkShardSplitSize(id, newSplitJson, "new_split_size");
auto startTimeJson = json.getDefault("split_start", 0);
checkLogic(
startTimeJson.isInt(),
"ShardSplitter: split_start is not an int for {}",
id);
checkLogic(
startTimeJson.asInt() >= 0,
"ShardSplitter: split_start is negative for {}",
id);
std::chrono::system_clock::time_point startTime(
std::chrono::seconds(startTimeJson.asInt()));
auto migrationPeriodJson = json.getDefault("migration_period", 0);
checkLogic(
migrationPeriodJson.isInt(),
"ShardSplitter: migration_period is not an int for {}",
id);
checkLogic(
migrationPeriodJson.asInt() >= 0,
"ShardSplitter: migration_period is negative for {}",
id);
std::chrono::duration<double> migrationPeriod(migrationPeriodJson.asInt());
auto fanoutDeletesJson = json.getDefault("fanout_deletes", false);
checkLogic(
fanoutDeletesJson.isBool(),
"ShardSplitter: fanout_deletes is not bool for {}",
id);
if (now > startTime + migrationPeriod || newSplit == oldSplit) {
return ShardSplitter::ShardSplitInfo(
newSplit, fanoutDeletesJson.asBool());
} else {
return ShardSplitter::ShardSplitInfo(
oldSplit,
newSplit,
startTime,
migrationPeriod,
fanoutDeletesJson.asBool());
}
}
// Should never reach here
throwLogic("Invalid json type, not an int or object for {}", id);
return ShardSplitter::ShardSplitInfo(1);
}
} // namespace
size_t ShardSplitter::ShardSplitInfo::getSplitSizeForCurrentHost() const {
if (migrating_) {
auto now = std::chrono::system_clock::now();
if (now < startTime_) {
return oldSplitSize_;
} else if (now > startTime_ + migrationPeriod_) {
migrating_ = false;
return newSplitSize_;
} else {
double point = std::chrono::duration_cast<std::chrono::duration<double>>(
now - startTime_)
.count() /
migrationPeriod_.count();
return globals::hostid() % kHostIdModulo /
static_cast<double>(kHostIdModulo) <
point
? newSplitSize_
: oldSplitSize_;
}
}
return newSplitSize_;
}
ShardSplitter::ShardSplitter(
const folly::dynamic& json,
const folly::dynamic& defaultSplitJson,
bool enablePrefixMatching)
: defaultShardSplit_(parseSplit(
defaultSplitJson,
"default",
std::chrono::system_clock::now())),
enablePrefixMatching_(enablePrefixMatching) {
checkLogic(json.isObject(), "ShardSplitter: config is not an object");
auto now = std::chrono::system_clock::now();
shardSplits_.reserve(json.size());
for (const auto& it : json.items()) {
checkLogic(
it.first.isString(),
"ShardSplitter: expected string for key in shard split config, "
"but got {}",
it.first.typeName());
folly::StringPiece shardId = it.first.getString();
const auto split = parseSplit(it.second, shardId, now);
// Only store if different than the default or is is migrating
if (split.hasMigrationConfigured() ||
split.getNewSplitSize() != defaultShardSplit_.getNewSplitSize()) {
shardSplits_.emplace(shardId, split);
}
}
}
const ShardSplitter::ShardSplitInfo& ShardSplitter::getShardSplit(
folly::StringPiece shard) const {
for (;;) {
auto splitIt = shardSplits_.find(shard);
if (splitIt != shardSplits_.end()) {
return splitIt->second;
}
if (!enablePrefixMatching_) {
break;
}
// No match, lop off the last section and try again
auto pos = shard.rfind('.');
if (pos == std::string::npos) {
break;
}
shard = shard.subpiece(0, pos);
}
return defaultShardSplit_;
}
const ShardSplitter::ShardSplitInfo* ShardSplitter::getShardSplit(
folly::StringPiece routingKey,
folly::StringPiece& shard) const {
if (!getShardId(routingKey, shard)) {
return nullptr;
}
return &getShardSplit(shard);
}
} // namespace mcrouter
} // namespace memcache
} // namespace facebook
<|endoftext|>
|
<commit_before>// @(#)root/base:$Id$
// Author: Philippe Canal 03/09/2003
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun, Fons Rademakers and al. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// std::string helper utilities //
// //
//////////////////////////////////////////////////////////////////////////
#include <ROOT/RConfig.hxx>
#include <string>
#include "TBuffer.h"
using namespace std;
void std_string_streamer(TBuffer &b, void *objadd)
{
// Streamer function for std::string object.
if (b.IsReading()) {
b.ReadStdString((std::string*)objadd);
} else {
b.WriteStdString((std::string*)objadd);
}
}
// Declare the streamer to the string TClass object
RootStreamer(string,std_string_streamer);
// Set a version number of the string TClass object
RootClassVersion(string,2);
<commit_msg>Order includes by generality.<commit_after>// @(#)root/base:$Id$
// Author: Philippe Canal 03/09/2003
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun, Fons Rademakers and al. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// std::string helper utilities //
// //
//////////////////////////////////////////////////////////////////////////
#include <ROOT/RConfig.hxx>
#include "TBuffer.h"
#include <string>
using namespace std;
void std_string_streamer(TBuffer &b, void *objadd)
{
// Streamer function for std::string object.
if (b.IsReading()) {
b.ReadStdString((std::string*)objadd);
} else {
b.WriteStdString((std::string*)objadd);
}
}
// Declare the streamer to the string TClass object
RootStreamer(string,std_string_streamer);
// Set a version number of the string TClass object
RootClassVersion(string,2);
<|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.
#if defined(_MSC_VER)
#include <intrin.h>
#else
#include <mmintrin.h>
#endif
#include "build/build_config.h"
#include "media/base/simd/filter_yuv.h"
namespace media {
#if defined(COMPILER_MSVC)
// Warning 4799 is about calling emms before the function exits.
// We calls emms in a frame level so suppress this warning.
#pragma warning(disable: 4799)
#endif
void FilterYUVRows_MMX(uint8* dest,
const uint8* src0,
const uint8* src1,
int width,
int fraction) {
int pixel = 0;
// Process the unaligned bytes first.
int unaligned_width =
(8 - (reinterpret_cast<uintptr_t>(dest) & 7)) & 7;
while (pixel < width && pixel < unaligned_width) {
dest[pixel] = (src0[pixel] * (256 - fraction) +
src1[pixel] * fraction) >> 8;
++pixel;
}
__m64 zero = _mm_setzero_si64();
__m64 src1_fraction = _mm_set1_pi16(fraction);
__m64 src0_fraction = _mm_set1_pi16(256 - fraction);
const __m64* src0_64 = reinterpret_cast<const __m64*>(src0 + pixel);
const __m64* src1_64 = reinterpret_cast<const __m64*>(src1 + pixel);
__m64* dest64 = reinterpret_cast<__m64*>(dest + pixel);
__m64* end64 = reinterpret_cast<__m64*>(
reinterpret_cast<uintptr_t>(dest + width) & ~7);
while (dest64 < end64) {
__m64 src0 = *src0_64++;
__m64 src1 = *src1_64++;
__m64 src2 = _mm_unpackhi_pi8(src0, zero);
__m64 src3 = _mm_unpackhi_pi8(src1, zero);
src0 = _mm_unpacklo_pi8(src0, zero);
src1 = _mm_unpacklo_pi8(src1, zero);
src0 = _mm_mullo_pi16(src0, src0_fraction);
src1 = _mm_mullo_pi16(src1, src1_fraction);
src2 = _mm_mullo_pi16(src2, src0_fraction);
src3 = _mm_mullo_pi16(src3, src1_fraction);
src0 = _mm_add_pi16(src0, src1);
src2 = _mm_add_pi16(src2, src3);
src0 = _mm_srli_pi16(src0, 8);
src2 = _mm_srli_pi16(src2, 8);
src0 = _mm_packs_pu16(src0, src2);
*dest64++ = src0;
pixel += 8;
}
while (pixel < width) {
dest[pixel] = (src0[pixel] * (256 - fraction) +
src1[pixel] * fraction) >> 8;
++pixel;
}
}
#if defined(COMPILER_MSVC)
#pragma warning(default: 4799)
#endif
} // namespace media
<commit_msg>Fix invalid use of pragma disable/default.<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.
#if defined(_MSC_VER)
#include <intrin.h>
#else
#include <mmintrin.h>
#endif
#include "build/build_config.h"
#include "media/base/simd/filter_yuv.h"
namespace media {
#if defined(COMPILER_MSVC)
// Warning 4799 is about calling emms before the function exits.
// We calls emms in a frame level so suppress this warning.
#pragma warning(push)
#pragma warning(disable: 4799)
#endif
void FilterYUVRows_MMX(uint8* dest,
const uint8* src0,
const uint8* src1,
int width,
int fraction) {
int pixel = 0;
// Process the unaligned bytes first.
int unaligned_width =
(8 - (reinterpret_cast<uintptr_t>(dest) & 7)) & 7;
while (pixel < width && pixel < unaligned_width) {
dest[pixel] = (src0[pixel] * (256 - fraction) +
src1[pixel] * fraction) >> 8;
++pixel;
}
__m64 zero = _mm_setzero_si64();
__m64 src1_fraction = _mm_set1_pi16(fraction);
__m64 src0_fraction = _mm_set1_pi16(256 - fraction);
const __m64* src0_64 = reinterpret_cast<const __m64*>(src0 + pixel);
const __m64* src1_64 = reinterpret_cast<const __m64*>(src1 + pixel);
__m64* dest64 = reinterpret_cast<__m64*>(dest + pixel);
__m64* end64 = reinterpret_cast<__m64*>(
reinterpret_cast<uintptr_t>(dest + width) & ~7);
while (dest64 < end64) {
__m64 src0 = *src0_64++;
__m64 src1 = *src1_64++;
__m64 src2 = _mm_unpackhi_pi8(src0, zero);
__m64 src3 = _mm_unpackhi_pi8(src1, zero);
src0 = _mm_unpacklo_pi8(src0, zero);
src1 = _mm_unpacklo_pi8(src1, zero);
src0 = _mm_mullo_pi16(src0, src0_fraction);
src1 = _mm_mullo_pi16(src1, src1_fraction);
src2 = _mm_mullo_pi16(src2, src0_fraction);
src3 = _mm_mullo_pi16(src3, src1_fraction);
src0 = _mm_add_pi16(src0, src1);
src2 = _mm_add_pi16(src2, src3);
src0 = _mm_srli_pi16(src0, 8);
src2 = _mm_srli_pi16(src2, 8);
src0 = _mm_packs_pu16(src0, src2);
*dest64++ = src0;
pixel += 8;
}
while (pixel < width) {
dest[pixel] = (src0[pixel] * (256 - fraction) +
src1[pixel] * fraction) >> 8;
++pixel;
}
}
#if defined(COMPILER_MSVC)
#pragma warning(pop)
#endif
} // namespace media
<|endoftext|>
|
<commit_before>/* algorithm.cpp - CS 472 Project #2: Genetic Programming
* Copyright 2014 Andrew Schwartzmeyer
*
* Source file for algorithm namespace
*/
#include <algorithm>
#include <cassert>
#include <ctime>
#include <iostream>
#include <fstream>
#include <future>
#include <thread>
#include "algorithm.hpp"
#include "../individual/individual.hpp"
#include "../options/options.hpp"
#include "../random_generator/random_generator.hpp"
namespace algorithm
{
using std::vector;
using individual::Individual;
using options::Options;
using namespace random_generator;
// Returns true if "a" is closer to 0 than "b" and is also normal.
bool
compare_fitness(const Individual& a, const Individual& b)
{
return std::isnormal(a.get_fitness())
? (a.get_fitness() < b.get_fitness()) : false;
}
// Opens the appropriate log file for given time, trial, and folder.
void
open_log(std::ofstream& log, const std::time_t& time, const int& trial,
const std::string& folder)
{
std::string filename = folder + std::to_string(time) + "_"
+ std::to_string(trial) + ".dat";
log.open(filename, std::ios_base::app);
if (not log.is_open())
{
std::cerr << "Log file " << filename << " could not be opened!\n";
std::exit(EXIT_FAILURE);
}
}
/* Log a line of relevant algorithm information (best and average
fitness and size plus adjusted best fitness). */
void
log_info(const unsigned int verbosity, const std::string& logs_dir,
const std::time_t& time, const int& trial, const int& iteration,
const Individual& best, const vector <Individual>& population)
{
// Don't log if verbosity is zero, but still allow calls to this function.
if (verbosity == 0)
return;
double total_fitness =
std::accumulate(population.begin(), population.end(), 0.,
[](const double& a, const Individual& b)->double const
{
return a + b.get_adjusted();
});
int total_size =
std::accumulate(population.begin(), population.end(), 0,
[](const int& a, const Individual& b)->double const
{
return a + b.get_total();
});
std::ofstream log;
open_log(log, time, trial, logs_dir);
log << iteration << "\t"
<< best.get_fitness() << "\t"
<< best.get_adjusted() << "\t"
<< total_fitness / population.size() << "\t"
<< best.get_total() << "\t"
<< total_size / population.size() << "\n";
log.close();
}
/* Create an initial population using "ramped half-and-half" (half
full trees, half randomly grown trees, all to random depths
between 0 and maximum depth). */
vector<Individual>
new_population(const Options& options)
{
vector<Individual> population;
int_dist depth_dist{0, static_cast<int>(options.max_depth)}; // ramped
for (unsigned int i = 0; i < options.population_size; ++i)
{
/* The depth is ramped, and so drawn randomly for each
individual. */
unsigned int depth = depth_dist(rg.engine);
population.emplace_back(Individual{
depth, options.grow_chance, options.map});
}
return population;
}
/* Return best candidate from size number of contestants randomly
drawn from population. */
Individual
selection(const unsigned int& size, const vector<Individual>& population)
{
int_dist dist{0, static_cast<int>(population.size()) - 1}; // closed interval
vector<Individual> contestants;
for (unsigned int i = 0; i < size; ++i)
contestants.emplace_back(population[dist(rg.engine)]);
return *std::min_element(contestants.begin(), contestants.end(),
compare_fitness);
}
/* Return size number of selected, recombined, mutated, and
re-evaluated children. */
const vector<Individual>
get_children(const unsigned long& size,
const vector<Individual>& population, const Options& options)
{
// Select parents for children.
vector<Individual> nodes;
while (nodes.size() != size)
{
Individual mother = selection(options.tournament_size, population);
Individual father = selection(options.tournament_size, population);
// Crossover with probability.
real_dist dist{0, 1};
if (dist(rg.engine) < options.crossover_chance)
crossover(options.internals_chance, mother, father);
// Place mother and father in nodes.
nodes.emplace_back(mother);
nodes.emplace_back(father);
}
for (Individual& child : nodes)
{
child.mutate(options.mutate_chance); // Mutate children
child.evaluate(options.map, options.penalty); // Evaluate children
}
return nodes;
}
/* Return new offspring population reassembled from parallel calls to
get_children () delegate. */
vector<Individual>
new_offspring(const Options& options, const vector<Individual>& population)
{
vector<Individual> offspring;
offspring.reserve(population.size());
// Determine proper number of threads and subsequent block size.
const unsigned long hardware_threads = std::thread::hardware_concurrency();
const unsigned long num_threads
= hardware_threads != 0 ? hardware_threads : 2;
assert(num_threads == 1 or population.size() % num_threads == 0);
const unsigned long block_size = population.size() / num_threads;
vector<std::future<const vector<Individual>>> results;
// Spawn threads.
for (unsigned long i = 0; i < num_threads; ++i)
results.emplace_back(std::async(std::launch::async, get_children,
block_size, std::ref(population),
options));
// Gather results and reassemble. TODO: Find O(1) solution to this.
for (std::future<const vector<Individual>>& result : results)
{
const vector<Individual> nodes = result.get();
offspring.insert(offspring.end(), nodes.begin(), nodes.end());
}
assert(offspring.size() == population.size());
return offspring;
}
/* The actual genetic algorithm applied which (hopefully) produces a
well-fit expression for a given dataset. */
const individual::Individual
genetic(const Options& options, const std::time_t time, const int& trial)
{
// Start logging
std::ofstream log;
if (options.verbosity > 0)
{
open_log(log, time, trial, options.logs_dir);
log << "# running a Genetic Program @ "
<< std::ctime(&time)
<< "# initial depth: " << options.max_depth
<< ", iterations: " << options.iterations
<< ", population size: " << options.population_size
<< ", tournament size: " << options.tournament_size << "\n"
<< "# raw fitness - best (adjusted) fitness - average (adjusted) fitness - size of best - average size\n";
log.close();
}
// Begin timing algorithm.
std::chrono::time_point<std::chrono::system_clock> start, end;
start = std::chrono::system_clock::now();
// Create initial population.
vector<Individual> population = new_population(options);
Individual best;
// Run algorithm to termination.
for (unsigned int i = 0; i < options.iterations; ++i)
{
// Find best Individual of current population.
best = *std::min_element(population.begin(), population.end(),
compare_fitness);
// Launch background logging thread.
auto log_thread = std::async(std::launch::async, log_info,
options.verbosity, options.logs_dir, time,
trial, i, best, population);
// Create replacement population.
vector<Individual> offspring = new_offspring(options, population);
// Perform elitism replacement of random individuals.
int_dist dist{0, static_cast<int>(options.population_size) - 1};
for (unsigned int e = 0; e < options.elitism_size; ++e)
offspring[dist(rg.engine)] = best;
// Replace current population with offspring.
population = offspring;
// Sync with background logging thread.
log_thread.wait();
}
// End timing algorithm.
end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
// Log time information.
if (options.verbosity > 0)
{
open_log(log, time, trial, options.logs_dir);
log << best.print() << best.print_formula()
<< "# finished computation @ " << std::ctime(&end_time)
<< "# elapsed time: " << elapsed_seconds.count() << "s\n";
log.close();
}
// Log evaluation plot data of best individual.
std::ofstream plot;
open_log(plot, time, trial, options.plots_dir);
plot << best.evaluate(options.map, options.penalty, true);
plot.close();
return best;
}
}
<commit_msg>Updating fitness comparison (bigger is now better)<commit_after>/* algorithm.cpp - CS 472 Project #2: Genetic Programming
* Copyright 2014 Andrew Schwartzmeyer
*
* Source file for algorithm namespace
*/
#include <algorithm>
#include <cassert>
#include <ctime>
#include <iostream>
#include <fstream>
#include <future>
#include <thread>
#include "algorithm.hpp"
#include "../individual/individual.hpp"
#include "../options/options.hpp"
#include "../random_generator/random_generator.hpp"
namespace algorithm
{
using std::vector;
using individual::Individual;
using options::Options;
using namespace random_generator;
// Returns true if "a" is closer to 0 than "b" and is also normal.
bool
compare_fitness(const Individual& a, const Individual& b)
{
return std::isnormal(a.get_fitness())
? (a.get_fitness() > b.get_fitness()) : false;
}
// Opens the appropriate log file for given time, trial, and folder.
void
open_log(std::ofstream& log, const std::time_t& time, const int& trial,
const std::string& folder)
{
std::string filename = folder + std::to_string(time) + "_"
+ std::to_string(trial) + ".dat";
log.open(filename, std::ios_base::app);
if (not log.is_open())
{
std::cerr << "Log file " << filename << " could not be opened!\n";
std::exit(EXIT_FAILURE);
}
}
/* Log a line of relevant algorithm information (best and average
fitness and size plus adjusted best fitness). */
void
log_info(const unsigned int verbosity, const std::string& logs_dir,
const std::time_t& time, const int& trial, const int& iteration,
const Individual& best, const vector <Individual>& population)
{
// Don't log if verbosity is zero, but still allow calls to this function.
if (verbosity == 0)
return;
double total_fitness =
std::accumulate(population.begin(), population.end(), 0.,
[](const double& a, const Individual& b)->double const
{
return a + b.get_adjusted();
});
int total_size =
std::accumulate(population.begin(), population.end(), 0,
[](const int& a, const Individual& b)->double const
{
return a + b.get_total();
});
std::ofstream log;
open_log(log, time, trial, logs_dir);
log << iteration << "\t"
<< best.get_fitness() << "\t"
<< best.get_adjusted() << "\t"
<< total_fitness / population.size() << "\t"
<< best.get_total() << "\t"
<< total_size / population.size() << "\n";
log.close();
}
/* Create an initial population using "ramped half-and-half" (half
full trees, half randomly grown trees, all to random depths
between 0 and maximum depth). */
vector<Individual>
new_population(const Options& options)
{
vector<Individual> population;
int_dist depth_dist{0, static_cast<int>(options.max_depth)}; // ramped
for (unsigned int i = 0; i < options.population_size; ++i)
{
/* The depth is ramped, and so drawn randomly for each
individual. */
unsigned int depth = depth_dist(rg.engine);
population.emplace_back(Individual{
depth, options.grow_chance, options.map});
}
return population;
}
/* Return best candidate from size number of contestants randomly
drawn from population. */
Individual
selection(const unsigned int& size, const vector<Individual>& population)
{
int_dist dist{0, static_cast<int>(population.size()) - 1}; // closed interval
vector<Individual> contestants;
for (unsigned int i = 0; i < size; ++i)
contestants.emplace_back(population[dist(rg.engine)]);
return *std::min_element(contestants.begin(), contestants.end(),
compare_fitness);
}
/* Return size number of selected, recombined, mutated, and
re-evaluated children. */
const vector<Individual>
get_children(const unsigned long& size,
const vector<Individual>& population, const Options& options)
{
// Select parents for children.
vector<Individual> nodes;
while (nodes.size() != size)
{
Individual mother = selection(options.tournament_size, population);
Individual father = selection(options.tournament_size, population);
// Crossover with probability.
real_dist dist{0, 1};
if (dist(rg.engine) < options.crossover_chance)
crossover(options.internals_chance, mother, father);
// Place mother and father in nodes.
nodes.emplace_back(mother);
nodes.emplace_back(father);
}
for (Individual& child : nodes)
{
child.mutate(options.mutate_chance); // Mutate children
child.evaluate(options.map, options.penalty); // Evaluate children
}
return nodes;
}
/* Return new offspring population reassembled from parallel calls to
get_children () delegate. */
vector<Individual>
new_offspring(const Options& options, const vector<Individual>& population)
{
vector<Individual> offspring;
offspring.reserve(population.size());
// Determine proper number of threads and subsequent block size.
const unsigned long hardware_threads = std::thread::hardware_concurrency();
const unsigned long num_threads
= hardware_threads != 0 ? hardware_threads : 2;
assert(num_threads == 1 or population.size() % num_threads == 0);
const unsigned long block_size = population.size() / num_threads;
vector<std::future<const vector<Individual>>> results;
// Spawn threads.
for (unsigned long i = 0; i < num_threads; ++i)
results.emplace_back(std::async(std::launch::async, get_children,
block_size, std::ref(population),
options));
// Gather results and reassemble. TODO: Find O(1) solution to this.
for (std::future<const vector<Individual>>& result : results)
{
const vector<Individual> nodes = result.get();
offspring.insert(offspring.end(), nodes.begin(), nodes.end());
}
assert(offspring.size() == population.size());
return offspring;
}
/* The actual genetic algorithm applied which (hopefully) produces a
well-fit expression for a given dataset. */
const individual::Individual
genetic(const Options& options, const std::time_t time, const int& trial)
{
// Start logging
std::ofstream log;
if (options.verbosity > 0)
{
open_log(log, time, trial, options.logs_dir);
log << "# running a Genetic Program @ "
<< std::ctime(&time)
<< "# initial depth: " << options.max_depth
<< ", iterations: " << options.iterations
<< ", population size: " << options.population_size
<< ", tournament size: " << options.tournament_size << "\n"
<< "# raw fitness - best (adjusted) fitness - average (adjusted) fitness - size of best - average size\n";
log.close();
}
// Begin timing algorithm.
std::chrono::time_point<std::chrono::system_clock> start, end;
start = std::chrono::system_clock::now();
// Create initial population.
vector<Individual> population = new_population(options);
Individual best;
// Run algorithm to termination.
for (unsigned int i = 0; i < options.iterations; ++i)
{
// Find best Individual of current population.
best = *std::min_element(population.begin(), population.end(),
compare_fitness);
// Launch background logging thread.
auto log_thread = std::async(std::launch::async, log_info,
options.verbosity, options.logs_dir, time,
trial, i, best, population);
// Create replacement population.
vector<Individual> offspring = new_offspring(options, population);
// Perform elitism replacement of random individuals.
int_dist dist{0, static_cast<int>(options.population_size) - 1};
for (unsigned int e = 0; e < options.elitism_size; ++e)
offspring[dist(rg.engine)] = best;
// Replace current population with offspring.
population = offspring;
// Sync with background logging thread.
log_thread.wait();
}
// End timing algorithm.
end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
// Log time information.
if (options.verbosity > 0)
{
open_log(log, time, trial, options.logs_dir);
log << best.print() << best.print_formula()
<< "# finished computation @ " << std::ctime(&end_time)
<< "# elapsed time: " << elapsed_seconds.count() << "s\n";
log.close();
}
// Log evaluation plot data of best individual.
std::ofstream plot;
open_log(plot, time, trial, options.plots_dir);
plot << best.evaluate(options.map, options.penalty, true);
plot.close();
return best;
}
}
<|endoftext|>
|
<commit_before>## This file is a template. The comment below is emitted
## into the rendered file; feel free to edit this file.
// !!! WARNING: This is a GENERATED Code..Please do NOT Edit !!!
<%
interfaceDict = {}
%>\
%for key in sensorDict.iterkeys():
<%
sensor = sensorDict[key]
serviceInterface = sensor["serviceInterface"]
if serviceInterface == "org.freedesktop.DBus.Properties":
updateFunc = "set::"
getFunc = "get::"
elif serviceInterface == "xyz.openbmc_project.Inventory.Manager":
updateFunc = "notify::"
getFunc = "inventory::get::"
else:
assert "Un-supported interface: " + serviceInterface
endif
if serviceInterface not in interfaceDict:
interfaceDict[serviceInterface] = {}
interfaceDict[serviceInterface]["updateFunc"] = updateFunc
interfaceDict[serviceInterface]["getFunc"] = getFunc
%>\
% endfor
#include "types.hpp"
#include "sensordatahandler.hpp"
using namespace ipmi::sensor;
%for key in sensorDict.iterkeys():
<%
sensor = sensorDict[key]
readingType = sensor["readingType"]
interfaces = sensor["interfaces"]
for interface, properties in interfaces.items():
for property, values in properties.items():
for offset, attributes in values.items():
type = attributes["type"]
%>\
%if "readingAssertion" == readingType:
namespace sensor_${key}
{
inline ipmi_ret_t readingAssertion(const SetSensorReadingReq& cmdData,
const Info& sensorInfo)
{
return set::readingAssertion<${type}>(cmdData, sensorInfo);
}
namespace get
{
inline GetSensorResponse readingAssertion(const Info& sensorInfo)
{
return ipmi::sensor::get::readingAssertion<${type}>(sensorInfo);
}
} //namespace get
} // namespace sensor_${key}
%elif "readingData" == readingType:
namespace sensor_${key}
{
inline ipmi_ret_t readingData(const SetSensorReadingReq& cmdData,
const Info& sensorInfo)
{
return set::readingData<${type}>(cmdData, sensorInfo);
}
namespace get
{
inline GetSensorResponse readingData(const Info& sensorInfo)
{
return ipmi::sensor::get::readingData<${type}>(sensorInfo);
}
} //namespace get
} // namespace sensor_${key}
%endif
% endfor
extern const IdInfoMap sensors = {
% for key in sensorDict.iterkeys():
% if key:
{${key},{
<%
sensor = sensorDict[key]
interfaces = sensor["interfaces"]
path = sensor["path"]
serviceInterface = sensor["serviceInterface"]
sensorType = sensor["sensorType"]
readingType = sensor["sensorReadingType"]
multiplier = sensor.get("multiplierM", 1)
offsetB = sensor.get("offsetB", 0)
exp = sensor.get("bExp", 0)
valueReadingType = sensor["readingType"]
updateFunc = interfaceDict[serviceInterface]["updateFunc"]
updateFunc += sensor["readingType"]
getFunc = interfaceDict[serviceInterface]["getFunc"]
getFunc += sensor["readingType"]
if "readingAssertion" == valueReadingType:
updateFunc = "sensor_" + str(key) + "::" + valueReadingType
getFunc = "sensor_" + str(key) + "::get::" + valueReadingType
elif "readingData" == valueReadingType:
updateFunc = "sensor_" + str(key) + "::" + valueReadingType
getFunc = "sensor_" + str(key) + "::get::" + valueReadingType
sensorInterface = serviceInterface
if serviceInterface == "org.freedesktop.DBus.Properties":
sensorInterface = next(iter(interfaces))
mutability = sensor.get("mutability", "Mutability::Read")
%>
${sensorType},"${path}","${sensorInterface}",${readingType},${multiplier},
${offsetB},${exp},${offsetB * pow(10,exp)},${updateFunc},${getFunc},Mutability(${mutability}),{
% for interface,properties in interfaces.items():
{"${interface}",{
% for dbus_property,property_value in properties.items():
{"${dbus_property}",{
% for offset,values in property_value.items():
{ ${offset},{
% if offset == 0xFF:
}},
<% continue %>\
% endif
<% valueType = values["type"] %>\
% for name,value in values.items():
% if name == "type":
<% continue %>\
% endif
% if valueType == "string":
std::string("${value}"),
% elif valueType == "bool":
<% value = str(value).lower() %>\
${value},
% else:
${value},
% endif
% endfor
}
},
% endfor
}},
% endfor
}},
% endfor
},
}},
% endif
% endfor
};
<commit_msg>sensor: Pass the dbus property type as a template parameter<commit_after>## This file is a template. The comment below is emitted
## into the rendered file; feel free to edit this file.
// !!! WARNING: This is a GENERATED Code..Please do NOT Edit !!!
<%
interfaceDict = {}
%>\
%for key in sensorDict.iterkeys():
<%
sensor = sensorDict[key]
serviceInterface = sensor["serviceInterface"]
if serviceInterface == "org.freedesktop.DBus.Properties":
updateFunc = "set::"
getFunc = "get::"
elif serviceInterface == "xyz.openbmc_project.Inventory.Manager":
updateFunc = "notify::"
getFunc = "inventory::get::"
else:
assert "Un-supported interface: " + serviceInterface
endif
if serviceInterface not in interfaceDict:
interfaceDict[serviceInterface] = {}
interfaceDict[serviceInterface]["updateFunc"] = updateFunc
interfaceDict[serviceInterface]["getFunc"] = getFunc
%>\
% endfor
#include "types.hpp"
#include "sensordatahandler.hpp"
using namespace ipmi::sensor;
extern const IdInfoMap sensors = {
% for key in sensorDict.iterkeys():
% if key:
{${key},{
<%
sensor = sensorDict[key]
interfaces = sensor["interfaces"]
path = sensor["path"]
serviceInterface = sensor["serviceInterface"]
sensorType = sensor["sensorType"]
readingType = sensor["sensorReadingType"]
multiplier = sensor.get("multiplierM", 1)
offsetB = sensor.get("offsetB", 0)
exp = sensor.get("bExp", 0)
valueReadingType = sensor["readingType"]
updateFunc = interfaceDict[serviceInterface]["updateFunc"]
updateFunc += sensor["readingType"]
getFunc = interfaceDict[serviceInterface]["getFunc"]
getFunc += sensor["readingType"]
if "readingAssertion" == valueReadingType or "readingData" == valueReadingType:
for interface,properties in interfaces.items():
for dbus_property,property_value in properties.items():
for offset,values in property_value.items():
valueType = values["type"]
updateFunc = "set::" + valueReadingType + "<" + valueType + ">"
getFunc = "get::" + valueReadingType + "<" + valueType + ">"
sensorInterface = serviceInterface
if serviceInterface == "org.freedesktop.DBus.Properties":
sensorInterface = next(iter(interfaces))
mutability = sensor.get("mutability", "Mutability::Read")
%>
${sensorType},"${path}","${sensorInterface}",${readingType},${multiplier},
${offsetB},${exp},${offsetB * pow(10,exp)},${updateFunc},${getFunc},Mutability(${mutability}),{
% for interface,properties in interfaces.items():
{"${interface}",{
% for dbus_property,property_value in properties.items():
{"${dbus_property}",{
% for offset,values in property_value.items():
{ ${offset},{
% if offset == 0xFF:
}},
<% continue %>\
% endif
<% valueType = values["type"] %>\
% for name,value in values.items():
% if name == "type":
<% continue %>\
% endif
% if valueType == "string":
std::string("${value}"),
% elif valueType == "bool":
<% value = str(value).lower() %>\
${value},
% else:
${value},
% endif
% endfor
}
},
% endfor
}},
% endfor
}},
% endfor
},
}},
% endif
% endfor
};
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fucopy.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: kz $ $Date: 2006-12-13 17:55:29 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "fucopy.hxx"
#ifndef _SFX_PROGRESS_HXX
#include <sfx2/progress.hxx>
#endif
#include <svx/svxids.hrc>
#include "sdresid.hxx"
#include "sdattr.hxx"
#include "strings.hrc"
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#include "drawdoc.hxx"
#include "DrawDocShell.hxx"
#ifndef _SV_WRKWIN_HXX
#include <vcl/wrkwin.hxx>
#endif
#ifndef _SVDOBJ_HXX //autogen
#include <svx/svdobj.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SVX_XCOLORITEM_HXX //autogen
#include <svx/xcolit.hxx>
#endif
#ifndef _SVX_XFLCLIT_HXX //autogen
#include <svx/xflclit.hxx>
#endif
#ifndef _XDEF_HXX //autogen
#include <svx/xdef.hxx>
#endif
#ifndef SVX_XFILLIT0_HXX //autogen
#include <svx/xfillit0.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#include "sdabstdlg.hxx"
#include "copydlg.hrc"
namespace sd {
TYPEINIT1( FuCopy, FuPoor );
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuCopy::FuCopy (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq)
: FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
}
FunctionReference FuCopy::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
FunctionReference xFunc( new FuCopy( pViewSh, pWin, pView, pDoc, rReq ) );
xFunc->DoExecute(rReq);
return xFunc;
}
void FuCopy::DoExecute( SfxRequest& rReq )
{
if( mpView->AreObjectsMarked() )
{
// Undo
String aString( mpView->GetDescriptionOfMarkedObjects() );
aString.Append( sal_Unicode(' ') );
aString.Append( String( SdResId( STR_UNDO_COPYOBJECTS ) ) );
mpView->BegUndo( aString );
const SfxItemSet* pArgs = rReq.GetArgs();
if( !pArgs )
{
SfxItemSet aSet( mpViewShell->GetPool(),
ATTR_COPY_START, ATTR_COPY_END, 0 );
// Farb-Attribut angeben
SfxItemSet aAttr( mpDoc->GetPool() );
mpView->GetAttributes( aAttr );
const SfxPoolItem* pPoolItem = NULL;
if( SFX_ITEM_SET == aAttr.GetItemState( XATTR_FILLSTYLE, TRUE, &pPoolItem ) )
{
XFillStyle eStyle = ( ( const XFillStyleItem* ) pPoolItem )->GetValue();
if( eStyle == XFILL_SOLID &&
SFX_ITEM_SET == aAttr.GetItemState( XATTR_FILLCOLOR, TRUE, &pPoolItem ) )
{
const XFillColorItem* pItem = ( const XFillColorItem* ) pPoolItem;
XColorItem aXColorItem( ATTR_COPY_START_COLOR, pItem->GetName(),
pItem->GetColorValue() );
aSet.Put( aXColorItem );
}
}
SdAbstractDialogFactory* pFact = SdAbstractDialogFactory::Create();
if( pFact )
{
AbstractCopyDlg* pDlg = pFact->CreateCopyDlg(NULL, aSet, mpDoc->GetColorTable(), mpView );
if( pDlg )
{
USHORT nResult = pDlg->Execute();
switch( nResult )
{
case RET_OK:
pDlg->GetAttr( aSet );
rReq.Done( aSet );
pArgs = rReq.GetArgs();
break;
default:
{
delete pDlg;
mpView->EndUndo();
}
return; // Abbruch
}
delete( pDlg );
}
}
}
Rectangle aRect;
INT32 lWidth = 0, lHeight = 0, lSizeX = 0L, lSizeY = 0L, lAngle = 0L;
UINT16 nNumber = 0;
Color aStartColor, aEndColor;
BOOL bColor = FALSE;
const SfxPoolItem* pPoolItem = NULL;
// Anzahl
if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_NUMBER, TRUE, &pPoolItem ) )
nNumber = ( ( const SfxUInt16Item* ) pPoolItem )->GetValue();
// Verschiebung
if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_MOVE_X, TRUE, &pPoolItem ) )
lSizeX = ( ( const SfxInt32Item* ) pPoolItem )->GetValue();
if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_MOVE_Y, TRUE, &pPoolItem ) )
lSizeY = ( ( const SfxInt32Item* ) pPoolItem )->GetValue();
if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_ANGLE, TRUE, &pPoolItem ) )
lAngle = ( ( const SfxInt32Item* )pPoolItem )->GetValue();
// Verrgroesserung / Verkleinerung
if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_WIDTH, TRUE, &pPoolItem ) )
lWidth = ( ( const SfxInt32Item* ) pPoolItem )->GetValue();
if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_HEIGHT, TRUE, &pPoolItem ) )
lHeight = ( ( const SfxInt32Item* ) pPoolItem )->GetValue();
// Startfarbe / Endfarbe
if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_START_COLOR, TRUE, &pPoolItem ) )
{
aStartColor = ( ( const XColorItem* ) pPoolItem )->GetColorValue();
bColor = TRUE;
}
if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_END_COLOR, TRUE, &pPoolItem ) )
{
aEndColor = ( ( const XColorItem* ) pPoolItem )->GetColorValue();
if( aStartColor == aEndColor )
bColor = FALSE;
}
else
bColor = FALSE;
// Handles wegnehmen
//HMHmpView->HideMarkHdl();
SfxProgress* pProgress = NULL;
BOOL bWaiting = FALSE;
if( nNumber > 1 )
{
String aStr( SdResId( STR_OBJECTS ) );
aStr.Append( sal_Unicode(' ') );
aStr.Append( String( SdResId( STR_UNDO_COPYOBJECTS ) ) );
pProgress = new SfxProgress( mpDocSh, aStr, nNumber );
mpDocSh->SetWaitCursor( TRUE );
bWaiting = TRUE;
}
const SdrMarkList aMarkList( mpView->GetMarkedObjectList() );
const ULONG nMarkCount = aMarkList.GetMarkCount();
SdrObject* pObj = NULL;
// Anzahl moeglicher Kopien berechnen
aRect = mpView->GetAllMarkedRect();
if( lWidth < 0L )
{
long nTmp = ( aRect.Right() - aRect.Left() ) / -lWidth;
nNumber = (UINT16) Min( nTmp, (long)nNumber );
}
if( lHeight < 0L )
{
long nTmp = ( aRect.Bottom() - aRect.Top() ) / -lHeight;
nNumber = (UINT16) Min( nTmp, (long)nNumber );
}
for( USHORT i = 1; i <= nNumber; i++ )
{
if( pProgress )
pProgress->SetState( i );
aRect = mpView->GetAllMarkedRect();
if( ( 1 == i ) && bColor )
{
SfxItemSet aNewSet( mpViewShell->GetPool(), XATTR_FILLSTYLE, XATTR_FILLCOLOR, 0L );
aNewSet.Put( XFillStyleItem( XFILL_SOLID ) );
aNewSet.Put( XFillColorItem( String(), aStartColor ) );
mpView->SetAttributes( aNewSet );
}
// make a copy of selected objects
mpView->CopyMarked();
// get newly selected objects
SdrMarkList aCopyMarkList( mpView->GetMarkedObjectList() );
ULONG j, nCopyMarkCount = aMarkList.GetMarkCount();
// set protection flags at marked copies to null
for( j = 0; j < nCopyMarkCount; j++ )
{
pObj = aCopyMarkList.GetMark( j )->GetMarkedSdrObj();
if( pObj )
{
pObj->SetMoveProtect( FALSE );
pObj->SetResizeProtect( FALSE );
}
}
Fraction aWidth( aRect.Right() - aRect.Left() + lWidth, aRect.Right() - aRect.Left() );
Fraction aHeight( aRect.Bottom() - aRect.Top() + lHeight, aRect.Bottom() - aRect.Top() );
if( mpView->IsResizeAllowed() )
mpView->ResizeAllMarked( aRect.TopLeft(), aWidth, aHeight );
if( mpView->IsRotateAllowed() )
mpView->RotateAllMarked( aRect.Center(), lAngle * 100 );
if( mpView->IsMoveAllowed() )
mpView->MoveAllMarked( Size( lSizeX, lSizeY ) );
// set protection flags at marked copies to original values
if( nMarkCount == nCopyMarkCount )
{
for( j = 0; j < nMarkCount; j++ )
{
SdrObject* pSrcObj = aMarkList.GetMark( j )->GetMarkedSdrObj();
SdrObject* pDstObj = aCopyMarkList.GetMark( j )->GetMarkedSdrObj();
if( pSrcObj && pDstObj &&
( pSrcObj->GetObjInventor() == pDstObj->GetObjInventor() ) &&
( pSrcObj->GetObjIdentifier() == pDstObj->GetObjIdentifier() ) )
{
pDstObj->SetMoveProtect( pSrcObj->IsMoveProtect() );
pDstObj->SetResizeProtect( pSrcObj->IsResizeProtect() );
}
}
}
if( bColor )
{
// Koennte man sicher noch optimieren, wuerde aber u.U.
// zu Rundungsfehlern fuehren
BYTE nRed = aStartColor.GetRed() + (BYTE) ( ( (long) aEndColor.GetRed() - (long) aStartColor.GetRed() ) * (long) i / (long) nNumber );
BYTE nGreen = aStartColor.GetGreen() + (BYTE) ( ( (long) aEndColor.GetGreen() - (long) aStartColor.GetGreen() ) * (long) i / (long) nNumber );
BYTE nBlue = aStartColor.GetBlue() + (BYTE) ( ( (long) aEndColor.GetBlue() - (long) aStartColor.GetBlue() ) * (long) i / (long) nNumber );
Color aNewColor( nRed, nGreen, nBlue );
SfxItemSet aNewSet( mpViewShell->GetPool(), XATTR_FILLSTYLE, XATTR_FILLCOLOR, 0L );
aNewSet.Put( XFillStyleItem( XFILL_SOLID ) );
aNewSet.Put( XFillColorItem( String(), aNewColor ) );
mpView->SetAttributes( aNewSet );
}
}
if ( pProgress )
delete pProgress;
if ( bWaiting )
mpDocSh->SetWaitCursor( FALSE );
// Handles zeigen
mpView->AdjustMarkHdl(); //HMH TRUE );
//HMHpView->ShowMarkHdl();
mpView->EndUndo();
}
}
} // end of namespace
<commit_msg>INTEGRATION: CWS changefileheader (1.14.298); FILE MERGED 2008/04/01 15:34:32 thb 1.14.298.3: #i85898# Stripping all external header guards 2008/04/01 12:38:52 thb 1.14.298.2: #i85898# Stripping all external header guards 2008/03/31 13:58:04 rt 1.14.298.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fucopy.cxx,v $
* $Revision: 1.15 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "fucopy.hxx"
#include <sfx2/progress.hxx>
#include <svx/svxids.hrc>
#include "sdresid.hxx"
#include "sdattr.hxx"
#include "strings.hrc"
#include "ViewShell.hxx"
#include "View.hxx"
#include "drawdoc.hxx"
#include "DrawDocShell.hxx"
#include <vcl/wrkwin.hxx>
#include <svx/svdobj.hxx>
#include <vcl/msgbox.hxx>
#include <sfx2/app.hxx>
#include <svx/xcolit.hxx>
#include <svx/xflclit.hxx>
#include <svx/xdef.hxx>
#include <svx/xfillit0.hxx>
#include <sfx2/request.hxx>
#include "sdabstdlg.hxx"
#include "copydlg.hrc"
namespace sd {
TYPEINIT1( FuCopy, FuPoor );
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuCopy::FuCopy (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq)
: FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
}
FunctionReference FuCopy::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
FunctionReference xFunc( new FuCopy( pViewSh, pWin, pView, pDoc, rReq ) );
xFunc->DoExecute(rReq);
return xFunc;
}
void FuCopy::DoExecute( SfxRequest& rReq )
{
if( mpView->AreObjectsMarked() )
{
// Undo
String aString( mpView->GetDescriptionOfMarkedObjects() );
aString.Append( sal_Unicode(' ') );
aString.Append( String( SdResId( STR_UNDO_COPYOBJECTS ) ) );
mpView->BegUndo( aString );
const SfxItemSet* pArgs = rReq.GetArgs();
if( !pArgs )
{
SfxItemSet aSet( mpViewShell->GetPool(),
ATTR_COPY_START, ATTR_COPY_END, 0 );
// Farb-Attribut angeben
SfxItemSet aAttr( mpDoc->GetPool() );
mpView->GetAttributes( aAttr );
const SfxPoolItem* pPoolItem = NULL;
if( SFX_ITEM_SET == aAttr.GetItemState( XATTR_FILLSTYLE, TRUE, &pPoolItem ) )
{
XFillStyle eStyle = ( ( const XFillStyleItem* ) pPoolItem )->GetValue();
if( eStyle == XFILL_SOLID &&
SFX_ITEM_SET == aAttr.GetItemState( XATTR_FILLCOLOR, TRUE, &pPoolItem ) )
{
const XFillColorItem* pItem = ( const XFillColorItem* ) pPoolItem;
XColorItem aXColorItem( ATTR_COPY_START_COLOR, pItem->GetName(),
pItem->GetColorValue() );
aSet.Put( aXColorItem );
}
}
SdAbstractDialogFactory* pFact = SdAbstractDialogFactory::Create();
if( pFact )
{
AbstractCopyDlg* pDlg = pFact->CreateCopyDlg(NULL, aSet, mpDoc->GetColorTable(), mpView );
if( pDlg )
{
USHORT nResult = pDlg->Execute();
switch( nResult )
{
case RET_OK:
pDlg->GetAttr( aSet );
rReq.Done( aSet );
pArgs = rReq.GetArgs();
break;
default:
{
delete pDlg;
mpView->EndUndo();
}
return; // Abbruch
}
delete( pDlg );
}
}
}
Rectangle aRect;
INT32 lWidth = 0, lHeight = 0, lSizeX = 0L, lSizeY = 0L, lAngle = 0L;
UINT16 nNumber = 0;
Color aStartColor, aEndColor;
BOOL bColor = FALSE;
const SfxPoolItem* pPoolItem = NULL;
// Anzahl
if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_NUMBER, TRUE, &pPoolItem ) )
nNumber = ( ( const SfxUInt16Item* ) pPoolItem )->GetValue();
// Verschiebung
if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_MOVE_X, TRUE, &pPoolItem ) )
lSizeX = ( ( const SfxInt32Item* ) pPoolItem )->GetValue();
if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_MOVE_Y, TRUE, &pPoolItem ) )
lSizeY = ( ( const SfxInt32Item* ) pPoolItem )->GetValue();
if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_ANGLE, TRUE, &pPoolItem ) )
lAngle = ( ( const SfxInt32Item* )pPoolItem )->GetValue();
// Verrgroesserung / Verkleinerung
if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_WIDTH, TRUE, &pPoolItem ) )
lWidth = ( ( const SfxInt32Item* ) pPoolItem )->GetValue();
if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_HEIGHT, TRUE, &pPoolItem ) )
lHeight = ( ( const SfxInt32Item* ) pPoolItem )->GetValue();
// Startfarbe / Endfarbe
if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_START_COLOR, TRUE, &pPoolItem ) )
{
aStartColor = ( ( const XColorItem* ) pPoolItem )->GetColorValue();
bColor = TRUE;
}
if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_END_COLOR, TRUE, &pPoolItem ) )
{
aEndColor = ( ( const XColorItem* ) pPoolItem )->GetColorValue();
if( aStartColor == aEndColor )
bColor = FALSE;
}
else
bColor = FALSE;
// Handles wegnehmen
//HMHmpView->HideMarkHdl();
SfxProgress* pProgress = NULL;
BOOL bWaiting = FALSE;
if( nNumber > 1 )
{
String aStr( SdResId( STR_OBJECTS ) );
aStr.Append( sal_Unicode(' ') );
aStr.Append( String( SdResId( STR_UNDO_COPYOBJECTS ) ) );
pProgress = new SfxProgress( mpDocSh, aStr, nNumber );
mpDocSh->SetWaitCursor( TRUE );
bWaiting = TRUE;
}
const SdrMarkList aMarkList( mpView->GetMarkedObjectList() );
const ULONG nMarkCount = aMarkList.GetMarkCount();
SdrObject* pObj = NULL;
// Anzahl moeglicher Kopien berechnen
aRect = mpView->GetAllMarkedRect();
if( lWidth < 0L )
{
long nTmp = ( aRect.Right() - aRect.Left() ) / -lWidth;
nNumber = (UINT16) Min( nTmp, (long)nNumber );
}
if( lHeight < 0L )
{
long nTmp = ( aRect.Bottom() - aRect.Top() ) / -lHeight;
nNumber = (UINT16) Min( nTmp, (long)nNumber );
}
for( USHORT i = 1; i <= nNumber; i++ )
{
if( pProgress )
pProgress->SetState( i );
aRect = mpView->GetAllMarkedRect();
if( ( 1 == i ) && bColor )
{
SfxItemSet aNewSet( mpViewShell->GetPool(), XATTR_FILLSTYLE, XATTR_FILLCOLOR, 0L );
aNewSet.Put( XFillStyleItem( XFILL_SOLID ) );
aNewSet.Put( XFillColorItem( String(), aStartColor ) );
mpView->SetAttributes( aNewSet );
}
// make a copy of selected objects
mpView->CopyMarked();
// get newly selected objects
SdrMarkList aCopyMarkList( mpView->GetMarkedObjectList() );
ULONG j, nCopyMarkCount = aMarkList.GetMarkCount();
// set protection flags at marked copies to null
for( j = 0; j < nCopyMarkCount; j++ )
{
pObj = aCopyMarkList.GetMark( j )->GetMarkedSdrObj();
if( pObj )
{
pObj->SetMoveProtect( FALSE );
pObj->SetResizeProtect( FALSE );
}
}
Fraction aWidth( aRect.Right() - aRect.Left() + lWidth, aRect.Right() - aRect.Left() );
Fraction aHeight( aRect.Bottom() - aRect.Top() + lHeight, aRect.Bottom() - aRect.Top() );
if( mpView->IsResizeAllowed() )
mpView->ResizeAllMarked( aRect.TopLeft(), aWidth, aHeight );
if( mpView->IsRotateAllowed() )
mpView->RotateAllMarked( aRect.Center(), lAngle * 100 );
if( mpView->IsMoveAllowed() )
mpView->MoveAllMarked( Size( lSizeX, lSizeY ) );
// set protection flags at marked copies to original values
if( nMarkCount == nCopyMarkCount )
{
for( j = 0; j < nMarkCount; j++ )
{
SdrObject* pSrcObj = aMarkList.GetMark( j )->GetMarkedSdrObj();
SdrObject* pDstObj = aCopyMarkList.GetMark( j )->GetMarkedSdrObj();
if( pSrcObj && pDstObj &&
( pSrcObj->GetObjInventor() == pDstObj->GetObjInventor() ) &&
( pSrcObj->GetObjIdentifier() == pDstObj->GetObjIdentifier() ) )
{
pDstObj->SetMoveProtect( pSrcObj->IsMoveProtect() );
pDstObj->SetResizeProtect( pSrcObj->IsResizeProtect() );
}
}
}
if( bColor )
{
// Koennte man sicher noch optimieren, wuerde aber u.U.
// zu Rundungsfehlern fuehren
BYTE nRed = aStartColor.GetRed() + (BYTE) ( ( (long) aEndColor.GetRed() - (long) aStartColor.GetRed() ) * (long) i / (long) nNumber );
BYTE nGreen = aStartColor.GetGreen() + (BYTE) ( ( (long) aEndColor.GetGreen() - (long) aStartColor.GetGreen() ) * (long) i / (long) nNumber );
BYTE nBlue = aStartColor.GetBlue() + (BYTE) ( ( (long) aEndColor.GetBlue() - (long) aStartColor.GetBlue() ) * (long) i / (long) nNumber );
Color aNewColor( nRed, nGreen, nBlue );
SfxItemSet aNewSet( mpViewShell->GetPool(), XATTR_FILLSTYLE, XATTR_FILLCOLOR, 0L );
aNewSet.Put( XFillStyleItem( XFILL_SOLID ) );
aNewSet.Put( XFillColorItem( String(), aNewColor ) );
mpView->SetAttributes( aNewSet );
}
}
if ( pProgress )
delete pProgress;
if ( bWaiting )
mpDocSh->SetWaitCursor( FALSE );
// Handles zeigen
mpView->AdjustMarkHdl(); //HMH TRUE );
//HMHpView->ShowMarkHdl();
mpView->EndUndo();
}
}
} // end of namespace
<|endoftext|>
|
<commit_before>/**
* @file main.cpp
*
* @brief File containing main Q-Learning algorithm and all necessary associated functions to implementing this routine.
*
* @author Machine Learning Team 2015-2016
* @date March, 2016
*/
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string>
#include <sstream>
#include <fstream>
#include "StateSpace.h"
#include "PriorityQueue.h"
#include "State.h"
#include "encoder.h"
#include "CreateModule.h"
/**
* @brief Gives a std::string representation of a primitive type.
*
* @remark Can be used to print priority queue contents.
* @param x Primitive type such as int, double, long ...
* @return std::string conversion of param x
*/
template<typename T> std::string to_string(T x) {
return static_cast<std::ostringstream&>((std::ostringstream() << std::dec << x)).str();
}
/**
* @brief Analog to temperature variable in Boltzmann Distribution, computes 'evolution variable' of system.
*
* This function computes a normal distribution over the parameterised number of loop iterations in order
* to provide a function which explores the state space dilligently initially which then decays off to the
* optimal solution after a large number of loop iterations.
*
* The normal distribution used by this function is:
*
* \f[ a e^{-\frac{bt^2}{c}} + \epsilon \f]
*
* where a, b and c are scaling coefficients (see method body) and \f$\epsilon\f$ is some small offset.
*
* @param t Number of loop iterations.
* @return Value of normal distribution at t loop iterations.
*/
double probabilityFluxDensityCoeffieicent(unsigned long t);
//function to select next action
/**
* @brief Selects an action to perform based on experience, iterations and probabilities.
*
* @param a_queue A priority queue instance storing integral types with double type priorities,
* represents the queue of possible actions with pre-initialised priority levels.
* @param iterations Number of loop iterations completed.
* @return integer corresponding to chosen action
*/
int selectAction(PriorityQueue<int, double>& a_queue, unsigned long iterations);
/**
* @brief Updates the utility (Q-value) of the system.
*
* Utility (Q-Value) of the system is updated via the Temporal Difference Learning Rule given by the following equation,
*
* \f[ Q_{i+1} (s,a) = Q_i (s,a) + \alpha [R(s') + \gamma \underset{a}{max} Q(s',a) - Q_i (s,a)] \f]
*
* where Q represents the utility of a state-action pair, \f$ \alpha \f$ is the learning rate, \f$ \gamma \f$ is the discount
* factor and \f$ max_a (Q) \f$ yields the action-maximum of the Q space. The learning rate should be set to a low value for
* highly stochastic, asymmetric systems or a high value for a lowly stochastic, symmetric system - this value lies between 0 and 1.
* The discount factor (also in the interval [0,1]) represents the time considerations of the learning algorithm, lower values indicate
* "living in the moment", whilst higher values indicate "planning for the future".
*
* @param space Reference to StateSpace object
* @param action Integer code to previous performed action
* @param new_state Reference to State instance giving the new system state
* @param old_state Reference to State instance giving the old system state
* @param alpha Learning rate of temporal difference learning algorithm (in the interval [0,1])
* @param gamma Discount factor applied to q-learning equation (in the interval [0,1])
*/
void updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma);
/**
* @brief Program launcher!
*
* Contains all initialisations including setting up the StateSpace and connecting to robot via a proxy. Holds main
* program loop to perform algorithm continuously using calls to selectAction and updateQ sequentially to update
* utilities and choose most optimal actions to perform based on position and velocity.
*
* @return Program exit code
*/
int main() {
// STUFF WE DONT UNDERSTAND, AND DONT NEED TO
//__________________________________________________________________________________________
//__________________________________________________________________________________________
// Libraries to load
std::string bodyLibName = "bodyinfo";
std::string movementLibName = "movementtools";
// Name of camera module in library
std::string bodyModuleName = "BodyInfo";
std::string movementModuleName = "MovementTools";
// Set broker name, ip and port, finding first available port from 54000
const std::string brokerName = "MotionTimingBroker";
int brokerPort = qi::os::findAvailablePort(54000);
const std::string brokerIp = "0.0.0.0";
// Default parent port and ip
int pport = 9559;
std::string pip = "127.0.0.1";
// Need this for SOAP serialisation of floats to work
setlocale(LC_NUMERIC, "C");
// Create a broker
boost::shared_ptr<AL::ALBroker> broker;
try {
broker = AL::ALBroker::createBroker(
brokerName,
brokerIp,
brokerPort,
pip,
pport,
0);
}
// Throw error and quit if a broker could not be created
catch (...) {
std::cerr << "Failed to connect broker to: "
<< pip
<< ":"
<< pport
<< std::endl;
AL::ALBrokerManager::getInstance()->killAllBroker();
AL::ALBrokerManager::kill();
return 1;
}
// Add the broker to NAOqi
AL::ALBrokerManager::setInstance(broker->fBrokerManager.lock());
AL::ALBrokerManager::getInstance()->addBroker(broker);
CreateModule(movementLibName, movementModuleName, broker, false, true);
CreateModule(bodyLibName, bodyModuleName, broker, false, true);
AL::ALProxy bodyInfoProxy(bodyModuleName, pip, pport);
AL::ALProxy movementToolsProxy(movementModuleName, pip, pport);
AL::ALMotionProxy motion(pip, pport);
//__________________________________________________________________________________________
//__________________________________________________________________________________________
//END OF STUFF WE DONT UNDERSTAND, BREATHE NOW
//learning factor
const double alpha = 0.8;
//discount factor
const double gamma = 0.5;
//seed rng
std::srand(static_cast<unsigned int>(std::time(NULL)));
int action_forwards = FORWARD;
int action_backwards = BACKWARD;
int chosen_action = action_forwards;
//create a priority queue to copy to all the state space priority queues
PriorityQueue<int, double> initiator_queue(MAX);
initiator_queue.enqueueWithPriority(action_forwards, 0);
initiator_queue.enqueueWithPriority(action_backwards, 0);
//create encoder
Encoder encoder;
encoder.Calibrate();
//pause briefly to allow the robot to be given a push if desired
qi::os::msleep(5000);
//create the state space
StateSpace space(100, 50, M_PI * 0.25, 1.0, initiator_queue);
//state objects
State current_state(0, 0, FORWARD);
State old_state(0, 0, FORWARD);
for( unsigned long i = 0; i<500 ;++i ) {
// set current state angle to angle received from encoder
// and set current state velocity to difference in new and
// old state angles over some time difference
current_state.theta = M_PI * (encoder.GetAngle()) / 180;
current_state.theta_dot = (current_state.theta - old_state.theta) / 700; //Needs actual time
current_state.robot_state = static_cast<ROBOT_STATE>(chosen_action);
// call updateQ function with state space, old and current states
// and learning rate, discount factor
updateQ(space, chosen_action, old_state, current_state, alpha, gamma);
// set old_state to current_state
old_state = current_state;
// determine chosen_action for current state
chosen_action = selectAction(space[current_state], i);
// depending upon chosen action, call robot movement tools proxy with either
// swingForwards or swingBackwards commands.
(chosen_action) ? movementToolsProxy.callVoid("swingForwards") : movementToolsProxy.callVoid("swingBackwards");
}
return 1;
}
double probabilityFluxDensityCoeffieicent(unsigned long t) {
return 100.0*std::exp((-8.0*t*t) / (2600.0*2600.0)) + 0.1;//0.1 is an offset
}
int selectAction(PriorityQueue<int, double>& a_queue, unsigned long iterations) {
typedef std::vector<std::pair<int, double> > VecPair ;
//turn priority queue into a vector of pairs
VecPair vec = a_queue.saveOrderedQueueAsVector();
//sum for partition function
double sum = 0.0;
// calculate partition function by iterating over action-values
for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) {
sum += std::exp((iter->second) / probabilityFluxDensityCoeffieicent(iterations));
}
// compute Boltzmann factors for action-values and enqueue to vec
for (VecPair::iterator iter = vec.begin(); iter < vec.end(); ++iter) {
iter->second = std::exp(iter->second / probabilityFluxDensityCoeffieicent(iterations)) / sum;
}
// calculate cumulative probability distribution
for (VecPair::iterator iter = vec.begin()++, end = vec.end(); iter < end; ++iter) {
//second member of pair becomes addition of its current value
//and that of the index before it
iter->second += (iter-1)->second;
}
//generate RN between 0 and 1
double rand_num = static_cast<double>(rand()) / RAND_MAX;
// choose action based on random number relation to priorities within action queue
for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) {
if (rand_num < iter->second)
return iter->first;
}
return -1; //note that this line should never be reached
}
void updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma) {
//oldQ value reference
double oldQ = space[old_state].search(action).second;
//reward given to current state
double R = new_state.getReward();
//optimal Q value for new state i.e. first element
double maxQ = space[new_state].peekFront().second;
//new Q value determined by Q learning algorithm
double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ);
// change priority of action to new Q value
space[old_state].changePriority(action, newQ);
}
/* OLD SELECT ACTION
int selectAction(const PriorityQueue<int, double>& a_queue, unsigned long iterations) {
/*
// queue to store action values
PriorityQueue<int, double> actionQueue(MAX);
double sum = 0.0;
// calculate partition function by iterating over action-values
for (PriorityQueue<int, double>::const_iterator iter = a_queue.begin(), end = a_queue.end(); iter < end; ++iter) {
sum += std::exp((iter->second) / temperature(iterations));
}
// compute Boltzmann factors for action-values and enqueue to actionQueue
for (PriorityQueue<int, double>::const_iterator iter = a_queue.begin(); iter < a_queue.end(); ++iter) {
double priority = std::exp(iter.operator*().second / temperature(iterations)) / sum;
actionQueue.enqueueWithPriority(iter.operator*().first, priority);
}
// calculate cumulative probability distribution
for (PriorityQueue<int, double>::const_iterator it1 = actionQueue.begin()++, it2 = actionQueue.begin(), end = actionQueue.end(); it1 < end; ++it1, ++it2) {
// change priority of it1->first data item in actionQueue to
// sum of priorities of it1 and it2 items
actionQueue.changePriority(it1->first, it1->second + it2->second);
}
//generate RN between 0 and 1
double rand_num = static_cast<double>(rand()) / RAND_MAX;
// choose action based on random number relation to priorities within action queue
for (PriorityQueue<int, double>::const_iterator iter = actionQueue.begin(), end = actionQueue.end(); iter < end; ++iter) {
if (rand_num < iter->second)
return iter->first;
}
return -1; //note that this line should never be reached
double rand_num = static_cast<double>(rand()) / RAND_MAX;
return (rand_num > 0.5)?0:1;
}
*/
<commit_msg>Update Main.cpp<commit_after>/**
* @file main.cpp
*
* @brief File containing main Q-Learning algorithm and all necessary associated functions to implementing this routine.
*
* @author Machine Learning Team 2015-2016
* @date March, 2016
*/
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string>
#include <sstream>
#include <fstream>
#include "StateSpace.h"
#include "PriorityQueue.h"
#include "State.h"
#include "encoder.h"
#include "CreateModule.h"
/**
* @brief Gives a std::string representation of a primitive type.
*
* @remark Can be used to print priority queue contents.
* @param x Primitive type such as int, double, long ...
* @return std::string conversion of param x
*/
template<typename T> std::string to_string(T x) {
return static_cast<std::ostringstream&>((std::ostringstream() << std::dec << x)).str();
}
/**
* @brief Analog to temperature variable in Boltzmann Distribution, computes 'evolution variable' of system.
*
* This function computes a normal distribution over the parameterised number of loop iterations in order
* to provide a function which explores the state space dilligently initially which then decays off to the
* optimal solution after a large number of loop iterations.
*
* The normal distribution used by this function is:
*
* \f[ a e^{-\frac{bt^2}{c}} + \epsilon \f]
*
* where a, b and c are scaling coefficients (see method body) and \f$\epsilon\f$ is some small offset.
*
* @param t Number of loop iterations.
* @return Value of normal distribution at t loop iterations.
*/
double probabilityFluxDensityCoeffieicent(unsigned long t);
//function to select next action
/**
* @brief Selects an action to perform based on experience, iterations and probabilities.
*
* @param a_queue A priority queue instance storing integral types with double type priorities,
* represents the queue of possible actions with pre-initialised priority levels.
* @param iterations Number of loop iterations completed.
* @return integer corresponding to chosen action
*/
int selectAction(PriorityQueue<int, double>& a_queue, unsigned long iterations);
/**
* @brief Updates the utility (Q-value) of the system.
*
* Utility (Q-Value) of the system is updated via the Temporal Difference Learning Rule given by the following equation,
*
* \f[ Q_{i+1} (s,a) = Q_i (s,a) + \alpha [R(s') + \gamma \underset{a}{max} Q(s',a) - Q_i (s,a)] \f]
*
* where Q represents the utility of a state-action pair, \f$ \alpha \f$ is the learning rate, \f$ \gamma \f$ is the discount
* factor and \f$ max_a (Q) \f$ yields the action-maximum of the Q space. The learning rate should be set to a low value for
* highly stochastic, asymmetric systems or a high value for a lowly stochastic, symmetric system - this value lies between 0 and 1.
* The discount factor (also in the interval [0,1]) represents the time considerations of the learning algorithm, lower values indicate
* "living in the moment", whilst higher values indicate "planning for the future".
*
* @param space Reference to StateSpace object
* @param action Integer code to previous performed action
* @param new_state Reference to State instance giving the new system state
* @param old_state Reference to State instance giving the old system state
* @param alpha Learning rate of temporal difference learning algorithm (in the interval [0,1])
* @param gamma Discount factor applied to q-learning equation (in the interval [0,1])
*/
void updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma);
/**
* @brief Program launcher!
*
* Contains all initialisations including setting up the StateSpace and connecting to robot via a proxy. Holds main
* program loop to perform algorithm continuously using calls to selectAction and updateQ sequentially to update
* utilities and choose most optimal actions to perform based on position and velocity.
*
* @return Program exit code
*/
int main() {
// STUFF WE DONT UNDERSTAND, AND DONT NEED TO
//__________________________________________________________________________________________
//__________________________________________________________________________________________
// Libraries to load
std::string bodyLibName = "bodyinfo";
std::string movementLibName = "movementtools";
// Name of camera module in library
std::string bodyModuleName = "BodyInfo";
std::string movementModuleName = "MovementTools";
// Set broker name, ip and port, finding first available port from 54000
const std::string brokerName = "MotionTimingBroker";
int brokerPort = qi::os::findAvailablePort(54000);
const std::string brokerIp = "0.0.0.0";
// Default parent port and ip
int pport = 9559;
std::string pip = "127.0.0.1";
// Need this for SOAP serialisation of floats to work
setlocale(LC_NUMERIC, "C");
// Create a broker
boost::shared_ptr<AL::ALBroker> broker;
try {
broker = AL::ALBroker::createBroker(
brokerName,
brokerIp,
brokerPort,
pip,
pport,
0);
}
// Throw error and quit if a broker could not be created
catch (...) {
std::cerr << "Failed to connect broker to: "
<< pip
<< ":"
<< pport
<< std::endl;
AL::ALBrokerManager::getInstance()->killAllBroker();
AL::ALBrokerManager::kill();
return 1;
}
// Add the broker to NAOqi
AL::ALBrokerManager::setInstance(broker->fBrokerManager.lock());
AL::ALBrokerManager::getInstance()->addBroker(broker);
CreateModule(movementLibName, movementModuleName, broker, false, true);
CreateModule(bodyLibName, bodyModuleName, broker, false, true);
AL::ALProxy bodyInfoProxy(bodyModuleName, pip, pport);
AL::ALProxy movementToolsProxy(movementModuleName, pip, pport);
AL::ALMotionProxy motion(pip, pport);
//__________________________________________________________________________________________
//__________________________________________________________________________________________
//END OF STUFF WE DONT UNDERSTAND, BREATHE NOW
//learning factor
const double alpha = 0.8;
//discount factor
const double gamma = 0.5;
//seed rng
std::srand(static_cast<unsigned int>(std::time(NULL)));
int action_forwards = FORWARD;
int action_backwards = BACKWARD;
int chosen_action = action_forwards;
//create a priority queue to copy to all the state space priority queues
PriorityQueue<int, double> initiator_queue(MAX);
initiator_queue.enqueueWithPriority(action_forwards, 0);
initiator_queue.enqueueWithPriority(action_backwards, 0);
//create encoder
Encoder encoder;
encoder.Calibrate();
//pause briefly to allow the robot to be given a push if desired
qi::os::msleep(5000);
//create the state space
StateSpace space(100, 50, M_PI * 0.25, 1.0, initiator_queue);
//state objects
State current_state(0, 0, FORWARD);
State old_state(0, 0, FORWARD);
for( unsigned long i = 0; i<500 ;++i ) {
// set current state angle to angle received from encoder
// and set current state velocity to difference in new and
// old state angles over some time difference
current_state.theta = M_PI * (encoder.GetAngle()) / 180;
current_state.theta_dot = (current_state.theta - old_state.theta) / 700; //Needs actual time
current_state.robot_state = static_cast<ROBOT_STATE>(chosen_action);
// call updateQ function with state space, old and current states
// and learning rate, discount factor
updateQ(space, chosen_action, old_state, current_state, alpha, gamma);
// set old_state to current_state
old_state = current_state;
// determine chosen_action for current state
chosen_action = selectAction(space[current_state], i);
// depending upon chosen action, call robot movement tools proxy with either
// swingForwards or swingBackwards commands.
(chosen_action) ? movementToolsProxy.callVoid("swingForwards") : movementToolsProxy.callVoid("swingBackwards");
}
std::ofstream outout("output.txt");
output<<space;
output.close();
return 1;
}
double probabilityFluxDensityCoeffieicent(unsigned long t) {
return 100.0*std::exp((-8.0*t*t) / (2600.0*2600.0)) + 0.1;//0.1 is an offset
}
int selectAction(PriorityQueue<int, double>& a_queue, unsigned long iterations) {
typedef std::vector<std::pair<int, double> > VecPair ;
//turn priority queue into a vector of pairs
VecPair vec = a_queue.saveOrderedQueueAsVector();
//sum for partition function
double sum = 0.0;
// calculate partition function by iterating over action-values
for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) {
sum += std::exp((iter->second) / probabilityFluxDensityCoeffieicent(iterations));
}
// compute Boltzmann factors for action-values and enqueue to vec
for (VecPair::iterator iter = vec.begin(); iter < vec.end(); ++iter) {
iter->second = std::exp(iter->second / probabilityFluxDensityCoeffieicent(iterations)) / sum;
}
// calculate cumulative probability distribution
for (VecPair::iterator iter = vec.begin()++, end = vec.end(); iter < end; ++iter) {
//second member of pair becomes addition of its current value
//and that of the index before it
iter->second += (iter-1)->second;
}
//generate RN between 0 and 1
double rand_num = static_cast<double>(rand()) / RAND_MAX;
// choose action based on random number relation to priorities within action queue
for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) {
if (rand_num < iter->second)
return iter->first;
}
return -1; //note that this line should never be reached
}
void updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma) {
//oldQ value reference
double oldQ = space[old_state].search(action).second;
//reward given to current state
double R = new_state.getReward();
//optimal Q value for new state i.e. first element
double maxQ = space[new_state].peekFront().second;
//new Q value determined by Q learning algorithm
double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ);
// change priority of action to new Q value
space[old_state].changePriority(action, newQ);
}
/* OLD SELECT ACTION
int selectAction(const PriorityQueue<int, double>& a_queue, unsigned long iterations) {
/*
// queue to store action values
PriorityQueue<int, double> actionQueue(MAX);
double sum = 0.0;
// calculate partition function by iterating over action-values
for (PriorityQueue<int, double>::const_iterator iter = a_queue.begin(), end = a_queue.end(); iter < end; ++iter) {
sum += std::exp((iter->second) / temperature(iterations));
}
// compute Boltzmann factors for action-values and enqueue to actionQueue
for (PriorityQueue<int, double>::const_iterator iter = a_queue.begin(); iter < a_queue.end(); ++iter) {
double priority = std::exp(iter.operator*().second / temperature(iterations)) / sum;
actionQueue.enqueueWithPriority(iter.operator*().first, priority);
}
// calculate cumulative probability distribution
for (PriorityQueue<int, double>::const_iterator it1 = actionQueue.begin()++, it2 = actionQueue.begin(), end = actionQueue.end(); it1 < end; ++it1, ++it2) {
// change priority of it1->first data item in actionQueue to
// sum of priorities of it1 and it2 items
actionQueue.changePriority(it1->first, it1->second + it2->second);
}
//generate RN between 0 and 1
double rand_num = static_cast<double>(rand()) / RAND_MAX;
// choose action based on random number relation to priorities within action queue
for (PriorityQueue<int, double>::const_iterator iter = actionQueue.begin(), end = actionQueue.end(); iter < end; ++iter) {
if (rand_num < iter->second)
return iter->first;
}
return -1; //note that this line should never be reached
double rand_num = static_cast<double>(rand()) / RAND_MAX;
return (rand_num > 0.5)?0:1;
}
*/
<|endoftext|>
|
<commit_before>#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <android/log.h>
//#include <log/log.h>
#include <log/logger.h>
#include <log/logprint.h>
#include <capnp/serialize.h>
#include "common/timing.h"
#include "cereal/gen/cpp/log.capnp.h"
#include "messaging.hpp"
int main() {
int err;
struct logger_list *logger_list = android_logger_list_alloc(ANDROID_LOG_RDONLY, 0, 0);
assert(logger_list);
struct logger *main_logger = android_logger_open(logger_list, LOG_ID_MAIN);
assert(main_logger);
struct logger *radio_logger = android_logger_open(logger_list, LOG_ID_RADIO);
assert(radio_logger);
struct logger *system_logger = android_logger_open(logger_list, LOG_ID_SYSTEM);
assert(system_logger);
struct logger *crash_logger = android_logger_open(logger_list, LOG_ID_CRASH);
assert(crash_logger);
// struct logger *kernel_logger = android_logger_open(logger_list, LOG_ID_KERNEL);
// assert(kernel_logger);
Context * c = Context::create();
PubSocket * androidLog = PubSocket::create(c, "androidLog");
assert(androidLog != NULL);
while (1) {
log_msg log_msg;
err = android_logger_list_read(logger_list, &log_msg);
if (err <= 0) {
break;
}
AndroidLogEntry entry;
err = android_log_processLogBuffer(&log_msg.entry_v1, &entry);
if (err < 0) {
continue;
}
capnp::MallocMessageBuilder msg;
cereal::Event::Builder event = msg.initRoot<cereal::Event>();
event.setLogMonoTime(nanos_since_boot());
auto androidEntry = event.initAndroidLogEntry();
androidEntry.setId(log_msg.id());
androidEntry.setTs(entry.tv_sec * 1000000000ULL + entry.tv_nsec);
androidEntry.setPriority(entry.priority);
androidEntry.setPid(entry.pid);
androidEntry.setTid(entry.tid);
androidEntry.setTag(entry.tag);
androidEntry.setMessage(entry.message);
auto words = capnp::messageToFlatArray(msg);
auto bytes = words.asBytes();
androidLog->send((char*)bytes.begin(), bytes.size());
}
android_logger_list_close(logger_list);
delete c;
delete androidLog;
return 0;
}
<commit_msg>Fix kernel logging in logcatd, fixes #957<commit_after>#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <android/log.h>
//#include <log/log.h>
#include <log/logger.h>
#include <log/logprint.h>
#include <capnp/serialize.h>
#include "common/timing.h"
#include "cereal/gen/cpp/log.capnp.h"
#include "messaging.hpp"
int main() {
int err;
struct logger_list *logger_list = android_logger_list_alloc(ANDROID_LOG_RDONLY, 0, 0);
assert(logger_list);
struct logger *main_logger = android_logger_open(logger_list, LOG_ID_MAIN);
assert(main_logger);
struct logger *radio_logger = android_logger_open(logger_list, LOG_ID_RADIO);
assert(radio_logger);
struct logger *system_logger = android_logger_open(logger_list, LOG_ID_SYSTEM);
assert(system_logger);
struct logger *crash_logger = android_logger_open(logger_list, LOG_ID_CRASH);
assert(crash_logger);
struct logger *kernel_logger = android_logger_open(logger_list, (log_id_t)5); // LOG_ID_KERNEL
assert(kernel_logger);
Context * c = Context::create();
PubSocket * androidLog = PubSocket::create(c, "androidLog");
assert(androidLog != NULL);
while (1) {
log_msg log_msg;
err = android_logger_list_read(logger_list, &log_msg);
if (err <= 0) {
break;
}
AndroidLogEntry entry;
err = android_log_processLogBuffer(&log_msg.entry_v1, &entry);
if (err < 0) {
continue;
}
capnp::MallocMessageBuilder msg;
cereal::Event::Builder event = msg.initRoot<cereal::Event>();
event.setLogMonoTime(nanos_since_boot());
auto androidEntry = event.initAndroidLogEntry();
androidEntry.setId(log_msg.id());
androidEntry.setTs(entry.tv_sec * 1000000000ULL + entry.tv_nsec);
androidEntry.setPriority(entry.priority);
androidEntry.setPid(entry.pid);
androidEntry.setTid(entry.tid);
androidEntry.setTag(entry.tag);
androidEntry.setMessage(entry.message);
auto words = capnp::messageToFlatArray(msg);
auto bytes = words.asBytes();
androidLog->send((char*)bytes.begin(), bytes.size());
}
android_logger_list_close(logger_list);
delete c;
delete androidLog;
return 0;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Library
Module: TenGlyph.hh
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
// .NAME vtkTensorGlyph - scale and orient glyph according to tensor eigenvalues and eigenvectors
// .SECTION Description
// vtkTensorGlyph is a filter that copies a geometric representation (specified
// as polygonal data) to every input point. The geometric representation, or
// glyph, can be scaled and/or rotated according to the tensor at the input
// point. Scaling and rotation is controlled by the eigenvalues/eigenvectors
// of the tensor as follows. For each tensor, the eigenvalues (and associated
// eigenvectors) are sorted to determine the major, medium, and minor
// eigenvalues/eigenvectors. The major eigenvalue scales the glyph in the
// x-direction, the medium in the y-direction, and the minor in the
// z-direction. Then, the glyph is rotated so that the glyph's local x-axis
// lies along the major eigenvector, y-axis along the medium eigenvector, and
// z-axis along the minor.
// A scale factor is provided to control the amount of scaling. Also, you
// can turn off scaling completely if desired.
// Another instance variable, ExtractEigenvalues, has been provided to
// control extraction of eigenvalues/eigenvectors. If this boolean is false,
// then eigenvalues/eigenvectors are not extracted, and the columns of the
// matrix are taken as the eigenvectors (norm of column is eigenvalue).
// This allows additional capability over the vtkGlyph3D object. That is, the
// glyph can be oriented in three directions instead of one.
// .SECTION See Also
// vtkGlyph3D
#ifndef __vtkTensorGlyph_h
#define __vtkTensorGlyph_h
#include "DS2PolyF.hh"
class vtkTensorGlyph : public vtkDataSetToPolyFilter
{
public:
vtkTensorGlyph();
~vtkTensorGlyph();
char *GetClassName() {return "vtkTensorGlyph";};
void PrintSelf(ostream& os, vtkIndent indent);
void Update();
// Description:
// Specify the geometry to copy to each point.
vtkSetObjectMacro(Source,vtkPolyData);
vtkGetObjectMacro(Source,vtkPolyData);
// Description:
// Turn on/off scaling of glyph with eigenvalues.
vtkSetMacro(Scaling,int);
vtkBooleanMacro(Scaling,int);
vtkGetMacro(Scaling,int);
// Description:
// Specify scale factor to scale object by. (Scale factor always affects
// output even if scaling is off).
vtkSetMacro(ScaleFactor,float);
vtkGetMacro(ScaleFactor,float);
// Description:
// Turn on/off extraction of eigenvalues from tensor.
vtkSetMacro(ExtractEigenvalues,int);
vtkBooleanMacro(ExtractEigenvalues,int);
vtkGetMacro(ExtractEigenvalues,int);
protected:
void Execute();
vtkPolyData *Source; // Geometry to copy to each point
int Scaling; // Determine whether scaling of geometry is performed
float ScaleFactor; // Scale factor to use to scale geometry
int ExtractEigenvalues; // Boolean controls eigenfunction extraction
};
#endif
<commit_msg> ENH: Got tensors working<commit_after>/*=========================================================================
Program: Visualization Library
Module: TenGlyph.hh
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
// .NAME vtkTensorGlyph - scale and orient glyph according to tensor eigenvalues and eigenvectors
// .SECTION Description
// vtkTensorGlyph is a filter that copies a geometric representation (specified
// as polygonal data) to every input point. The geometric representation, or
// glyph, can be scaled and/or rotated according to the tensor at the input
// point. Scaling and rotation is controlled by the eigenvalues/eigenvectors
// of the tensor as follows. For each tensor, the eigenvalues (and associated
// eigenvectors) are sorted to determine the major, medium, and minor
// eigenvalues/eigenvectors. The major eigenvalue scales the glyph in the
// x-direction, the medium in the y-direction, and the minor in the
// z-direction. Then, the glyph is rotated so that the glyph's local x-axis
// lies along the major eigenvector, y-axis along the medium eigenvector, and
// z-axis along the minor.
// A scale factor is provided to control the amount of scaling. Also, you
// can turn off scaling completely if desired. The boolean variable LogScaling
// controls whether the scaling is performed logarithmically. That is, the
// log base 10 of the scale factors (i.e., absolute values of eigenvalues)
// are used. This is useful in certain applications where singularities or
// large order of magnitude differences exist in the eigenvalues.
// Another instance variable, ExtractEigenvalues, has been provided to
// control extraction of eigenvalues/eigenvectors. If this boolean is false,
// then eigenvalues/eigenvectors are not extracted, and the columns of the
// matrix are taken as the eigenvectors (norm of column is eigenvalue).
// This allows additional capability over the vtkGlyph3D object. That is, the
// glyph can be oriented in three directions instead of one.
// .SECTION See Also
// vtkGlyph3D, vtkPointLoad, vtkHyperStreamline
#ifndef __vtkTensorGlyph_h
#define __vtkTensorGlyph_h
#include "DS2PolyF.hh"
class vtkTensorGlyph : public vtkDataSetToPolyFilter
{
public:
vtkTensorGlyph();
~vtkTensorGlyph();
char *GetClassName() {return "vtkTensorGlyph";};
void PrintSelf(ostream& os, vtkIndent indent);
void Update();
// Description:
// Specify the geometry to copy to each point.
vtkSetObjectMacro(Source,vtkPolyData);
vtkGetObjectMacro(Source,vtkPolyData);
// Description:
// Turn on/off scaling of glyph with eigenvalues.
vtkSetMacro(Scaling,int);
vtkGetMacro(Scaling,int);
vtkBooleanMacro(Scaling,int);
// Description:
// Specify scale factor to scale object by. (Scale factor always affects
// output even if scaling is off).
vtkSetMacro(ScaleFactor,float);
vtkGetMacro(ScaleFactor,float);
// Description:
// Turn on/off extraction of eigenvalues from tensor.
vtkSetMacro(ExtractEigenvalues,int);
vtkBooleanMacro(ExtractEigenvalues,int);
vtkGetMacro(ExtractEigenvalues,int);
// Description:
// Turn on/off coloring of glyph with input scalar data. If false, or
// input scalar data not present, then the scalars from the source
// object are passed through the filter.
vtkSetMacro(ColorGlyphs,int);
vtkGetMacro(ColorGlyphs,int);
vtkBooleanMacro(ColorGlyphs,int);
// Description:
// Turn on/off logarithmic scaling. If scaling is on, the log base 10
// of the original scale factors are used to scale the glyphs.
vtkSetMacro(LogScaling,int);
vtkGetMacro(LogScaling,int);
vtkBooleanMacro(LogScaling,int);
protected:
void Execute();
vtkPolyData *Source; // Geometry to copy to each point
int Scaling; // Determine whether scaling of geometry is performed
float ScaleFactor; // Scale factor to use to scale geometry
int ExtractEigenvalues; // Boolean controls eigenfunction extraction
int ColorGlyphs; // Boolean controls coloring with input scalar data
int LogScaling; // Boolean controls logarithmic scaling
};
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2011, Paul Tagliamonte <tag@pault.ag>
*
* 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.
*/
#ifndef _TERMINAL_HH_
#define _TERMINAL_HH_ foo
#include <pty.h>
typedef struct _TerminalCell {
unsigned char attr;
unsigned char ch;
} TerminalCell;
class Terminal {
protected:
int width;
int height;
int scroll_frame_top;
int scroll_frame_bottom;
int cX;
int cY;
unsigned char cMode;
TerminalCell * chars;
pid_t pty;
pid_t childpid;
void erase_to_from( int iX, int iY, int tX, int tY );
void advance_curs();
void _init_Terminal( int width, int height );
public:
Terminal(int width, int height);
Terminal();
~Terminal();
virtual void insert( unsigned char c );
void type( char c );
void scroll_up();
void poke();
pid_t fork( const char * command ); /* XXX: Protect this? */
int get_width();
int get_height();
};
#endif
<commit_msg>expsing chars (for now) - will make get_chars(); later<commit_after>/*
* Copyright (C) 2011, Paul Tagliamonte <tag@pault.ag>
*
* 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.
*/
#ifndef _TERMINAL_HH_
#define _TERMINAL_HH_ foo
#include <pty.h>
typedef struct _TerminalCell {
unsigned char attr;
unsigned char ch;
} TerminalCell;
class Terminal {
protected:
int width;
int height;
int scroll_frame_top;
int scroll_frame_bottom;
int cX;
int cY;
unsigned char cMode;
pid_t pty;
pid_t childpid;
void erase_to_from( int iX, int iY, int tX, int tY );
void advance_curs();
void _init_Terminal( int width, int height );
public:
TerminalCell * chars;
Terminal(int width, int height);
Terminal();
~Terminal();
virtual void insert( unsigned char c );
void type( char c );
void scroll_up();
void poke();
pid_t fork( const char * command ); /* XXX: Protect this? */
int get_width();
int get_height();
};
#endif
<|endoftext|>
|
<commit_before>/*
* cli.hpp - Simple framework for writing line-oriented command interpreters
*
* Copyright 2010 Jesús Torres <jmtorres@ull.es>
*
* 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.
*/
#ifndef CLI_HPP_
#define CLI_HPP_
#include <iostream>
#include <string>
#include <boost/function.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/spirit/include/qi.hpp>
#include <cli/callbacks.hpp>
#include <cli/internals.hpp>
#include <cli/readline.hpp>
namespace cli
{
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
//
// Class CommandLineInterpreter
//
template <template<typename> class Parser, typename Command>
class CommandLineInterpreter
{
public:
typedef CommandLineInterpreter<Parser, Command> Type;
typedef Parser<std::string::iterator> ParserType;
typedef Command CommandType;
//
// Callback functions types
//
typedef typename callbacks::DoCommandCallback<Type>::Type
DoCommandCallback;
typedef typename callbacks::EmptyLineCallback<Type>::Type
EmptyLineCallback;
typedef typename callbacks::PreDoCommandCallback<Type>::Type
PreDoCommandCallback;
typedef typename callbacks::PostDoCommandCallback<Type>::Type
PostDoCommandCallback;
typedef typename callbacks::PreLoopCallback<Type>::Type
PreLoopCallback;
typedef typename callbacks::PostLoopCallback<Type>::Type
PostLoopCallback;
//
// Class constructors
//
CommandLineInterpreter(bool useReadline = true);
CommandLineInterpreter(std::istream& in, std::ostream& out,
bool useReadline = true);
//
// Methods to interpret command-line input
//
void loop();
bool interpretOneLine(std::string line);
//
// Class attribute getters
//
std::istream& getInStream() const
{ return in_; }
std::ostream& getOutStream() const
{ return out_; }
std::string getLastCommand() const
{ return lastCommand_; }
//
// Class attribute setters
//
void setIntroText(const std::string& intro)
{ introText_ = intro; }
void setPromptText(const std::string& prompt)
{ promptText_ = prompt; }
void setHistoryFile(const std::string& fileName);
//
// Callback functions setter
//
template <template <typename> class Callback, typename Functor>
void setCallback(Functor function);
protected:
//
// Hook methods invoked for command execution
//
virtual bool doCommand(const Command& command);
virtual bool emptyLine();
//
// Hook methods invoked inside interpretOneLine()
//
virtual void preDoCommand(std::string& line) {};
virtual bool postDoCommand(bool isFinished,
const std::string& line);
//
// Hook methods invoked once inside loop()
//
virtual void preLoop();
virtual void postLoop();
private:
std::istream& in_;
std::ostream& out_;
readline::Readline readLine_;
boost::scoped_ptr<ParserType> lineParser_;
std::string introText_;
std::string promptText_;
std::string lastCommand_;
//
// Callback functions objects
//
boost::function<DoCommandCallback> doCommandCallback_;
boost::function<EmptyLineCallback> emptyLineCallback_;
boost::function<PreDoCommandCallback> preDoCommandCallback_;
boost::function<PostDoCommandCallback> postDoCommandCallback_;
boost::function<PreLoopCallback> preLoopCallback_;
boost::function<PostLoopCallback> postLoopCallback_;
template <template <typename> class Callback>
template <typename Interpreter, typename Functor>
friend void cli::callbacks::SetCallbackImpl<Callback>::
setCallback(Interpreter&, Functor);
};
template <template <typename> class Parser, typename Command>
CommandLineInterpreter<Parser, Command>::CommandLineInterpreter(
bool useReadline)
: in_(std::cin),
out_(std::cout),
readLine_(std::cin, std::cout, useReadline),
lineParser_(new ParserType)
{}
template <template <typename> class Parser, typename Command>
CommandLineInterpreter<Parser, Command>::CommandLineInterpreter(
std::istream& in, std::ostream& out, bool useReadline)
: in_(in),
out_(out),
readLine_(in, out, useReadline),
lineParser_(new ParserType)
{}
template <template <typename> class Parser, typename Command>
void CommandLineInterpreter<Parser, Command>::loop()
{
preLoop();
if (internals::isStreamTty(out_)) {
if (! introText_.empty()) {
out_ << introText_ << std::endl;
}
}
std::string line;
while (true) {
bool isOk = readLine_.readLine(line, promptText_);
if (! isOk)
break;
bool isFinished = interpretOneLine(line);
if (isFinished)
break;
}
postLoop();
}
template <template <typename> class Parser, typename Command>
bool CommandLineInterpreter<Parser, Command>::interpretOneLine(
std::string line)
{
preDoCommand(line);
if (internals::isLineEmpty(line)) {
return emptyLine();
}
else {
lastCommand_ = line;
}
Command command;
std::string::iterator begin = line.begin();
std::string::iterator end = line.end();
typename ParserType::skipper_type skipperParser;
bool success = qi::phrase_parse(begin, end, *lineParser_,
skipperParser, command);
if (success) {
bool isFinished = doCommand(command);
return postDoCommand(isFinished, line);
}
return false;
}
template <template <typename> class Parser, typename Command>
bool CommandLineInterpreter<Parser, Command>::doCommand(
const Command& command)
{
return doCommandCallback_.empty() ?
false : doCommandCallback_(command);
}
template <template <typename> class Parser, typename Command>
bool CommandLineInterpreter<Parser, Command>::emptyLine()
{
if (! emptyLineCallback_.empty()) {
return emptyLineCallback_();
}
else if (! lastCommand_.empty()) {
return interpretOneLine(lastCommand_);
}
return false;
}
template <template <typename> class Parser, typename Command>
bool CommandLineInterpreter<Parser, Command>::postDoCommand(
bool isFinished, const std::string& line)
{
return postDoCommandCallback_.empty() ?
isFinished : postDoCommandCallback_(isFinished, line);
}
template <template <typename> class Parser, typename Command>
void CommandLineInterpreter<Parser, Command>::preLoop()
{
if (! preLoopCallback_.empty()) {
preLoopCallback_();
}
}
template <template <typename> class Parser, typename Command>
void CommandLineInterpreter<Parser, Command>::postLoop()
{
if (! postLoopCallback_.empty()) {
postLoopCallback_();
}
}
template <template <typename> class Parser, typename Command>
template <template <typename> class Callback, typename Functor>
void CommandLineInterpreter<Parser, Command>::setCallback(Functor function)
{
callbacks::SetCallbackImpl<Callback>::setCallback(*this, function);
}
template <template <typename> class Parser, typename Command>
void CommandLineInterpreter<Parser, Command>::setHistoryFile(
const std::string& fileName)
{
readLine_.clearHistory();
readLine_.setHistoryFile(fileName);
}
}
#endif /* CLI_HPP_ */
<commit_msg>allow parser object injection during interpreter construction and parser factory overload<commit_after>/*
* cli.hpp - Simple framework for writing line-oriented command interpreters
*
* Copyright 2010 Jesús Torres <jmtorres@ull.es>
*
* 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.
*/
#ifndef CLI_HPP_
#define CLI_HPP_
#include <iostream>
#include <string>
#include <boost/function.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/spirit/include/qi.hpp>
#include <cli/callbacks.hpp>
#include <cli/internals.hpp>
#include <cli/readline.hpp>
namespace cli
{
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
//
// Class CommandLineInterpreter
//
template <template<typename> class Parser, typename Command>
class CommandLineInterpreter
{
public:
typedef CommandLineInterpreter<Parser, Command> Type;
typedef Parser<std::string::iterator> ParserType;
typedef Command CommandType;
//
// Callback functions types
//
typedef typename callbacks::DoCommandCallback<Type>::Type
DoCommandCallback;
typedef typename callbacks::EmptyLineCallback<Type>::Type
EmptyLineCallback;
typedef typename callbacks::PreDoCommandCallback<Type>::Type
PreDoCommandCallback;
typedef typename callbacks::PostDoCommandCallback<Type>::Type
PostDoCommandCallback;
typedef typename callbacks::PreLoopCallback<Type>::Type
PreLoopCallback;
typedef typename callbacks::PostLoopCallback<Type>::Type
PostLoopCallback;
//
// Class constructors
//
CommandLineInterpreter(bool useReadline = true);
CommandLineInterpreter(std::istream& in, std::ostream& out,
bool useReadline = true);
CommandLineInterpreter(boost::shared_ptr<ParserType> parser,
bool useReadline = true);
CommandLineInterpreter(ParserType* parser,
bool useReadline = true);
CommandLineInterpreter(boost::shared_ptr<ParserType> parser,
std::istream& in, std::ostream& out, bool useReadline = true);
CommandLineInterpreter(ParserType* parser, std::istream& in,
std::ostream& out, bool useReadline = true);
//
// Methods to interpret command-line input
//
void loop();
bool interpretOneLine(std::string line);
//
// Class attribute getters
//
std::istream& getInStream() const
{ return in_; }
std::ostream& getOutStream() const
{ return out_; }
std::string getLastCommand() const
{ return lastCommand_; }
//
// Class attribute setters
//
void setIntroText(const std::string& intro)
{ introText_ = intro; }
void setPromptText(const std::string& prompt)
{ promptText_ = prompt; }
void setHistoryFile(const std::string& fileName);
//
// Callback functions setter
//
template <template <typename> class Callback, typename Functor>
void setCallback(Functor function);
protected:
//
// Hook methods invoked for command execution
//
virtual bool doCommand(const Command& command);
virtual bool emptyLine();
//
// Hook methods invoked inside interpretOneLine()
//
virtual void preDoCommand(std::string& line) {};
virtual bool postDoCommand(bool isFinished,
const std::string& line);
//
// Hook methods invoked once inside loop()
//
virtual void preLoop();
virtual void postLoop();
//
// Command-line parser factory
//
virtual ParserType* parserFactory();
private:
std::istream& in_;
std::ostream& out_;
readline::Readline readLine_;
boost::shared_ptr<ParserType> lineParser_;
std::string introText_;
std::string promptText_;
std::string lastCommand_;
//
// Callback functions objects
//
boost::function<DoCommandCallback> doCommandCallback_;
boost::function<EmptyLineCallback> emptyLineCallback_;
boost::function<PreDoCommandCallback> preDoCommandCallback_;
boost::function<PostDoCommandCallback> postDoCommandCallback_;
boost::function<PreLoopCallback> preLoopCallback_;
boost::function<PostLoopCallback> postLoopCallback_;
template <template <typename> class Callback>
template <typename Interpreter, typename Functor>
friend void cli::callbacks::SetCallbackImpl<Callback>::
setCallback(Interpreter&, Functor);
//
// No-op memory deallocator
//
struct noOpDelete
{
void operator()(ParserType*) {}
};
};
template <template <typename> class Parser, typename Command>
CommandLineInterpreter<Parser, Command>::CommandLineInterpreter(
bool useReadline)
: in_(std::cin),
out_(std::cout),
readLine_(std::cin, std::cout, useReadline),
lineParser_(parserFactory())
{}
template <template <typename> class Parser, typename Command>
CommandLineInterpreter<Parser, Command>::CommandLineInterpreter(
std::istream& in,
std::ostream& out,
bool useReadline)
: in_(in),
out_(out),
readLine_(in, out, useReadline),
lineParser_(parserFactory())
{}
template <template <typename> class Parser, typename Command>
CommandLineInterpreter<Parser, Command>::CommandLineInterpreter(
boost::shared_ptr<ParserType> parser,
bool useReadline)
: in_(std::cin),
out_(std::cout),
readLine_(std::cin, std::cout, useReadline),
lineParser_(parser)
{}
template <template <typename> class Parser, typename Command>
CommandLineInterpreter<Parser, Command>::CommandLineInterpreter(
ParserType* parser,
bool useReadline)
: in_(std::cin),
out_(std::cout),
readLine_(std::cin, std::cout, useReadline),
lineParser_(parser, noOpDelete())
{}
template <template <typename> class Parser, typename Command>
CommandLineInterpreter<Parser, Command>::CommandLineInterpreter(
boost::shared_ptr<ParserType> parser,
std::istream& in,
std::ostream& out,
bool useReadline)
: in_(in),
out_(out),
readLine_(in, out, useReadline),
lineParser_(parser)
{}
template <template <typename> class Parser, typename Command>
CommandLineInterpreter<Parser, Command>::CommandLineInterpreter(
ParserType* parser,
std::istream& in,
std::ostream& out,
bool useReadline)
: in_(in),
out_(out),
readLine_(in, out, useReadline),
lineParser_(parser, noOpDelete())
{}
template <template <typename> class Parser, typename Command>
typename CommandLineInterpreter<Parser, Command>::ParserType*
CommandLineInterpreter<Parser, Command>::parserFactory()
{
return new ParserType;
}
template <template <typename> class Parser, typename Command>
void CommandLineInterpreter<Parser, Command>::loop()
{
preLoop();
if (internals::isStreamTty(out_)) {
if (! introText_.empty()) {
out_ << introText_ << std::endl;
}
}
std::string line;
while (true) {
bool isOk = readLine_.readLine(line, promptText_);
if (! isOk)
break;
bool isFinished = interpretOneLine(line);
if (isFinished)
break;
}
postLoop();
}
template <template <typename> class Parser, typename Command>
bool CommandLineInterpreter<Parser, Command>::interpretOneLine(
std::string line)
{
preDoCommand(line);
if (internals::isLineEmpty(line)) {
return emptyLine();
}
else {
lastCommand_ = line;
}
Command command;
std::string::iterator begin = line.begin();
std::string::iterator end = line.end();
typename ParserType::skipper_type skipperParser;
bool success = qi::phrase_parse(begin, end, *lineParser_,
skipperParser, command);
if (success) {
bool isFinished = doCommand(command);
return postDoCommand(isFinished, line);
}
return false;
}
template <template <typename> class Parser, typename Command>
bool CommandLineInterpreter<Parser, Command>::doCommand(
const Command& command)
{
return doCommandCallback_.empty() ?
false : doCommandCallback_(command);
}
template <template <typename> class Parser, typename Command>
bool CommandLineInterpreter<Parser, Command>::emptyLine()
{
if (! emptyLineCallback_.empty()) {
return emptyLineCallback_();
}
else if (! lastCommand_.empty()) {
return interpretOneLine(lastCommand_);
}
return false;
}
template <template <typename> class Parser, typename Command>
bool CommandLineInterpreter<Parser, Command>::postDoCommand(
bool isFinished, const std::string& line)
{
return postDoCommandCallback_.empty() ?
isFinished : postDoCommandCallback_(isFinished, line);
}
template <template <typename> class Parser, typename Command>
void CommandLineInterpreter<Parser, Command>::preLoop()
{
if (! preLoopCallback_.empty()) {
preLoopCallback_();
}
}
template <template <typename> class Parser, typename Command>
void CommandLineInterpreter<Parser, Command>::postLoop()
{
if (! postLoopCallback_.empty()) {
postLoopCallback_();
}
}
template <template <typename> class Parser, typename Command>
template <template <typename> class Callback, typename Functor>
void CommandLineInterpreter<Parser, Command>::setCallback(Functor function)
{
callbacks::SetCallbackImpl<Callback>::setCallback(*this, function);
}
template <template <typename> class Parser, typename Command>
void CommandLineInterpreter<Parser, Command>::setHistoryFile(
const std::string& fileName)
{
readLine_.clearHistory();
readLine_.setHistoryFile(fileName);
}
}
#endif /* CLI_HPP_ */
<|endoftext|>
|
<commit_before>// Natron
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
*Created by Alexandre GAUTHIER-FOICHAT on 6/1/2012.
*contact: immarespond at gmail dot com
*
*/
#include "ProcessHandler.h"
#include <QDateTime>
#include <QProcess>
#include <QLocalServer>
#include <QLocalSocket>
#include <QCoreApplication>
#include <QTemporaryFile>
#include <QWaitCondition>
#include <QMutex>
#include <QDir>
#include "Engine/AppInstance.h"
#include "Engine/AppManager.h"
#include "Engine/KnobFile.h"
#include "Engine/EffectInstance.h"
ProcessHandler::ProcessHandler(AppInstance* app,
const QString& projectPath,
Natron::OutputEffectInstance* writer)
: _app(app)
,_process(new QProcess)
,_writer(writer)
,_ipcServer(0)
,_bgProcessOutputSocket(0)
,_bgProcessInputSocket(0)
,_earlyCancel(false)
{
///setup the server used to listen the output of the background process
QDateTime now = QDateTime::currentDateTime();
_ipcServer = new QLocalServer();
QObject::connect(_ipcServer,SIGNAL(newConnection()),this,SLOT(onNewConnectionPending()));
QString serverName(NATRON_APPLICATION_NAME "_OUTPUT_PIPE_" + now.toString());
_ipcServer->listen(serverName);
QStringList processArgs;
processArgs << projectPath << "-b" << "-w" << writer->getName().c_str();
processArgs << "--IPCpipe" << (_ipcServer->fullServerName());
///connect the useful slots of the process
QObject::connect(_process,SIGNAL(readyReadStandardOutput()),this,SLOT(onStandardOutputBytesWritten()));
QObject::connect(_process,SIGNAL(readyReadStandardError()),this,SLOT(onStandardErrorBytesWritten()));
QObject::connect(_process,SIGNAL(error(QProcess::ProcessError)),this,SLOT(onProcessError(QProcess::ProcessError)));
QObject::connect(_process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(onProcessEnd(int,QProcess::ExitStatus)));
///validate the frame range to render
int firstFrame,lastFrame;
writer->getFrameRange(&firstFrame, &lastFrame);
if(firstFrame > lastFrame)
throw std::invalid_argument("First frame in the sequence is greater than the last frame");
///start the process
_process->start(QCoreApplication::applicationFilePath(),processArgs);
///get the output file knob to get the same of the sequence
std::string outputFileSequence;
const std::vector< boost::shared_ptr<Knob> >& knobs = writer->getKnobs();
for (U32 i = 0; i < knobs.size(); ++i) {
if (knobs[i]->typeName() == OutputFile_Knob::typeNameStatic()) {
boost::shared_ptr<OutputFile_Knob> fk = boost::dynamic_pointer_cast<OutputFile_Knob>(knobs[i]);
if(fk->isOutputImageFile()){
outputFileSequence = fk->getValue().toString().toStdString();
}
}
}
app->notifyRenderProcessHandlerStarted(outputFileSequence.c_str(),firstFrame,lastFrame,this);
}
ProcessHandler::~ProcessHandler(){
_process->close();
delete _process;
delete _ipcServer;
delete _bgProcessInputSocket;
}
void ProcessHandler::onNewConnectionPending() {
///accept only 1 connection!
if (_bgProcessOutputSocket) {
return;
}
_bgProcessOutputSocket = _ipcServer->nextPendingConnection();
QObject::connect(_bgProcessOutputSocket, SIGNAL(readyRead()), this, SLOT(onDataWrittenToSocket()));
}
void ProcessHandler::onDataWrittenToSocket() {
QString str = _bgProcessOutputSocket->readLine();
while(str.endsWith('\n')) {
str.chop(1);
}
qDebug() << "ProcessHandler::onDataWrittenToSocket() received " << str;
if (str.startsWith(kFrameRenderedStringShort)) {
str = str.remove(kFrameRenderedStringShort);
emit frameRendered(str.toInt());
} else if (str.startsWith(kRenderingFinishedStringShort)) {
if(_process->state() == QProcess::Running) {
_process->waitForFinished();
}
} else if (str.startsWith(kProgressChangedStringShort)) {
str = str.remove(kProgressChangedStringShort);
emit frameProgress(str.toInt());
} else if (str.startsWith(kBgProcessServerCreatedShort)) {
str = str.remove(kBgProcessServerCreatedShort);
///the bg process wants us to create the pipe for its input
if (!_bgProcessInputSocket) {
_bgProcessInputSocket = new QLocalSocket();
QObject::connect(_bgProcessInputSocket, SIGNAL(connected()), this, SLOT(onInputPipeConnectionMade()));
_bgProcessInputSocket->connectToServer(str,QLocalSocket::ReadWrite);
}
} else if(str.startsWith(kRenderingStartedShort)) {
///if the user pressed cancel prior to the pipe being created, wait for it to be created and send the abort
///message right away
if (_earlyCancel) {
_bgProcessInputSocket->waitForConnected(5000);
_earlyCancel = false;
onProcessCanceled();
}
} else {
qDebug() << "Error: Unable to interpret message: " << str;
throw std::runtime_error("ProcessHandler::onDataWrittenToSocket() received erroneous message");
}
}
void ProcessHandler::onInputPipeConnectionMade() {
qDebug() << "The input channel was successfully created and connected.";
}
void ProcessHandler::onStandardOutputBytesWritten(){
QString str(_process->readAllStandardOutput().data());
qDebug() << str ;
}
void ProcessHandler::onStandardErrorBytesWritten() {
QString str(_process->readAllStandardError().data());
qDebug() << str ;
}
void ProcessHandler::onProcessCanceled(){
emit processCanceled();
if(!_bgProcessInputSocket) {
_earlyCancel = true;
} else {
_bgProcessInputSocket->write((QString(kAbortRenderingStringShort) + '\n').toUtf8());
_bgProcessInputSocket->flush();
if(_process->state() == QProcess::Running) {
_process->waitForFinished();
}
}
}
void ProcessHandler::onProcessError(QProcess::ProcessError err){
if(err == QProcess::FailedToStart){
Natron::errorDialog(_writer->getName(),"The render process failed to start");
}else if(err == QProcess::Crashed){
//@TODO: find out a way to get the backtrace
}
}
void ProcessHandler::onProcessEnd(int exitCode,QProcess::ExitStatus stat){
if(stat == QProcess::CrashExit){
Natron::errorDialog(_writer->getName(),"The render process exited after a crash");
// _hasProcessBeenDeleted = true;
}else if(exitCode == 1){
Natron::errorDialog(_writer->getName(), "The process ended with a return code of 1, this indicates an undetermined problem occured.");
}else{
Natron::informationDialog(_writer->getName(),"Render finished!");
}
emit processCanceled();
delete this;
}
ProcessInputChannel::ProcessInputChannel(const QString& mainProcessServerName)
: QThread()
, _mainProcessServerName(mainProcessServerName)
, _backgroundOutputPipe(0)
, _backgroundIPCServer(0)
, _backgroundInputPipe(0)
, _mustQuit(false)
, _mustQuitCond(new QWaitCondition)
, _mustQuitMutex(new QMutex)
{
initialize();
_backgroundIPCServer->moveToThread(this);
start();
}
ProcessInputChannel::~ProcessInputChannel() {
if (isRunning()) {
_mustQuit = true;
while (_mustQuit) {
_mustQuitCond->wait(_mustQuitMutex);
}
}
delete _backgroundIPCServer;
delete _backgroundOutputPipe;
delete _mustQuitCond;
delete _mustQuitMutex;
}
void ProcessInputChannel::writeToOutputChannel(const QString& message){
_backgroundOutputPipe->write((message+'\n').toUtf8());
_backgroundOutputPipe->flush();
}
void ProcessInputChannel::onNewConnectionPending() {
if (_backgroundInputPipe) {
///listen to only 1 process!
return;
}
_backgroundInputPipe = _backgroundIPCServer->nextPendingConnection();
QObject::connect(_backgroundInputPipe, SIGNAL(readyRead()), this, SLOT(onInputChannelMessageReceived()));
}
bool ProcessInputChannel::onInputChannelMessageReceived() {
QString str(_backgroundInputPipe->readLine());
while(str.endsWith('\n')) {
str.chop(1);
}
if (str.startsWith(kAbortRenderingStringShort)) {
qDebug() << "Aborting render!";
appPTR->abortAnyProcessing();
return true;
} else {
qDebug() << "Error: Unable to interpret message: " << str;
throw std::runtime_error("ProcessInputChannel::onInputChannelMessageReceived() received erroneous message");
}
return false;
}
void ProcessInputChannel::run() {
for(;;) {
if (_backgroundInputPipe->waitForReadyRead(100)) {
if(onInputChannelMessageReceived()) {
qDebug() << "Background process now closing the input channel...";
return;
}
}
QMutexLocker l(_mustQuitMutex);
if (_mustQuit) {
_mustQuit = false;
_mustQuitCond->wakeOne();
return;
}
}
}
void ProcessInputChannel::initialize() {
_backgroundOutputPipe = new QLocalSocket();
QObject::connect(_backgroundOutputPipe, SIGNAL(connected()), this, SLOT(onOutputPipeConnectionMade()));
_backgroundOutputPipe->connectToServer(_mainProcessServerName,QLocalSocket::ReadWrite);
QDateTime now = QDateTime::currentDateTime();
_backgroundIPCServer = new QLocalServer();
QObject::connect(_backgroundIPCServer,SIGNAL(newConnection()),this,SLOT(onNewConnectionPending()));
QString serverName;
{
QTemporaryFile tmpf(QDir::tempPath() + QDir::separator() + NATRON_APPLICATION_NAME "_INPUT_SOCKET");
tmpf.open();
serverName = tmpf.fileName();
}
_backgroundIPCServer->listen(serverName);
if(!_backgroundOutputPipe->waitForConnected(5000)){ //< blocking, we wait for the server to respond
std::cout << "WARNING: The GUI application failed to respond, canceling this process will not be possible"
" unless it finishes or you kill it." << std::endl;
}
writeToOutputChannel(QString(kBgProcessServerCreatedShort) + _backgroundIPCServer->fullServerName());
///we wait for the GUI app to connect its socket to this server, we let it 5 sec to reply
_backgroundIPCServer->waitForNewConnection(5000);
///since we're still not returning the event loop, just process them manually in case
///Qt didn't caught the new connection pending.
QCoreApplication::processEvents();
}
void ProcessInputChannel::onOutputPipeConnectionMade() {
qDebug() << "The output channel was successfully created and connected.";
}
<commit_msg>ProcessHandler: use PID instead of localized date<commit_after>// Natron
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
*Created by Alexandre GAUTHIER-FOICHAT on 6/1/2012.
*contact: immarespond at gmail dot com
*
*/
#include "ProcessHandler.h"
#include <QProcess>
#include <QLocalServer>
#include <QLocalSocket>
#include <QCoreApplication>
#include <QTemporaryFile>
#include <QWaitCondition>
#include <QMutex>
#include <QDir>
#include <QDebug>
#include "Engine/AppInstance.h"
#include "Engine/AppManager.h"
#include "Engine/KnobFile.h"
#include "Engine/EffectInstance.h"
ProcessHandler::ProcessHandler(AppInstance* app,
const QString& projectPath,
Natron::OutputEffectInstance* writer)
: _app(app)
,_process(new QProcess)
,_writer(writer)
,_ipcServer(0)
,_bgProcessOutputSocket(0)
,_bgProcessInputSocket(0)
,_earlyCancel(false)
{
///setup the server used to listen the output of the background process
_ipcServer = new QLocalServer();
QObject::connect(_ipcServer,SIGNAL(newConnection()),this,SLOT(onNewConnectionPending()));
QString serverName(NATRON_APPLICATION_NAME "_OUTPUT_PIPE_" + QString::number(qApp->applicationPid()));
_ipcServer->listen(serverName);
QStringList processArgs;
processArgs << projectPath << "-b" << "-w" << writer->getName().c_str();
processArgs << "--IPCpipe" << (_ipcServer->fullServerName());
///connect the useful slots of the process
QObject::connect(_process,SIGNAL(readyReadStandardOutput()),this,SLOT(onStandardOutputBytesWritten()));
QObject::connect(_process,SIGNAL(readyReadStandardError()),this,SLOT(onStandardErrorBytesWritten()));
QObject::connect(_process,SIGNAL(error(QProcess::ProcessError)),this,SLOT(onProcessError(QProcess::ProcessError)));
QObject::connect(_process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(onProcessEnd(int,QProcess::ExitStatus)));
///validate the frame range to render
int firstFrame,lastFrame;
writer->getFrameRange(&firstFrame, &lastFrame);
if(firstFrame > lastFrame)
throw std::invalid_argument("First frame in the sequence is greater than the last frame");
///start the process
qDebug() << "Starting background rendering: " << QCoreApplication::applicationFilePath() << processArgs;
_process->start(QCoreApplication::applicationFilePath(),processArgs);
///get the output file knob to get the same of the sequence
std::string outputFileSequence;
const std::vector< boost::shared_ptr<Knob> >& knobs = writer->getKnobs();
for (U32 i = 0; i < knobs.size(); ++i) {
if (knobs[i]->typeName() == OutputFile_Knob::typeNameStatic()) {
boost::shared_ptr<OutputFile_Knob> fk = boost::dynamic_pointer_cast<OutputFile_Knob>(knobs[i]);
if(fk->isOutputImageFile()){
outputFileSequence = fk->getValue().toString().toStdString();
}
}
}
app->notifyRenderProcessHandlerStarted(outputFileSequence.c_str(),firstFrame,lastFrame,this);
}
ProcessHandler::~ProcessHandler(){
_process->close();
delete _process;
delete _ipcServer;
delete _bgProcessInputSocket;
}
void ProcessHandler::onNewConnectionPending() {
///accept only 1 connection!
if (_bgProcessOutputSocket) {
return;
}
_bgProcessOutputSocket = _ipcServer->nextPendingConnection();
QObject::connect(_bgProcessOutputSocket, SIGNAL(readyRead()), this, SLOT(onDataWrittenToSocket()));
}
void ProcessHandler::onDataWrittenToSocket() {
QString str = _bgProcessOutputSocket->readLine();
while(str.endsWith('\n')) {
str.chop(1);
}
qDebug() << "ProcessHandler::onDataWrittenToSocket() received " << str;
if (str.startsWith(kFrameRenderedStringShort)) {
str = str.remove(kFrameRenderedStringShort);
emit frameRendered(str.toInt());
} else if (str.startsWith(kRenderingFinishedStringShort)) {
if(_process->state() == QProcess::Running) {
_process->waitForFinished();
}
} else if (str.startsWith(kProgressChangedStringShort)) {
str = str.remove(kProgressChangedStringShort);
emit frameProgress(str.toInt());
} else if (str.startsWith(kBgProcessServerCreatedShort)) {
str = str.remove(kBgProcessServerCreatedShort);
///the bg process wants us to create the pipe for its input
if (!_bgProcessInputSocket) {
_bgProcessInputSocket = new QLocalSocket();
QObject::connect(_bgProcessInputSocket, SIGNAL(connected()), this, SLOT(onInputPipeConnectionMade()));
_bgProcessInputSocket->connectToServer(str,QLocalSocket::ReadWrite);
}
} else if(str.startsWith(kRenderingStartedShort)) {
///if the user pressed cancel prior to the pipe being created, wait for it to be created and send the abort
///message right away
if (_earlyCancel) {
_bgProcessInputSocket->waitForConnected(5000);
_earlyCancel = false;
onProcessCanceled();
}
} else {
qDebug() << "Error: Unable to interpret message: " << str;
throw std::runtime_error("ProcessHandler::onDataWrittenToSocket() received erroneous message");
}
}
void ProcessHandler::onInputPipeConnectionMade() {
qDebug() << "The input channel was successfully created and connected.";
}
void ProcessHandler::onStandardOutputBytesWritten(){
QString str(_process->readAllStandardOutput().data());
qDebug() << str ;
}
void ProcessHandler::onStandardErrorBytesWritten() {
QString str(_process->readAllStandardError().data());
qDebug() << str ;
}
void ProcessHandler::onProcessCanceled(){
emit processCanceled();
if(!_bgProcessInputSocket) {
_earlyCancel = true;
} else {
_bgProcessInputSocket->write((QString(kAbortRenderingStringShort) + '\n').toUtf8());
_bgProcessInputSocket->flush();
if(_process->state() == QProcess::Running) {
_process->waitForFinished();
}
}
}
void ProcessHandler::onProcessError(QProcess::ProcessError err){
if(err == QProcess::FailedToStart){
Natron::errorDialog(_writer->getName(),"The render process failed to start");
}else if(err == QProcess::Crashed){
//@TODO: find out a way to get the backtrace
}
}
void ProcessHandler::onProcessEnd(int exitCode,QProcess::ExitStatus stat){
if(stat == QProcess::CrashExit){
Natron::errorDialog(_writer->getName(),"The render process exited after a crash");
// _hasProcessBeenDeleted = true;
}else if(exitCode == 1){
Natron::errorDialog(_writer->getName(), "The process ended with a return code of 1, this indicates an undetermined problem occured.");
}else{
Natron::informationDialog(_writer->getName(),"Render finished!");
}
emit processCanceled();
delete this;
}
ProcessInputChannel::ProcessInputChannel(const QString& mainProcessServerName)
: QThread()
, _mainProcessServerName(mainProcessServerName)
, _backgroundOutputPipe(0)
, _backgroundIPCServer(0)
, _backgroundInputPipe(0)
, _mustQuit(false)
, _mustQuitCond(new QWaitCondition)
, _mustQuitMutex(new QMutex)
{
initialize();
_backgroundIPCServer->moveToThread(this);
start();
}
ProcessInputChannel::~ProcessInputChannel() {
if (isRunning()) {
_mustQuit = true;
while (_mustQuit) {
_mustQuitCond->wait(_mustQuitMutex);
}
}
delete _backgroundIPCServer;
delete _backgroundOutputPipe;
delete _mustQuitCond;
delete _mustQuitMutex;
}
void ProcessInputChannel::writeToOutputChannel(const QString& message){
_backgroundOutputPipe->write((message+'\n').toUtf8());
_backgroundOutputPipe->flush();
}
void ProcessInputChannel::onNewConnectionPending() {
if (_backgroundInputPipe) {
///listen to only 1 process!
return;
}
_backgroundInputPipe = _backgroundIPCServer->nextPendingConnection();
QObject::connect(_backgroundInputPipe, SIGNAL(readyRead()), this, SLOT(onInputChannelMessageReceived()));
}
bool ProcessInputChannel::onInputChannelMessageReceived() {
QString str(_backgroundInputPipe->readLine());
while(str.endsWith('\n')) {
str.chop(1);
}
if (str.startsWith(kAbortRenderingStringShort)) {
qDebug() << "Aborting render!";
appPTR->abortAnyProcessing();
return true;
} else {
qDebug() << "Error: Unable to interpret message: " << str;
throw std::runtime_error("ProcessInputChannel::onInputChannelMessageReceived() received erroneous message");
}
return false;
}
void ProcessInputChannel::run() {
for(;;) {
if (_backgroundInputPipe->waitForReadyRead(100)) {
if(onInputChannelMessageReceived()) {
qDebug() << "Background process now closing the input channel...";
return;
}
}
QMutexLocker l(_mustQuitMutex);
if (_mustQuit) {
_mustQuit = false;
_mustQuitCond->wakeOne();
return;
}
}
}
void ProcessInputChannel::initialize() {
_backgroundOutputPipe = new QLocalSocket();
QObject::connect(_backgroundOutputPipe, SIGNAL(connected()), this, SLOT(onOutputPipeConnectionMade()));
_backgroundOutputPipe->connectToServer(_mainProcessServerName,QLocalSocket::ReadWrite);
_backgroundIPCServer = new QLocalServer();
QObject::connect(_backgroundIPCServer,SIGNAL(newConnection()),this,SLOT(onNewConnectionPending()));
QString serverName;
{
QTemporaryFile tmpf(QDir::tempPath() + QDir::separator() + NATRON_APPLICATION_NAME "_INPUT_SOCKET");
tmpf.open();
serverName = tmpf.fileName();
}
_backgroundIPCServer->listen(serverName);
if(!_backgroundOutputPipe->waitForConnected(5000)){ //< blocking, we wait for the server to respond
std::cout << "WARNING: The GUI application failed to respond, canceling this process will not be possible"
" unless it finishes or you kill it." << std::endl;
}
writeToOutputChannel(QString(kBgProcessServerCreatedShort) + _backgroundIPCServer->fullServerName());
///we wait for the GUI app to connect its socket to this server, we let it 5 sec to reply
_backgroundIPCServer->waitForNewConnection(5000);
///since we're still not returning the event loop, just process them manually in case
///Qt didn't caught the new connection pending.
QCoreApplication::processEvents();
}
void ProcessInputChannel::onOutputPipeConnectionMade() {
qDebug() << "The output channel was successfully created and connected.";
}
<|endoftext|>
|
<commit_before>#include <vector>
#include <boost/lambda/lambda.hpp>
#include "Linq.h"
namespace CppLinq
{
using namespace std;
using boost::lambda::_1;
struct Person
{
Person(const string& name, int age) :
m_name(name), m_age(age)
{
}
string m_name;
int m_age;
};
class LinqTest
{
public:
LinqTest()
{
m_guests.reset(new vector<Person>());
m_guests->push_back(Person("John", 32));
m_guests->push_back(Person("Mike", 28));
m_guests->push_back(Person("Eliz", 27));
}
void PerformTest()
{
assert(from(m_guests).count() == 3);
assert(from(m_guests).where(&_1 ->* &Person::m_age > 30).count() == 1);
assert(from(m_guests).select<int>(&_1 ->* &Person::m_age).count() == 3);
shared_ptr<vector<int>> results = from(m_guests).select<int>(&_1 ->* &Person::m_age).get();
assert(results->size() == 3);
assert((*results)[0] == 32);
assert(from(m_guests).group<int>(&_1 ->* &Person::m_age).count() == 3);
vector<Person> people;
people.push_back(Person("Joe", 20));
assert(from(&people).group<int>(&_1 ->* &Person::m_age).count() == 1);
m_guests->push_back(Person("Joe", 18));
DataSet<vector<Person>> results2 = insert(from(m_guests).where(&_1 ->* &Person::m_age > 30)).into(from(m_guests).where(&_1 ->* &Person::m_name == "Joe"));
assert(results2.count() == 2);
shared_ptr<vector<int>> ages = results2.select<int>(&_1 ->* &Person::m_age).get();
assert(count(ages->begin(), ages->end(), 32) == 1);
assert(count(ages->begin(), ages->end(), 18) == 1);
}
private:
shared_ptr<vector<Person>> m_guests;
};
}
int main()
{
CppLinq::LinqTest test;
test.PerformTest();
}<commit_msg>Add orderby test<commit_after>#include <vector>
#include <boost/lambda/lambda.hpp>
#include "Linq.h"
#include <iostream>
namespace CppLinq
{
using namespace std;
using boost::lambda::_1;
struct Person
{
Person(const string& name, int age) :
m_name(name), m_age(age)
{
}
string m_name;
int m_age;
};
class LinqTest
{
public:
LinqTest()
{
m_guests.reset(new vector<Person>());
m_guests->push_back(Person("John", 32));
m_guests->push_back(Person("Mike", 28));
m_guests->push_back(Person("Eliz", 27));
}
void PerformTest()
{
assert(from(m_guests).count() == 3);
assert(from(m_guests).orderby<int>(&_1 ->* &Person::m_age, Descending).count() == 3);
for (int i = 0; i < m_guests->size(); ++i)
{
cout << m_guests->at(i).m_name << ' ' << m_guests->at(i).m_age << endl;
}
assert(from(m_guests).where(&_1 ->* &Person::m_age > 30).count() == 1);
assert(from(m_guests).select<int>(&_1 ->* &Person::m_age).count() == 3);
shared_ptr<vector<int>> results = from(m_guests).select<int>(&_1 ->* &Person::m_age).get();
assert(results->size() == 3);
assert((*results)[0] == 32);
assert(from(m_guests).group<int>(&_1 ->* &Person::m_age).count() == 3);
vector<Person> people;
people.push_back(Person("Joe", 20));
assert(from(&people).group<int>(&_1 ->* &Person::m_age).count() == 1);
m_guests->push_back(Person("Joe", 18));
DataSet<vector<Person>> results2 = insert(from(m_guests).where(&_1 ->* &Person::m_age > 30)).into(from(m_guests).where(&_1 ->* &Person::m_name == "Joe"));
assert(results2.count() == 2);
shared_ptr<vector<int>> ages = results2.select<int>(&_1 ->* &Person::m_age).get();
assert(count(ages->begin(), ages->end(), 32) == 1);
assert(count(ages->begin(), ages->end(), 18) == 1);
}
private:
shared_ptr<vector<Person>> m_guests;
};
}
int main()
{
CppLinq::LinqTest test;
test.PerformTest();
}<|endoftext|>
|
<commit_before>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html
#ifndef __RAPICORN_THREAD_HH__
#define __RAPICORN_THREAD_HH__
#include <rcore/utilities.hh>
#include <rcore/threadlib.hh>
#include <thread>
namespace Rapicorn {
struct RECURSIVE_LOCK {} constexpr RECURSIVE_LOCK {}; ///< Flag for recursive Mutex initialization.
/**
* The Mutex synchronization primitive is a thin wrapper around std::mutex.
* This class supports static construction.
*/
class Mutex {
pthread_mutex_t m_mutex;
public:
constexpr Mutex () : m_mutex (PTHREAD_MUTEX_INITIALIZER) {}
constexpr Mutex (struct RECURSIVE_LOCK) : m_mutex (PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP) {}
void lock () { pthread_mutex_lock (&m_mutex); }
void unlock () { pthread_mutex_unlock (&m_mutex); }
bool try_lock () { return 0 == pthread_mutex_trylock (&m_mutex); }
typedef pthread_mutex_t* native_handle_type;
native_handle_type native_handle() { return &m_mutex; }
/*ctor*/ Mutex (const Mutex&) = delete;
Mutex& operator= (const Mutex&) = delete;
};
/**
* The Spinlock uses low-latency busy spinning to acquire locks.
* It is a thin wrapper around pthread_spin_lock().
* This class supports static construction.
*/
class Spinlock {
pthread_spinlock_t m_spinlock;
public:
constexpr Spinlock () : m_spinlock (RAPICORN_SPINLOCK_INITIALIZER) {}
void lock () { pthread_spin_lock (&m_spinlock); }
void unlock () { pthread_spin_unlock (&m_spinlock); }
bool try_lock () { return 0 == pthread_spin_trylock (&m_spinlock); }
typedef pthread_spinlock_t* native_handle_type;
native_handle_type native_handle() { return &m_spinlock; }
/*ctor*/ Spinlock (const Spinlock&) = delete;
Mutex& operator= (const Spinlock&) = delete;
};
/// Class keeping information per Thread.
struct ThreadInfo {
/// @name Hazard Pointers
typedef std::vector<void*> VoidPointers;
void *volatile hp[8]; ///< Hazard pointers variables, see: http://www.research.ibm.com/people/m/michael/ieeetpds-2004.pdf .
static VoidPointers collect_hazards (); ///< Collect hazard pointers from all threads. Returns sorted vector of unique elements.
static inline bool lookup_pointer (const std::vector<void*> &ptrs, void *arg); ///< Lookup pointers in a hazard pointer vector.
/// @name Thread identification
String ident (); ///< Simple identifier for this thread, usually TID/PID.
String name (); ///< Get thread name.
void name (const String &newname); ///< Change thread name.
static inline ThreadInfo& self (); ///< Get ThreadInfo for the current thread, inlined, using fast thread local storage.
/** @name Accessing custom data members
* For further details, see DataListContainer.
*/
template<typename T> inline T get_data (DataKey<T> *key) { tdl(); T d = m_data_list.get (key); tdu(); return d; }
template<typename T> inline void set_data (DataKey<T> *key, T data) { tdl(); m_data_list.set (key, data); tdu(); }
template<typename T> inline void delete_data (DataKey<T> *key) { tdl(); m_data_list.del (key); tdu(); }
template<typename T> inline T swap_data (DataKey<T> *key) { tdl(); T d = m_data_list.swap (key); tdu(); return d; }
template<typename T> inline T swap_data (DataKey<T> *key, T data) { tdl(); T d = m_data_list.swap (key, data); tdu(); return d; }
private:
ThreadInfo *volatile next;
pthread_t pth_thread_id;
char pad[RAPICORN_CACHE_LINE_ALIGNMENT - sizeof hp - sizeof next - sizeof pth_thread_id];
String m_name;
Mutex m_data_mutex;
DataList m_data_list;
static ThreadInfo __thread *self_cached;
/*ctor*/ ThreadInfo ();
/*ctor*/ ThreadInfo (const ThreadInfo&) = delete;
/*dtor*/ ~ThreadInfo ();
ThreadInfo& operator= (const ThreadInfo&) = delete;
static void destroy_specific(void *vdata);
void reset_specific ();
void setup_specific ();
static ThreadInfo* create ();
void tdl () { m_data_mutex.lock(); }
void tdu () { m_data_mutex.unlock(); }
};
struct AUTOMATIC_LOCK {} constexpr AUTOMATIC_LOCK {}; ///< Flag for automatic locking of a ScopedLock<Mutex>.
struct BALANCED_LOCK {} constexpr BALANCED_LOCK {}; ///< Flag for balancing unlock/lock in a ScopedLock<Mutex>.
/**
* The ScopedLock is a scope based lock ownership wrapper.
* Placing a ScopedLock object on the stack conveniently ensures that its mutex
* will be automatically locked and properly unlocked when the scope is left,
* the current function returns or throws an exception. Mutex obbjects to be used
* by a ScopedLock need to provide the public methods lock() and unlock().
* In AUTOMATIC_LOCK mode, the owned mutex is automatically locked upon construction
* and unlocked upon destruction. Intermediate calls to unlock() and lock() on the
* ScopedLock will be accounted for in the destructor.
* In BALANCED_LOCK mode, the lock is not automatically acquired upon construction,
* however the destructor will balance all intermediate unlock() and lock() calls.
* So this mode can be used to manage ownership for an already locked mutex.
*/
template<class MUTEX>
class ScopedLock : protected NonCopyable {
MUTEX &m_mutex;
volatile int m_count;
public:
inline ~ScopedLock () { while (m_count < 0) lock(); while (m_count > 0) unlock(); }
inline void lock () { m_mutex.lock(); m_count++; }
inline void unlock () { m_count--; m_mutex.unlock(); }
inline ScopedLock (MUTEX &mutex, struct AUTOMATIC_LOCK = AUTOMATIC_LOCK) : m_mutex (mutex), m_count (0) { lock(); }
inline ScopedLock (MUTEX &mutex, struct BALANCED_LOCK) : m_mutex (mutex), m_count (0) {}
};
/**
* The Cond synchronization primitive is a thin wrapper around pthread_cond_wait().
* This class supports static construction.
*/
class Cond {
pthread_cond_t m_cond;
static struct timespec abstime (int64);
/*ctor*/ Cond (const Cond&) = delete;
Cond& operator= (const Cond&) = delete;
public:
constexpr Cond () : m_cond (PTHREAD_COND_INITIALIZER) {}
/*dtor*/ ~Cond () { pthread_cond_destroy (&m_cond); }
void signal () { pthread_cond_signal (&m_cond); }
void broadcast () { pthread_cond_broadcast (&m_cond); }
void wait (Mutex &m) { pthread_cond_wait (&m_cond, m.native_handle()); }
void wait_timed (Mutex &m, int64 max_usecs)
{ struct timespec abs = abstime (max_usecs); pthread_cond_timedwait (&m_cond, m.native_handle(), &abs); }
typedef pthread_cond_t* native_handle_type;
native_handle_type native_handle() { return &m_cond; }
};
/// @namespace Rapicorn::ThisThread The Rapicorn::ThisThread namespace provides functions for the current thread of execution.
namespace ThisThread {
String name (); ///< Get thread name.
int online_cpus (); ///< Get the number of available CPUs.
int affinity (); ///< Get the current CPU affinity.
void affinity (int cpu); ///< Set the current CPU affinity.
int thread_pid (); ///< Get the current threads's thread ID (TID). For further details, see gettid().
int process_pid (); ///< Get the process ID (PID). For further details, see getpid().
#ifdef DOXYGEN // parts reused from std::this_thread
/// Relinquish the processor to allow execution of other threads. For further details, see std::this_thread::yield().
void yield ();
/// Returns the pthread_t id for the current thread. For further details, see std::this_thread::get_id().
std::thread::id get_id ();
/// Sleep for @a sleep_duration has been reached. For further details, see std::this_thread::sleep_for().
template<class Rep, class Period> void sleep_for (std::chrono::duration<Rep,Period> sleep_duration);
/// Sleep until @a sleep_time has been reached. For further details, see std::this_thread::sleep_until().
template<class Clock, class Duration> void sleep_until (const std::chrono::time_point<Clock,Duration> &sleep_time);
#else // !DOXYGEN
using namespace std::this_thread;
#endif // !DOXYGEN
} // ThisThread
#ifdef RAPICORN_CONVENIENCE
/** The @e do_once statement preceeds code blocks to ensure that a critical section is executed atomically and at most once.
* Example: @SNIPPET{rcore/tests/threads.cc, do_once-EXAMPLE}
*/
#define do_once RAPICORN_DO_ONCE
#endif // RAPICORN_CONVENIENCE
/// Atomic types are race free integer and pointer types, similar to std::atomic.
/// All atomic types support load(), store(), cas() and additional type specific accessors.
template<typename T> class Atomic;
/// Atomic char type.
template<> struct Atomic<char> : Lib::Atomic<char> {
Atomic<char> (char i = 0) : Lib::Atomic<char> (i) {}
using Lib::Atomic<char>::operator=;
};
/// Atomic int8 type.
template<> struct Atomic<int8> : Lib::Atomic<int8> {
Atomic<int8> (int8 i = 0) : Lib::Atomic<int8> (i) {}
using Lib::Atomic<int8>::operator=;
};
/// Atomic uint8 type.
template<> struct Atomic<uint8> : Lib::Atomic<uint8> {
Atomic<uint8> (uint8 i = 0) : Lib::Atomic<uint8> (i) {}
using Lib::Atomic<uint8>::operator=;
};
/// Atomic int32 type.
template<> struct Atomic<int32> : Lib::Atomic<int32> {
Atomic<int32> (int32 i = 0) : Lib::Atomic<int32> (i) {}
using Lib::Atomic<int32>::operator=;
};
/// Atomic uint32 type.
template<> struct Atomic<uint32> : Lib::Atomic<uint32> {
Atomic<uint32> (uint32 i = 0) : Lib::Atomic<uint32> (i) {}
using Lib::Atomic<uint32>::operator=;
};
/// Atomic int64 type.
template<> struct Atomic<int64> : Lib::Atomic<int64> {
Atomic<int64> (int64 i = 0) : Lib::Atomic<int64> (i) {}
using Lib::Atomic<int64>::operator=;
};
/// Atomic uint64 type.
template<> struct Atomic<uint64> : Lib::Atomic<uint64> {
Atomic<uint64> (uint64 i = 0) : Lib::Atomic<uint64> (i) {}
using Lib::Atomic<uint64>::operator=;
};
/// Atomic pointer type.
template<typename V> class Atomic<V*> : protected Lib::Atomic<V*> {
typedef Lib::Atomic<V*> A;
public:
constexpr Atomic (V *p = nullptr) : A (p) {}
using A::store;
using A::load;
using A::cas;
using A::operator=;
V* operator+= (ptrdiff_t d) volatile { return A::operator+= ((V*) d); }
V* operator-= (ptrdiff_t d) volatile { return A::operator-= ((V*) d); }
operator V* () const volatile { return load(); }
void push_link (V*volatile *nextp, V *newv) { do { *nextp = load(); } while (!cas (*nextp, newv)); }
};
// == Implementation Bits ==
inline ThreadInfo&
ThreadInfo::self()
{
if (RAPICORN_UNLIKELY (!self_cached))
self_cached = create();
return *self_cached;
}
inline bool
ThreadInfo::lookup_pointer (const std::vector<void*> &ptrs, void *arg)
{
size_t n_elements = ptrs.size(), offs = 0;
while (offs < n_elements)
{
size_t i = (offs + n_elements) >> 1;
void *current = ptrs[i];
if (arg == current)
return true; // match
else if (arg < current)
n_elements = i;
else // (arg > current)
offs = i + 1;
}
return false; // unmatched
}
} // Rapicorn
#endif // __RAPICORN_THREAD_HH__
<commit_msg>RCORE: added AsyncBlockingQueue<commit_after>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html
#ifndef __RAPICORN_THREAD_HH__
#define __RAPICORN_THREAD_HH__
#include <rcore/utilities.hh>
#include <rcore/threadlib.hh>
#include <thread>
#include <list>
namespace Rapicorn {
struct RECURSIVE_LOCK {} constexpr RECURSIVE_LOCK {}; ///< Flag for recursive Mutex initialization.
/**
* The Mutex synchronization primitive is a thin wrapper around std::mutex.
* This class supports static construction.
*/
class Mutex {
pthread_mutex_t m_mutex;
public:
constexpr Mutex () : m_mutex (PTHREAD_MUTEX_INITIALIZER) {}
constexpr Mutex (struct RECURSIVE_LOCK) : m_mutex (PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP) {}
void lock () { pthread_mutex_lock (&m_mutex); }
void unlock () { pthread_mutex_unlock (&m_mutex); }
bool try_lock () { return 0 == pthread_mutex_trylock (&m_mutex); }
typedef pthread_mutex_t* native_handle_type;
native_handle_type native_handle() { return &m_mutex; }
/*ctor*/ Mutex (const Mutex&) = delete;
Mutex& operator= (const Mutex&) = delete;
};
/**
* The Spinlock uses low-latency busy spinning to acquire locks.
* It is a thin wrapper around pthread_spin_lock().
* This class supports static construction.
*/
class Spinlock {
pthread_spinlock_t m_spinlock;
public:
constexpr Spinlock () : m_spinlock (RAPICORN_SPINLOCK_INITIALIZER) {}
void lock () { pthread_spin_lock (&m_spinlock); }
void unlock () { pthread_spin_unlock (&m_spinlock); }
bool try_lock () { return 0 == pthread_spin_trylock (&m_spinlock); }
typedef pthread_spinlock_t* native_handle_type;
native_handle_type native_handle() { return &m_spinlock; }
/*ctor*/ Spinlock (const Spinlock&) = delete;
Mutex& operator= (const Spinlock&) = delete;
};
/// Class keeping information per Thread.
struct ThreadInfo {
/// @name Hazard Pointers
typedef std::vector<void*> VoidPointers;
void *volatile hp[8]; ///< Hazard pointers variables, see: http://www.research.ibm.com/people/m/michael/ieeetpds-2004.pdf .
static VoidPointers collect_hazards (); ///< Collect hazard pointers from all threads. Returns sorted vector of unique elements.
static inline bool lookup_pointer (const std::vector<void*> &ptrs, void *arg); ///< Lookup pointers in a hazard pointer vector.
/// @name Thread identification
String ident (); ///< Simple identifier for this thread, usually TID/PID.
String name (); ///< Get thread name.
void name (const String &newname); ///< Change thread name.
static inline ThreadInfo& self (); ///< Get ThreadInfo for the current thread, inlined, using fast thread local storage.
/** @name Accessing custom data members
* For further details, see DataListContainer.
*/
template<typename T> inline T get_data (DataKey<T> *key) { tdl(); T d = m_data_list.get (key); tdu(); return d; }
template<typename T> inline void set_data (DataKey<T> *key, T data) { tdl(); m_data_list.set (key, data); tdu(); }
template<typename T> inline void delete_data (DataKey<T> *key) { tdl(); m_data_list.del (key); tdu(); }
template<typename T> inline T swap_data (DataKey<T> *key) { tdl(); T d = m_data_list.swap (key); tdu(); return d; }
template<typename T> inline T swap_data (DataKey<T> *key, T data) { tdl(); T d = m_data_list.swap (key, data); tdu(); return d; }
private:
ThreadInfo *volatile next;
pthread_t pth_thread_id;
char pad[RAPICORN_CACHE_LINE_ALIGNMENT - sizeof hp - sizeof next - sizeof pth_thread_id];
String m_name;
Mutex m_data_mutex;
DataList m_data_list;
static ThreadInfo __thread *self_cached;
/*ctor*/ ThreadInfo ();
/*ctor*/ ThreadInfo (const ThreadInfo&) = delete;
/*dtor*/ ~ThreadInfo ();
ThreadInfo& operator= (const ThreadInfo&) = delete;
static void destroy_specific(void *vdata);
void reset_specific ();
void setup_specific ();
static ThreadInfo* create ();
void tdl () { m_data_mutex.lock(); }
void tdu () { m_data_mutex.unlock(); }
};
struct AUTOMATIC_LOCK {} constexpr AUTOMATIC_LOCK {}; ///< Flag for automatic locking of a ScopedLock<Mutex>.
struct BALANCED_LOCK {} constexpr BALANCED_LOCK {}; ///< Flag for balancing unlock/lock in a ScopedLock<Mutex>.
/**
* The ScopedLock is a scope based lock ownership wrapper.
* Placing a ScopedLock object on the stack conveniently ensures that its mutex
* will be automatically locked and properly unlocked when the scope is left,
* the current function returns or throws an exception. Mutex obbjects to be used
* by a ScopedLock need to provide the public methods lock() and unlock().
* In AUTOMATIC_LOCK mode, the owned mutex is automatically locked upon construction
* and unlocked upon destruction. Intermediate calls to unlock() and lock() on the
* ScopedLock will be accounted for in the destructor.
* In BALANCED_LOCK mode, the lock is not automatically acquired upon construction,
* however the destructor will balance all intermediate unlock() and lock() calls.
* So this mode can be used to manage ownership for an already locked mutex.
*/
template<class MUTEX>
class ScopedLock : protected NonCopyable {
MUTEX &m_mutex;
volatile int m_count;
public:
inline ~ScopedLock () { while (m_count < 0) lock(); while (m_count > 0) unlock(); }
inline void lock () { m_mutex.lock(); m_count++; }
inline void unlock () { m_count--; m_mutex.unlock(); }
inline ScopedLock (MUTEX &mutex, struct AUTOMATIC_LOCK = AUTOMATIC_LOCK) : m_mutex (mutex), m_count (0) { lock(); }
inline ScopedLock (MUTEX &mutex, struct BALANCED_LOCK) : m_mutex (mutex), m_count (0) {}
};
/**
* The Cond synchronization primitive is a thin wrapper around pthread_cond_wait().
* This class supports static construction.
*/
class Cond {
pthread_cond_t m_cond;
static struct timespec abstime (int64);
/*ctor*/ Cond (const Cond&) = delete;
Cond& operator= (const Cond&) = delete;
public:
constexpr Cond () : m_cond (PTHREAD_COND_INITIALIZER) {}
/*dtor*/ ~Cond () { pthread_cond_destroy (&m_cond); }
void signal () { pthread_cond_signal (&m_cond); }
void broadcast () { pthread_cond_broadcast (&m_cond); }
void wait (Mutex &m) { pthread_cond_wait (&m_cond, m.native_handle()); }
void wait_timed (Mutex &m, int64 max_usecs)
{ struct timespec abs = abstime (max_usecs); pthread_cond_timedwait (&m_cond, m.native_handle(), &abs); }
typedef pthread_cond_t* native_handle_type;
native_handle_type native_handle() { return &m_cond; }
};
/// @namespace Rapicorn::ThisThread The Rapicorn::ThisThread namespace provides functions for the current thread of execution.
namespace ThisThread {
String name (); ///< Get thread name.
int online_cpus (); ///< Get the number of available CPUs.
int affinity (); ///< Get the current CPU affinity.
void affinity (int cpu); ///< Set the current CPU affinity.
int thread_pid (); ///< Get the current threads's thread ID (TID). For further details, see gettid().
int process_pid (); ///< Get the process ID (PID). For further details, see getpid().
#ifdef DOXYGEN // parts reused from std::this_thread
/// Relinquish the processor to allow execution of other threads. For further details, see std::this_thread::yield().
void yield ();
/// Returns the pthread_t id for the current thread. For further details, see std::this_thread::get_id().
std::thread::id get_id ();
/// Sleep for @a sleep_duration has been reached. For further details, see std::this_thread::sleep_for().
template<class Rep, class Period> void sleep_for (std::chrono::duration<Rep,Period> sleep_duration);
/// Sleep until @a sleep_time has been reached. For further details, see std::this_thread::sleep_until().
template<class Clock, class Duration> void sleep_until (const std::chrono::time_point<Clock,Duration> &sleep_time);
#else // !DOXYGEN
using namespace std::this_thread;
#endif // !DOXYGEN
} // ThisThread
#ifdef RAPICORN_CONVENIENCE
/** The @e do_once statement preceeds code blocks to ensure that a critical section is executed atomically and at most once.
* Example: @SNIPPET{rcore/tests/threads.cc, do_once-EXAMPLE}
*/
#define do_once RAPICORN_DO_ONCE
#endif // RAPICORN_CONVENIENCE
/// Atomic types are race free integer and pointer types, similar to std::atomic.
/// All atomic types support load(), store(), cas() and additional type specific accessors.
template<typename T> class Atomic;
/// Atomic char type.
template<> struct Atomic<char> : Lib::Atomic<char> {
Atomic<char> (char i = 0) : Lib::Atomic<char> (i) {}
using Lib::Atomic<char>::operator=;
};
/// Atomic int8 type.
template<> struct Atomic<int8> : Lib::Atomic<int8> {
Atomic<int8> (int8 i = 0) : Lib::Atomic<int8> (i) {}
using Lib::Atomic<int8>::operator=;
};
/// Atomic uint8 type.
template<> struct Atomic<uint8> : Lib::Atomic<uint8> {
Atomic<uint8> (uint8 i = 0) : Lib::Atomic<uint8> (i) {}
using Lib::Atomic<uint8>::operator=;
};
/// Atomic int32 type.
template<> struct Atomic<int32> : Lib::Atomic<int32> {
Atomic<int32> (int32 i = 0) : Lib::Atomic<int32> (i) {}
using Lib::Atomic<int32>::operator=;
};
/// Atomic uint32 type.
template<> struct Atomic<uint32> : Lib::Atomic<uint32> {
Atomic<uint32> (uint32 i = 0) : Lib::Atomic<uint32> (i) {}
using Lib::Atomic<uint32>::operator=;
};
/// Atomic int64 type.
template<> struct Atomic<int64> : Lib::Atomic<int64> {
Atomic<int64> (int64 i = 0) : Lib::Atomic<int64> (i) {}
using Lib::Atomic<int64>::operator=;
};
/// Atomic uint64 type.
template<> struct Atomic<uint64> : Lib::Atomic<uint64> {
Atomic<uint64> (uint64 i = 0) : Lib::Atomic<uint64> (i) {}
using Lib::Atomic<uint64>::operator=;
};
/// Atomic pointer type.
template<typename V> class Atomic<V*> : protected Lib::Atomic<V*> {
typedef Lib::Atomic<V*> A;
public:
constexpr Atomic (V *p = nullptr) : A (p) {}
using A::store;
using A::load;
using A::cas;
using A::operator=;
V* operator+= (ptrdiff_t d) volatile { return A::operator+= ((V*) d); }
V* operator-= (ptrdiff_t d) volatile { return A::operator-= ((V*) d); }
operator V* () const volatile { return load(); }
void push_link (V*volatile *nextp, V *newv) { do { *nextp = load(); } while (!cas (*nextp, newv)); }
};
// == AsyncBlockingQueue ==
/**
* This is a thread-safe asyncronous queue which blocks in pop() until data is provided through push().
*/
template<class Value>
class AsyncBlockingQueue {
Mutex m_mutex;
Cond m_cond;
std::list<Value> m_list;
public:
void push (const Value &v);
Value pop ();
void swap (std::list<Value> &list);
};
// == Implementation Bits ==
template<class Value> void
AsyncBlockingQueue<Value>::push (const Value &v)
{
ScopedLock<Mutex> sl (m_mutex);
const bool notify = m_list.empty();
m_list.push_back (v);
if (RAPICORN_UNLIKELY (notify))
m_cond.broadcast();
}
template<class Value> Value
AsyncBlockingQueue<Value>::pop ()
{
ScopedLock<Mutex> sl (m_mutex);
while (m_list.empty())
m_cond.wait (m_mutex);
Value v = m_list.front();
m_list.pop_front();
return v;
}
template<class Value> void
AsyncBlockingQueue<Value>::swap (std::list<Value> &list)
{
ScopedLock<Mutex> sl (m_mutex);
const bool notify = m_list.empty();
m_list.swap (list);
if (notify && !m_list.empty())
m_cond.broadcast();
}
inline ThreadInfo&
ThreadInfo::self()
{
if (RAPICORN_UNLIKELY (!self_cached))
self_cached = create();
return *self_cached;
}
inline bool
ThreadInfo::lookup_pointer (const std::vector<void*> &ptrs, void *arg)
{
size_t n_elements = ptrs.size(), offs = 0;
while (offs < n_elements)
{
size_t i = (offs + n_elements) >> 1;
void *current = ptrs[i];
if (arg == current)
return true; // match
else if (arg < current)
n_elements = i;
else // (arg > current)
offs = i + 1;
}
return false; // unmatched
}
} // Rapicorn
#endif // __RAPICORN_THREAD_HH__
<|endoftext|>
|
<commit_before>#ifndef TYPE_ARITHMETIC
#define TYPE_ARITHMETIC
struct NullType {};
struct InvalidType {};
typedef char SmallType;
struct BigType { char dummy[16]; };
template<class T> struct TypeForType { typedef T Type;};
template<int N> struct TypeForInt { enum { value = N }; };
template<bool b> struct TypeForBool { enum { value = b}; };
typedef TypeForBool<true> TrueType;
typedef TypeForBool<false> FalseType;
template<class T> struct BoolNot { typedef TypeForBool<!T::value> Type; };
template<class T> struct IntNeg { typedef TypeForInt<-T::value> Type; };
template<class T> struct IntInv { typedef TypeForInt<~int(T::value)> Type; };
template<class T> struct IntInc { typedef TypeForInt<T::value + 1> Type; };
template<class T> struct IntDec { typedef TypeForInt<T::value - 1> Type; };
template<
class T0, class T1,
class T2 = TrueType,
class T3 = TrueType,
class T4 = TrueType,
class T5 = TrueType,
class T6 = TrueType,
class T7 = TrueType
> struct BoolAnd
{
typedef TypeForBool<
T0::value && T1::value
&& T2::value && T3::value
&& T4::value && T5::value
&& T6::value && T7::value
> Type;
};
template<
class T0, class T1,
class T2 = FalseType,
class T3 = FalseType,
class T4 = FalseType,
class T5 = FalseType,
class T6 = FalseType,
class T7 = FalseType
> struct BoolOr
{
typedef TypeForBool<
T0::value || T1::value
|| T2::value || T3::value
|| T4::value || T5::value
|| T6::value || T7::value
> Type;
};
namespace Private {
namespace BoolXorPrivate {
template<class T0, class T1> struct BoolXorHelper2
{
typedef TypeForBool<(T0::value && !T1::value) || (!T0::value && T1::value)> Type;
};
template<class T0, class T1, class T2> struct BoolXorHelper3
{
typedef typename BoolXorHelper2<typename BoolXorHelper2<T0, T1>::Type, T2>::Type Type;
};
template<class T0, class T1, class T2, class T3> struct BoolXorHelper4
{
typedef typename BoolXorHelper2<typename BoolXorHelper3<T0, T1, T2>::Type, T3>::Type Type;
};
template<class T0, class T1, class T2, class T3, class T4> struct BoolXorHelper5
{
typedef typename BoolXorHelper2<typename BoolXorHelper4<T0, T1, T2, T3>::Type, T4>::Type Type;
};
template<class T0, class T1, class T2, class T3, class T4, class T5> struct BoolXorHelper6
{
typedef typename BoolXorHelper2<typename BoolXorHelper5<T0, T1, T2, T3, T4>::Type, T5>::Type Type;
};
template<class T0, class T1, class T2, class T3, class T4, class T5, class T6> struct BoolXorHelper7
{
typedef typename BoolXorHelper2<typename BoolXorHelper6<T0, T1, T2, T3, T4, T5>::Type, T6>::Type Type;
};
template<class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7> struct BoolXorHelper8
{
typedef typename BoolXorHelper2<typename BoolXorHelper7<T0, T1, T2, T3, T4, T5, T6>::Type, T7>::Type Type;
};
} //namespace BoolXorPrivate
} //namespace Private
template<
class T0, class T1,
class T2 = FalseType,
class T3 = FalseType,
class T4 = FalseType,
class T5 = FalseType,
class T6 = FalseType,
class T7 = FalseType
> struct BoolXor
{
typedef typename Private::BoolXorPrivate::BoolXorHelper8<T0, T1, T2, T3, T4, T5, T6, T7>::Type Type;
};
template<
class T0, class T1,
class T2 = TypeForInt<0>,
class T3 = TypeForInt<0>,
class T4 = TypeForInt<0>,
class T5 = TypeForInt<0>,
class T6 = TypeForInt<0>,
class T7 = TypeForInt<0>
> struct IntAdd
{
typedef typename TypeForInt<
T0::value + T1::value
+ T2::value + T3::value
+ T4::value + T5::value
+ T6::value + T7::value
>::Type Type;
};
template<
class T0, class T1,
class T2 = TypeForInt<1>,
class T3 = TypeForInt<1>,
class T4 = TypeForInt<1>,
class T5 = TypeForInt<1>,
class T6 = TypeForInt<1>,
class T7 = TypeForInt<1>
> struct IntMul
{
typedef typename TypeForInt<
T0::value * T1::value
* T2::value * T3::value
* T4::value * T5::value
* T6::value * T7::value
>::Type Type;
};
template<class T0, class T1> struct IntSub { typedef TypeForInt<T0::value - T1::value> Type; };
template<class T0, class T1> struct IntDiv { typedef TypeForInt<T0::value / T1::value> Type; };
template<class T0, class T1> struct IntMod { typedef TypeForInt<T0::value % T1::value> Type; };
template<class T0, class T1> struct IntPow
{
typedef typename IntMul<T0, typename IntPow<T0, typename IntDec<T1>::Type>::Type>::Type Type;
};
template<class T0> struct IntPow<T0, TypeForInt<0> > { typedef T0 Type; };
template<class T0, class T1> struct IntCompare
{
enum
{
isEqual = (T0::value == T1::value),
isNotEqual = (T0::value != T1::value),
isLess = (T0::value < T1::value),
isNotLess = (T0::value >= T1::value),
isGreater = (T0::value < T1::value),
isNotGreater = (T0::value >= T1::value),
};
typedef TypeForBool<isEqual> Equal;
typedef TypeForBool<isNotEqual> NotEqual;
typedef TypeForBool<isLess> Less;
typedef TypeForBool<isNotLess> NotLess;
typedef TypeForBool<isGreater> Greater;
typedef TypeForBool<isNotGreater> NotGreater;
};
namespace Private {
namespace TypeIfPrivate {
template<class T, class Y> struct TypeIfHelper;
template<class Y> struct TypeIfHelper<TrueType, Y> { typedef Y Type; };
template<class Y> struct TypeIfHelper<FalseType, Y> { };
} //namespace TypeIfPrivate
} //namespace Private
template<class Cond, class ThenClass, class ElseClass> struct TypeIf
: public Private::TypeIfPrivate::TypeIfHelper<Cond, ThenClass>
, public Private::TypeIfPrivate::TypeIfHelper<typename BoolNot<Cond>::Type, ElseClass>
{};
#endif //TYPE_ARITHMETIC<commit_msg>-: Fixed: bug in IntPow<> meta-function<commit_after>#ifndef TYPE_ARITHMETIC
#define TYPE_ARITHMETIC
struct NullType {};
struct InvalidType {};
typedef char SmallType;
struct BigType { char dummy[16]; };
template<class T> struct TypeForType { typedef T Type;};
template<int N> struct TypeForInt { enum { value = N }; };
template<bool b> struct TypeForBool { enum { value = b}; };
typedef TypeForBool<true> TrueType;
typedef TypeForBool<false> FalseType;
template<class T> struct BoolNot { typedef TypeForBool<!T::value> Type; };
template<class T> struct IntNeg { typedef TypeForInt<-T::value> Type; };
template<class T> struct IntInv { typedef TypeForInt<~int(T::value)> Type; };
template<class T> struct IntInc { typedef TypeForInt<T::value + 1> Type; };
template<class T> struct IntDec { typedef TypeForInt<T::value - 1> Type; };
template<
class T0, class T1,
class T2 = TrueType,
class T3 = TrueType,
class T4 = TrueType,
class T5 = TrueType,
class T6 = TrueType,
class T7 = TrueType
> struct BoolAnd
{
typedef TypeForBool<
T0::value && T1::value
&& T2::value && T3::value
&& T4::value && T5::value
&& T6::value && T7::value
> Type;
};
template<
class T0, class T1,
class T2 = FalseType,
class T3 = FalseType,
class T4 = FalseType,
class T5 = FalseType,
class T6 = FalseType,
class T7 = FalseType
> struct BoolOr
{
typedef TypeForBool<
T0::value || T1::value
|| T2::value || T3::value
|| T4::value || T5::value
|| T6::value || T7::value
> Type;
};
namespace Private {
namespace BoolXorPrivate {
template<class T0, class T1> struct BoolXorHelper2
{
typedef TypeForBool<(T0::value && !T1::value) || (!T0::value && T1::value)> Type;
};
template<class T0, class T1, class T2> struct BoolXorHelper3
{
typedef typename BoolXorHelper2<typename BoolXorHelper2<T0, T1>::Type, T2>::Type Type;
};
template<class T0, class T1, class T2, class T3> struct BoolXorHelper4
{
typedef typename BoolXorHelper2<typename BoolXorHelper3<T0, T1, T2>::Type, T3>::Type Type;
};
template<class T0, class T1, class T2, class T3, class T4> struct BoolXorHelper5
{
typedef typename BoolXorHelper2<typename BoolXorHelper4<T0, T1, T2, T3>::Type, T4>::Type Type;
};
template<class T0, class T1, class T2, class T3, class T4, class T5> struct BoolXorHelper6
{
typedef typename BoolXorHelper2<typename BoolXorHelper5<T0, T1, T2, T3, T4>::Type, T5>::Type Type;
};
template<class T0, class T1, class T2, class T3, class T4, class T5, class T6> struct BoolXorHelper7
{
typedef typename BoolXorHelper2<typename BoolXorHelper6<T0, T1, T2, T3, T4, T5>::Type, T6>::Type Type;
};
template<class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7> struct BoolXorHelper8
{
typedef typename BoolXorHelper2<typename BoolXorHelper7<T0, T1, T2, T3, T4, T5, T6>::Type, T7>::Type Type;
};
} //namespace BoolXorPrivate
} //namespace Private
template<
class T0, class T1,
class T2 = FalseType,
class T3 = FalseType,
class T4 = FalseType,
class T5 = FalseType,
class T6 = FalseType,
class T7 = FalseType
> struct BoolXor
{
typedef typename Private::BoolXorPrivate::BoolXorHelper8<T0, T1, T2, T3, T4, T5, T6, T7>::Type Type;
};
template<
class T0, class T1,
class T2 = TypeForInt<0>,
class T3 = TypeForInt<0>,
class T4 = TypeForInt<0>,
class T5 = TypeForInt<0>,
class T6 = TypeForInt<0>,
class T7 = TypeForInt<0>
> struct IntAdd
{
typedef typename TypeForInt<
T0::value + T1::value
+ T2::value + T3::value
+ T4::value + T5::value
+ T6::value + T7::value
>::Type Type;
};
template<
class T0, class T1,
class T2 = TypeForInt<1>,
class T3 = TypeForInt<1>,
class T4 = TypeForInt<1>,
class T5 = TypeForInt<1>,
class T6 = TypeForInt<1>,
class T7 = TypeForInt<1>
> struct IntMul
{
typedef typename TypeForInt<
T0::value * T1::value
* T2::value * T3::value
* T4::value * T5::value
* T6::value * T7::value
>::Type Type;
};
template<class T0, class T1> struct IntSub { typedef TypeForInt<T0::value - T1::value> Type; };
template<class T0, class T1> struct IntDiv { typedef TypeForInt<T0::value / T1::value> Type; };
template<class T0, class T1> struct IntMod { typedef TypeForInt<T0::value % T1::value> Type; };
template<class T0, class T1> struct IntPow
{
typedef typename IntMul<T0, typename IntPow<T0, typename IntDec<T1>::Type>::Type>::Type Type;
};
template<class T0> struct IntPow<T0, TypeForInt<0> > { typedef TypeForInt<1> Type; };
template<class T0, class T1> struct IntCompare
{
enum
{
isEqual = (T0::value == T1::value),
isNotEqual = (T0::value != T1::value),
isLess = (T0::value < T1::value),
isNotLess = (T0::value >= T1::value),
isGreater = (T0::value < T1::value),
isNotGreater = (T0::value >= T1::value),
};
typedef TypeForBool<isEqual> Equal;
typedef TypeForBool<isNotEqual> NotEqual;
typedef TypeForBool<isLess> Less;
typedef TypeForBool<isNotLess> NotLess;
typedef TypeForBool<isGreater> Greater;
typedef TypeForBool<isNotGreater> NotGreater;
};
namespace Private {
namespace TypeIfPrivate {
template<class T, class Y> struct TypeIfHelper;
template<class Y> struct TypeIfHelper<TrueType, Y> { typedef Y Type; };
template<class Y> struct TypeIfHelper<FalseType, Y> { };
} //namespace TypeIfPrivate
} //namespace Private
template<class Cond, class ThenClass, class ElseClass> struct TypeIf
: public Private::TypeIfPrivate::TypeIfHelper<Cond, ThenClass>
, public Private::TypeIfPrivate::TypeIfHelper<typename BoolNot<Cond>::Type, ElseClass>
{};
#endif //TYPE_ARITHMETIC<|endoftext|>
|
<commit_before>// @(#)root/thread:$Id$
// Author: Fons Rademakers 25/06/97
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TPosixMutex //
// //
// This class provides an interface to the posix mutex routines. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TThread.h"
#include "TPosixMutex.h"
#include "PosixThreadInc.h"
ClassImp(TPosixMutex);
////////////////////////////////////////////////////////////////////////////////
/// Create a posix mutex lock.
TPosixMutex::TPosixMutex(Bool_t recursive) : TMutexImp()
{
if (recursive) {
SetBit(kIsRecursive);
int rc;
pthread_mutexattr_t attr;
rc = pthread_mutexattr_init(&attr);
if (!rc) {
rc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
if (!rc) {
rc = pthread_mutex_init(&fMutex, &attr);
if (rc)
SysError("TPosixMutex", "pthread_mutex_init error");
} else
SysError("TPosixMutex", "pthread_mutexattr_settype error");
} else
SysError("TPosixMutex", "pthread_mutex_init error");
pthread_mutexattr_destroy(&attr);
} else {
int rc = pthread_mutex_init(&fMutex, 0);
if (rc)
SysError("TPosixMutex", "pthread_mutex_init error");
}
}
////////////////////////////////////////////////////////////////////////////////
/// TMutex dtor.
TPosixMutex::~TPosixMutex()
{
int rc = pthread_mutex_destroy(&fMutex);
if (rc)
SysError("~TPosixMutex", "pthread_mutex_destroy error");
}
////////////////////////////////////////////////////////////////////////////////
/// Lock the mutex.
Int_t TPosixMutex::Lock()
{
return pthread_mutex_lock(&fMutex);
}
////////////////////////////////////////////////////////////////////////////////
/// Try locking the mutex. Returns 0 if mutex can be locked.
Int_t TPosixMutex::TryLock()
{
return pthread_mutex_trylock(&fMutex);
}
////////////////////////////////////////////////////////////////////////////////
/// Unlock the mutex.
Int_t TPosixMutex::UnLock(void)
{
return pthread_mutex_unlock(&fMutex);
}
namespace {
struct TPosixMutexState: public TVirtualMutex::State {
int fLockCount = 0;
};
}
////////////////////////////////////////////////////////////////////////////////
/// Reset the mutex state to unlocked. The state before resetting to unlocked is
/// returned and can be passed to `Restore()` later on. This function must only
/// be called while the mutex is locked.
std::unique_ptr<TVirtualMutex::State> TPosixMutex::Reset()
{
std::unique_ptr<TPosixMutexState> pState(new TPosixMutexState);
if (TestBit(kIsRecursive)) {
while (!UnLock())
++pState->fLockCount;
return std::move(pState);
}
// Not recursive. Unlocking a non-recursive, non-robust, unlocked mutex has an
// undefined return value - so we cannot *guarantee* that the mutex is locked.
// But we can try.
if (int rc = UnLock()) {
SysError("Reset", "pthread_mutex_unlock failed with %d, "
"but Reset() must be called on locked mutex!",
rc);
return std::move(pState);
}
++pState->fLockCount;
return std::move(pState);
}
////////////////////////////////////////////////////////////////////////////////
/// Restore the mutex state to the state pointed to by `state`. This function
/// must only be called while the mutex is unlocked.
void TPosixMutex::Restore(std::unique_ptr<TVirtualMutex::State> &&state)
{
TPosixMutexState *pState = dynamic_cast<TPosixMutexState *>(state.get());
if (!pState) {
if (state) {
SysError("Restore", "LOGIC ERROR - invalid state object!");
return;
}
// No state, do nothing.
return;
}
do {
Lock();
} while (--pState->fLockCount);
}
<commit_msg>Assert that the mutex is locked. Else we risk an int underflow.<commit_after>// @(#)root/thread:$Id$
// Author: Fons Rademakers 25/06/97
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TPosixMutex //
// //
// This class provides an interface to the posix mutex routines. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TThread.h"
#include "TPosixMutex.h"
#include "PosixThreadInc.h"
ClassImp(TPosixMutex);
////////////////////////////////////////////////////////////////////////////////
/// Create a posix mutex lock.
TPosixMutex::TPosixMutex(Bool_t recursive) : TMutexImp()
{
if (recursive) {
SetBit(kIsRecursive);
int rc;
pthread_mutexattr_t attr;
rc = pthread_mutexattr_init(&attr);
if (!rc) {
rc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
if (!rc) {
rc = pthread_mutex_init(&fMutex, &attr);
if (rc)
SysError("TPosixMutex", "pthread_mutex_init error");
} else
SysError("TPosixMutex", "pthread_mutexattr_settype error");
} else
SysError("TPosixMutex", "pthread_mutex_init error");
pthread_mutexattr_destroy(&attr);
} else {
int rc = pthread_mutex_init(&fMutex, 0);
if (rc)
SysError("TPosixMutex", "pthread_mutex_init error");
}
}
////////////////////////////////////////////////////////////////////////////////
/// TMutex dtor.
TPosixMutex::~TPosixMutex()
{
int rc = pthread_mutex_destroy(&fMutex);
if (rc)
SysError("~TPosixMutex", "pthread_mutex_destroy error");
}
////////////////////////////////////////////////////////////////////////////////
/// Lock the mutex.
Int_t TPosixMutex::Lock()
{
return pthread_mutex_lock(&fMutex);
}
////////////////////////////////////////////////////////////////////////////////
/// Try locking the mutex. Returns 0 if mutex can be locked.
Int_t TPosixMutex::TryLock()
{
return pthread_mutex_trylock(&fMutex);
}
////////////////////////////////////////////////////////////////////////////////
/// Unlock the mutex.
Int_t TPosixMutex::UnLock(void)
{
return pthread_mutex_unlock(&fMutex);
}
namespace {
struct TPosixMutexState: public TVirtualMutex::State {
int fLockCount = 0;
};
}
////////////////////////////////////////////////////////////////////////////////
/// Reset the mutex state to unlocked. The state before resetting to unlocked is
/// returned and can be passed to `Restore()` later on. This function must only
/// be called while the mutex is locked.
std::unique_ptr<TVirtualMutex::State> TPosixMutex::Reset()
{
std::unique_ptr<TPosixMutexState> pState(new TPosixMutexState);
if (TestBit(kIsRecursive)) {
while (!UnLock())
++pState->fLockCount;
if (!pState->fLockCount)
SysError("Reset", "Reset() called on unlocked Mutex!");
return std::move(pState);
}
// Not recursive. Unlocking a non-recursive, non-robust, unlocked mutex has an
// undefined return value - so we cannot *guarantee* that the mutex is locked.
// But we can try.
if (int rc = UnLock()) {
SysError("Reset", "pthread_mutex_unlock failed with %d, "
"but Reset() must be called on locked mutex!",
rc);
return std::move(pState);
}
++pState->fLockCount;
return std::move(pState);
}
////////////////////////////////////////////////////////////////////////////////
/// Restore the mutex state to the state pointed to by `state`. This function
/// must only be called while the mutex is unlocked.
void TPosixMutex::Restore(std::unique_ptr<TVirtualMutex::State> &&state)
{
TPosixMutexState *pState = dynamic_cast<TPosixMutexState *>(state.get());
if (!pState) {
if (state) {
SysError("Restore", "LOGIC ERROR - invalid state object!");
return;
}
// No state, do nothing.
return;
}
if (!pState->fLockCount) {
SysError("Reset", "Restore() called with unlocked state!");
return;
}
do {
Lock();
} while (--pState->fLockCount);
}
<|endoftext|>
|
<commit_before>//===--- AccessPathVerification.cpp - verify access paths and storage -----===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// Verify AccessPath computation. For the address of every memory operation in
/// the module, compute the access path, compute all the users of that path,
/// then verify that all users have the same access path.
///
/// This is potentially expensive, so there is a fast mode that limits the
/// number of uses visited per path.
///
/// During full verification, also check that all addresses that share an
/// AccessPath are covered when computed the use list of that AccessPath. This
/// is important because optimizations may assume that the use list is
/// complete.
///
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "access-path-verification"
#include "swift/SIL/MemAccessUtils.h"
#include "swift/SIL/PrettyStackTrace.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILValue.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "llvm/Support/Debug.h"
using namespace swift;
namespace {
/// Verify access path and uses of each access.
class AccessPathVerification : public SILModuleTransform {
llvm::DenseMap<Operand *, AccessPath> useToPathMap;
// Transient uses
llvm::SmallVector<Operand *, 64> uses;
public:
void verifyAccessPath(Operand *operand) {
auto accessPath = AccessPath::compute(operand->get());
if (!accessPath.isValid())
return;
auto iterAndInserted = useToPathMap.try_emplace(operand, accessPath);
// If this use was already computed from a previously visited path, make
// sure the path we just computed matches.
if (!iterAndInserted.second) {
auto collectedFromPath = iterAndInserted.first->second;
if (collectedFromPath != accessPath) {
llvm::errs() << "Address use: " << *operand->getUser()
<< " collected from path\n ";
collectedFromPath.dump();
llvm::errs() << " has different path\n ";
accessPath.dump();
operand->getUser()->getFunction()->dump();
assert(false && "computed path does not match collected path");
}
return;
}
// This is a new path, so map all its uses.
assert(uses.empty());
accessPath.collectUses(uses, AccessUseType::Exact,
operand->getParentFunction());
bool foundOperandUse = false;
for (Operand *use : uses) {
if (use == operand) {
foundOperandUse = true;
continue;
}
auto iterAndInserted = useToPathMap.try_emplace(use, accessPath);
if (!iterAndInserted.second) {
llvm::errs() << "Address use: " << *operand->getUser()
<< " with path...\n";
accessPath.dump();
llvm::errs() << " was not collected for: " << *use->getUser();
llvm::errs() << " with path...\n";
auto computedPath = iterAndInserted.first->second;
computedPath.dump();
use->getUser()->getFunction()->dump();
assert(false && "missing collected use");
}
}
if (!foundOperandUse && !accessPath.hasUnknownOffset()) {
llvm::errs() << "Address use: " << *operand->getUser()
<< " is not a use of path\n ";
accessPath.dump();
assert(false && "not a user of its own computed path ");
}
uses.clear();
}
void run() override {
for (auto &fn : *getModule()) {
if (fn.empty())
continue;
PrettyStackTraceSILFunction functionDumper("...", &fn);
for (auto &bb : fn) {
for (auto &inst : bb) {
if (inst.mayReadOrWriteMemory())
visitAccessedAddress(&inst, [this](Operand *operand) {
return verifyAccessPath(operand);
});
}
}
useToPathMap.clear();
}
}
};
} // end anonymous namespace
SILTransform *swift::createAccessPathVerification() {
return new AccessPathVerification();
}
<commit_msg>The verifier should only output to llvm::errs()<commit_after>//===--- AccessPathVerification.cpp - verify access paths and storage -----===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// Verify AccessPath computation. For the address of every memory operation in
/// the module, compute the access path, compute all the users of that path,
/// then verify that all users have the same access path.
///
/// This is potentially expensive, so there is a fast mode that limits the
/// number of uses visited per path.
///
/// During full verification, also check that all addresses that share an
/// AccessPath are covered when computed the use list of that AccessPath. This
/// is important because optimizations may assume that the use list is
/// complete.
///
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "access-path-verification"
#include "swift/SIL/MemAccessUtils.h"
#include "swift/SIL/PrettyStackTrace.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILValue.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "llvm/Support/Debug.h"
using namespace swift;
namespace {
/// Verify access path and uses of each access.
class AccessPathVerification : public SILModuleTransform {
llvm::DenseMap<Operand *, AccessPath> useToPathMap;
// Transient uses
llvm::SmallVector<Operand *, 64> uses;
public:
void verifyAccessPath(Operand *operand) {
auto accessPath = AccessPath::compute(operand->get());
if (!accessPath.isValid())
return;
auto iterAndInserted = useToPathMap.try_emplace(operand, accessPath);
// If this use was already computed from a previously visited path, make
// sure the path we just computed matches.
if (!iterAndInserted.second) {
auto collectedFromPath = iterAndInserted.first->second;
if (collectedFromPath != accessPath) {
llvm::errs() << "Address use: " << *operand->getUser()
<< " collected from path\n ";
collectedFromPath.print(llvm::errs());
llvm::errs() << " has different path\n ";
accessPath.print(llvm::errs());
operand->getUser()->getFunction()->print(llvm::errs());
assert(false && "computed path does not match collected path");
}
return;
}
// This is a new path, so map all its uses.
assert(uses.empty());
accessPath.collectUses(uses, AccessUseType::Exact,
operand->getParentFunction());
bool foundOperandUse = false;
for (Operand *use : uses) {
if (use == operand) {
foundOperandUse = true;
continue;
}
auto iterAndInserted = useToPathMap.try_emplace(use, accessPath);
if (!iterAndInserted.second) {
llvm::errs() << "Address use: " << *operand->getUser()
<< " with path...\n";
accessPath.print(llvm::errs());
llvm::errs() << " was not collected for: " << *use->getUser();
llvm::errs() << " with path...\n";
auto computedPath = iterAndInserted.first->second;
computedPath.print(llvm::errs());
use->getUser()->getFunction()->print(llvm::errs());
assert(false && "missing collected use");
}
}
if (!foundOperandUse && !accessPath.hasUnknownOffset()) {
llvm::errs() << "Address use: " << *operand->getUser()
<< " is not a use of path\n ";
accessPath.print(llvm::errs());
assert(false && "not a user of its own computed path ");
}
uses.clear();
}
void run() override {
for (auto &fn : *getModule()) {
if (fn.empty())
continue;
PrettyStackTraceSILFunction functionDumper("...", &fn);
for (auto &bb : fn) {
for (auto &inst : bb) {
if (inst.mayReadOrWriteMemory())
visitAccessedAddress(&inst, [this](Operand *operand) {
return verifyAccessPath(operand);
});
}
}
useToPathMap.clear();
}
}
};
} // end anonymous namespace
SILTransform *swift::createAccessPathVerification() {
return new AccessPathVerification();
}
<|endoftext|>
|
<commit_before>/*
yahoochatselectordialog.h
Copyright (c) 2006 by Andre Duffeck <andre@duffeck.de>
Kopete (c) 2002-2006 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program 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. *
* *
*************************************************************************
*/
#include <QDomDocument>
#include <QTreeWidgetItem>
#include <QHeaderView>
#include "ui_yahoochatselectorwidgetbase.h"
#include "yahoochatselectordialog.h"
YahooChatSelectorDialog::YahooChatSelectorDialog( QWidget *parent )
: KDialog( parent )
{
setCaption( i18n( "Choose a chat room..." ) );
setButtons( KDialog::Ok | KDialog::Cancel );
setDefaultButton( KDialog::Ok );
showButtonSeparator( true );
mUi = new Ui_YahooChatSelectorWidgetBase();
QBoxLayout *layout = new QVBoxLayout(this);
QWidget *widget = new QWidget(this);
mUi->setupUi(widget);
layout->addWidget(widget);
setMainWidget(widget);
mUi->treeCategories->header()->hide();
mUi->treeRooms->header()->hide();
QTreeWidgetItem *loading = new QTreeWidgetItem(mUi->treeCategories);
loading->setText( 0, i18n("Loading...") );
mUi->treeCategories->addTopLevelItem( loading );
connect(mUi->treeCategories, SIGNAL(currentItemChanged ( QTreeWidgetItem *, QTreeWidgetItem * )),
this, SLOT(slotCategorySelectionChanged( QTreeWidgetItem *, QTreeWidgetItem * )));
connect(mUi->treeRooms, SIGNAL(itemDoubleClicked( QTreeWidgetItem *, int )),
this, SLOT(slotChatRoomDoubleClicked( QTreeWidgetItem *, int )) );
}
YahooChatSelectorDialog::~YahooChatSelectorDialog()
{
delete mUi;
}
void YahooChatSelectorDialog::slotCategorySelectionChanged( QTreeWidgetItem *newItem, QTreeWidgetItem *oldItem )
{
Q_UNUSED( oldItem );
kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << "Selected Category: " << newItem->text( 0 ) << "(" << newItem->data( 0, Qt::UserRole ).toInt() << ")" << endl;
mUi->treeRooms->clear();
QTreeWidgetItem *loading = new QTreeWidgetItem(mUi->treeRooms);
loading->setText( 0, i18n("Loading...") );
mUi->treeRooms->addTopLevelItem( loading );
Yahoo::ChatCategory category;
category.id = newItem->data( 0, Qt::UserRole ).toInt();
category.name = newItem->text( 0 );
emit chatCategorySelected( category );
}
void YahooChatSelectorDialog::slotChatRoomDoubleClicked( QTreeWidgetItem * item, int column )
{
Q_UNUSED( column );
Q_UNUSED( item );
QDialog::accept();
}
void YahooChatSelectorDialog::slotSetChatCategories( const QDomDocument &doc )
{
kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << doc.toString() << endl;
mUi->treeCategories->takeTopLevelItem(0);
QTreeWidgetItem *root = new QTreeWidgetItem( mUi->treeCategories );
root->setText( 0, i18n("Yahoo Chat rooms") );
QDomNode child = doc.firstChild();
mUi->treeCategories->setItemExpanded( root, true );
while( !child.isNull() )
{
parseChatCategory(child, root);
child = child.nextSibling();
}
}
void YahooChatSelectorDialog::parseChatCategory( const QDomNode &node, QTreeWidgetItem *parentItem )
{
QTreeWidgetItem *newParent = parentItem;
if( node.nodeName().startsWith( "category" ) )
{
QTreeWidgetItem *item = new QTreeWidgetItem( parentItem );
item->setText( 0, node.toElement().attribute( "name" ) );
item->setData( 0, Qt::UserRole, node.toElement().attribute( "id" ) );
parentItem->addChild( item );
newParent = item;
}
QDomNode child = node.firstChild();
while( !child.isNull() )
{
parseChatCategory(child, newParent);
child = child.nextSibling();
}
}
void YahooChatSelectorDialog::slotSetChatRooms( const Yahoo::ChatCategory &category, const QDomDocument &doc )
{
kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << doc.toString() << endl;
Q_UNUSED( category );
mUi->treeRooms->clear();
QDomNode child = doc.firstChild();
while( !child.isNull() )
{
parseChatRoom( child );
child = child.nextSibling();
}
}
void YahooChatSelectorDialog::parseChatRoom( const QDomNode &node )
{
if( node.nodeName().startsWith( "room" ) )
{
QTreeWidgetItem *item = new QTreeWidgetItem( mUi->treeRooms );
QDomElement elem = node.toElement();
QString name = elem.attribute( "name" );
QString id = elem.attribute( "id" );
item->setText( 0, name );
item->setData( 0, Qt::ToolTipRole, elem.attribute( "topic" ) );
item->setData( 0, Qt::UserRole, id );
QDomNode child;
for( child = node.firstChild(); !child.isNull(); child = child.nextSibling() )
{
if( child.nodeName().startsWith( "lobby" ) )
{
QTreeWidgetItem *lobby = new QTreeWidgetItem( item );
QDomElement e = child.toElement();
QString voices = e.attribute( "voices" );
QString users = e.attribute( "users" );
QString webcams = e.attribute( "webcams" );
QString count = e.attribute( "count" );
lobby->setText( 0, name + QString( ":%1" )
.arg( count ) );
lobby->setData( 0, Qt::ToolTipRole, QString( "Users: %1 Webcams: %2 Voices: %3" )
.arg( users, webcams, voices ) );
lobby->setData( 0, Qt::UserRole, id );
item->addChild( lobby );
}
}
}
else
{
QDomNode child = node.firstChild();
while( !child.isNull() )
{
parseChatRoom( child );
child = child.nextSibling();
}
}
}
Yahoo::ChatRoom YahooChatSelectorDialog::selectedRoom()
{
Yahoo::ChatRoom room;
QTreeWidgetItem *item = mUi->treeRooms->selectedItems().first();
room.name = item->text( 0 );
room.topic = item->data( 0, Qt::ToolTipRole ).toString();
room.id = item->data( 0, Qt::UserRole ).toInt();
return room;
}
#include "yahoochatselectordialog.moc"
<commit_msg>i18n()<commit_after>/*
yahoochatselectordialog.h
Copyright (c) 2006 by Andre Duffeck <andre@duffeck.de>
Kopete (c) 2002-2006 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program 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. *
* *
*************************************************************************
*/
#include <QDomDocument>
#include <QTreeWidgetItem>
#include <QHeaderView>
#include "ui_yahoochatselectorwidgetbase.h"
#include "yahoochatselectordialog.h"
YahooChatSelectorDialog::YahooChatSelectorDialog( QWidget *parent )
: KDialog( parent )
{
setCaption( i18n( "Choose a chat room..." ) );
setButtons( KDialog::Ok | KDialog::Cancel );
setDefaultButton( KDialog::Ok );
showButtonSeparator( true );
mUi = new Ui_YahooChatSelectorWidgetBase();
QBoxLayout *layout = new QVBoxLayout(this);
QWidget *widget = new QWidget(this);
mUi->setupUi(widget);
layout->addWidget(widget);
setMainWidget(widget);
mUi->treeCategories->header()->hide();
mUi->treeRooms->header()->hide();
QTreeWidgetItem *loading = new QTreeWidgetItem(mUi->treeCategories);
loading->setText( 0, i18n("Loading...") );
mUi->treeCategories->addTopLevelItem( loading );
connect(mUi->treeCategories, SIGNAL(currentItemChanged ( QTreeWidgetItem *, QTreeWidgetItem * )),
this, SLOT(slotCategorySelectionChanged( QTreeWidgetItem *, QTreeWidgetItem * )));
connect(mUi->treeRooms, SIGNAL(itemDoubleClicked( QTreeWidgetItem *, int )),
this, SLOT(slotChatRoomDoubleClicked( QTreeWidgetItem *, int )) );
}
YahooChatSelectorDialog::~YahooChatSelectorDialog()
{
delete mUi;
}
void YahooChatSelectorDialog::slotCategorySelectionChanged( QTreeWidgetItem *newItem, QTreeWidgetItem *oldItem )
{
Q_UNUSED( oldItem );
kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << "Selected Category: " << newItem->text( 0 ) << "(" << newItem->data( 0, Qt::UserRole ).toInt() << ")" << endl;
mUi->treeRooms->clear();
QTreeWidgetItem *loading = new QTreeWidgetItem(mUi->treeRooms);
loading->setText( 0, i18n("Loading...") );
mUi->treeRooms->addTopLevelItem( loading );
Yahoo::ChatCategory category;
category.id = newItem->data( 0, Qt::UserRole ).toInt();
category.name = newItem->text( 0 );
emit chatCategorySelected( category );
}
void YahooChatSelectorDialog::slotChatRoomDoubleClicked( QTreeWidgetItem * item, int column )
{
Q_UNUSED( column );
Q_UNUSED( item );
QDialog::accept();
}
void YahooChatSelectorDialog::slotSetChatCategories( const QDomDocument &doc )
{
kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << doc.toString() << endl;
mUi->treeCategories->takeTopLevelItem(0);
QTreeWidgetItem *root = new QTreeWidgetItem( mUi->treeCategories );
root->setText( 0, i18n("Yahoo Chat rooms") );
QDomNode child = doc.firstChild();
mUi->treeCategories->setItemExpanded( root, true );
while( !child.isNull() )
{
parseChatCategory(child, root);
child = child.nextSibling();
}
}
void YahooChatSelectorDialog::parseChatCategory( const QDomNode &node, QTreeWidgetItem *parentItem )
{
QTreeWidgetItem *newParent = parentItem;
if( node.nodeName().startsWith( "category" ) )
{
QTreeWidgetItem *item = new QTreeWidgetItem( parentItem );
item->setText( 0, node.toElement().attribute( "name" ) );
item->setData( 0, Qt::UserRole, node.toElement().attribute( "id" ) );
parentItem->addChild( item );
newParent = item;
}
QDomNode child = node.firstChild();
while( !child.isNull() )
{
parseChatCategory(child, newParent);
child = child.nextSibling();
}
}
void YahooChatSelectorDialog::slotSetChatRooms( const Yahoo::ChatCategory &category, const QDomDocument &doc )
{
kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << doc.toString() << endl;
Q_UNUSED( category );
mUi->treeRooms->clear();
QDomNode child = doc.firstChild();
while( !child.isNull() )
{
parseChatRoom( child );
child = child.nextSibling();
}
}
void YahooChatSelectorDialog::parseChatRoom( const QDomNode &node )
{
if( node.nodeName().startsWith( "room" ) )
{
QTreeWidgetItem *item = new QTreeWidgetItem( mUi->treeRooms );
QDomElement elem = node.toElement();
QString name = elem.attribute( "name" );
QString id = elem.attribute( "id" );
item->setText( 0, name );
item->setData( 0, Qt::ToolTipRole, elem.attribute( "topic" ) );
item->setData( 0, Qt::UserRole, id );
QDomNode child;
for( child = node.firstChild(); !child.isNull(); child = child.nextSibling() )
{
if( child.nodeName().startsWith( "lobby" ) )
{
QTreeWidgetItem *lobby = new QTreeWidgetItem( item );
QDomElement e = child.toElement();
QString voices = e.attribute( "voices" );
QString users = e.attribute( "users" );
QString webcams = e.attribute( "webcams" );
QString count = e.attribute( "count" );
lobby->setText( 0, name + QString( ":%1" )
.arg( count ) );
lobby->setData( 0, Qt::ToolTipRole, i18n( "Users: %1 Webcams: %2 Voices: %3" )
.arg( users, webcams, voices ) );
lobby->setData( 0, Qt::UserRole, id );
item->addChild( lobby );
}
}
}
else
{
QDomNode child = node.firstChild();
while( !child.isNull() )
{
parseChatRoom( child );
child = child.nextSibling();
}
}
}
Yahoo::ChatRoom YahooChatSelectorDialog::selectedRoom()
{
Yahoo::ChatRoom room;
QTreeWidgetItem *item = mUi->treeRooms->selectedItems().first();
room.name = item->text( 0 );
room.topic = item->data( 0, Qt::ToolTipRole ).toString();
room.id = item->data( 0, Qt::UserRole ).toInt();
return room;
}
#include "yahoochatselectordialog.moc"
<|endoftext|>
|
<commit_before>#ifndef NSB_FILE_HPP
#define NSB_FILE_HPP
#include "scriptfile.hpp"
#include <vector>
#include <map>
struct Line
{
uint16_t Magic;
std::vector<std::string> Params;
};
class NsbFile : public ScriptFile
{
public:
NsbFile(const std::string& Name, char* Data = nullptr, uint32_t Size = 0);
static bool IsValidMagic(uint16_t Magic);
static const char* StringifyMagic(uint16_t Magic);
static uint16_t MagicifyString(const char* String);
Line* GetNextLine();
uint32_t GetFunctionLine(const char* Name) const;
void SetSourceIter(uint32_t NewIter);
uint32_t GetNextLineEntry() const;
private:
void Read(std::istream* pStream);
uint32_t SourceIter;
std::vector<Line> Source;
std::map<const char*, uint32_t> Functions;
std::string Name;
};
#endif
<commit_msg>Fix fail. Symbol lookup works fine now<commit_after>#ifndef NSB_FILE_HPP
#define NSB_FILE_HPP
#include "scriptfile.hpp"
#include <vector>
#include <map>
struct Line
{
uint16_t Magic;
std::vector<std::string> Params;
};
class NsbFile : public ScriptFile
{
public:
NsbFile(const std::string& Name, char* Data = nullptr, uint32_t Size = 0);
static bool IsValidMagic(uint16_t Magic);
static const char* StringifyMagic(uint16_t Magic);
static uint16_t MagicifyString(const char* String);
Line* GetNextLine();
uint32_t GetFunctionLine(const char* Name) const;
void SetSourceIter(uint32_t NewIter);
uint32_t GetNextLineEntry() const;
private:
void Read(std::istream* pStream);
uint32_t SourceIter;
std::vector<Line> Source;
std::map<std::string, uint32_t> Functions;
std::string Name;
};
#endif
<|endoftext|>
|
<commit_before>#include "style.h"
#include "material.h"
#include "gl/renderState.h"
#include "gl/shaderProgram.h"
#include "gl/mesh.h"
#include "scene/light.h"
#include "scene/styleParam.h"
#include "scene/drawRule.h"
#include "scene/scene.h"
#include "scene/spriteAtlas.h"
#include "tile/tile.h"
#include "data/dataSource.h"
#include "view/view.h"
#include "tangram.h"
namespace Tangram {
Style::Style(std::string _name, Blending _blendMode, GLenum _drawMode) :
m_name(_name),
m_shaderProgram(std::make_unique<ShaderProgram>()),
m_blend(_blendMode),
m_drawMode(_drawMode) {
m_material.material = std::make_shared<Material>();
}
Style::~Style() {}
Style::LightHandle::LightHandle(Light* _light, std::unique_ptr<LightUniforms> _uniforms)
: light(_light), uniforms(std::move(_uniforms)){}
const std::vector<std::string>& Style::builtInStyleNames() {
static std::vector<std::string> builtInStyleNames{ "points", "lines", "polygons", "text", "debug", "debugtext" };
return builtInStyleNames;
}
void Style::build(const Scene& _scene) {
constructVertexLayout();
constructShaderProgram();
m_shaderProgram->setDescription("{style:" + m_name + "}");
switch (m_lightingType) {
case LightingType::vertex:
m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_LIGHTING_VERTEX\n", false);
break;
case LightingType::fragment:
m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_LIGHTING_FRAGMENT\n", false);
break;
default:
break;
}
if (m_material.material) {
m_material.uniforms = m_material.material->injectOnProgram(*m_shaderProgram);
}
if (m_lightingType != LightingType::none) {
for (auto& light : _scene.lights()) {
auto uniforms = light->injectOnProgram(*m_shaderProgram);
if (uniforms) {
m_lights.emplace_back(light.get(), std::move(uniforms));
}
}
}
setupRasters(_scene.dataSources());
}
void Style::setMaterial(const std::shared_ptr<Material>& _material) {
m_material.material = _material;
m_material.uniforms.reset();
}
void Style::setLightingType(LightingType _type) {
m_lightingType = _type;
}
void Style::setupShaderUniforms(Scene& _scene) {
for (auto& uniformPair : m_styleUniforms) {
const auto& name = uniformPair.first;
auto& value = uniformPair.second;
if (value.is<std::string>()) {
std::shared_ptr<Texture> texture = nullptr;
std::string textureName = value.get<std::string>();
if (!_scene.texture(textureName, texture) || !texture) {
LOGN("Texture with texture name %s is not available to be sent as uniform",
textureName.c_str());
continue;
}
texture->update(RenderState::nextAvailableTextureUnit());
texture->bind(RenderState::currentTextureUnit());
m_shaderProgram->setUniformi(name, RenderState::currentTextureUnit());
} else {
if (value.is<bool>()) {
m_shaderProgram->setUniformi(name, value.get<bool>());
} else if(value.is<float>()) {
m_shaderProgram->setUniformf(name, value.get<float>());
} else if(value.is<glm::vec2>()) {
m_shaderProgram->setUniformf(name, value.get<glm::vec2>());
} else if(value.is<glm::vec3>()) {
m_shaderProgram->setUniformf(name, value.get<glm::vec3>());
} else if(value.is<glm::vec4>()) {
m_shaderProgram->setUniformf(name, value.get<glm::vec4>());
} else if (value.is<UniformArray1f>()) {
m_shaderProgram->setUniformf(name, value.get<UniformArray1f>());
} else if (value.is<UniformTextureArray>()) {
UniformTextureArray& textureUniformArray = value.get<UniformTextureArray>();
textureUniformArray.slots.clear();
for (const auto& textureName : textureUniformArray.names) {
std::shared_ptr<Texture> texture = nullptr;
if (!_scene.texture(textureName, texture) || !texture) {
LOGN("Texture with texture name %s is not available to be sent as uniform",
textureName.c_str());
continue;
}
texture->update(RenderState::nextAvailableTextureUnit());
texture->bind(RenderState::currentTextureUnit());
textureUniformArray.slots.push_back(RenderState::currentTextureUnit());
}
m_shaderProgram->setUniformi(name, textureUniformArray);
}
}
}
}
bool Style::hasRasters() const {
return m_rasterType == RasterType::custom ||
m_rasterType == RasterType::color ||
m_rasterType == RasterType::normal;
}
void Style::setupRasters(const fastmap<std::string, std::shared_ptr<DataSource>>& _dataSources) {
if (!hasRasters()) {
return;
}
if (m_rasterType == RasterType::normal) {
m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_RASTER_TEXTURE_NORMAL\n", false);
} else if (m_rasterType == RasterType::color) {
m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_RASTER_TEXTURE_COLOR\n", false);
}
int numRasterSource = 0;
for (const auto& dataSourcePair : _dataSources) {
if (dataSourcePair.second->isRaster()) {
numRasterSource++;
}
}
m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_NUM_RASTER_SOURCES "
+ std::to_string(numRasterSource) + "\n", false);
m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_MODEL_POSITION_BASE_ZOOM_VARYING\n", false);
std::string rasterBlock = stringFromFile("shaders/rasters.glsl", PathType::internal);
m_shaderProgram->addSourceBlock("raster", rasterBlock);
}
void Style::onBeginDrawFrame(const View& _view, Scene& _scene) {
// Reset the currently used texture unit to 0
RenderState::resetTextureUnit();
// Set time uniforms style's shader programs
m_shaderProgram->setUniformf(m_uTime, Tangram::frameTime());
m_shaderProgram->setUniformf(m_uDevicePixelRatio, m_pixelScale);
if (m_material.uniforms) {
m_material.material->setupProgram(*m_material.uniforms);
}
// Set up lights
for (const auto& light : m_lights) {
light.light->setupProgram(_view, *light.uniforms);
}
// Set Map Position
m_shaderProgram->setUniformf(m_uResolution, _view.getWidth(), _view.getHeight());
const auto& mapPos = _view.getPosition();
m_shaderProgram->setUniformf(m_uMapPosition, mapPos.x, mapPos.y, _view.getZoom());
m_shaderProgram->setUniformMatrix3f(m_uNormalMatrix, _view.getNormalMatrix());
m_shaderProgram->setUniformMatrix3f(m_uInverseNormalMatrix, _view.getInverseNormalMatrix());
m_shaderProgram->setUniformf(m_uMetersPerPixel, 1.0 / _view.pixelsPerMeter());
m_shaderProgram->setUniformMatrix4f(m_uView, _view.getViewMatrix());
m_shaderProgram->setUniformMatrix4f(m_uProj, _view.getProjectionMatrix());
setupShaderUniforms(_scene);
// Configure render state
switch (m_blend) {
case Blending::none:
RenderState::blending(GL_FALSE);
RenderState::blendingFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
RenderState::depthTest(GL_TRUE);
RenderState::depthWrite(GL_TRUE);
break;
case Blending::add:
RenderState::blending(GL_TRUE);
RenderState::blendingFunc(GL_ONE, GL_ONE);
RenderState::depthTest(GL_FALSE);
RenderState::depthWrite(GL_TRUE);
break;
case Blending::multiply:
RenderState::blending(GL_TRUE);
RenderState::blendingFunc(GL_ZERO, GL_SRC_COLOR);
RenderState::depthTest(GL_FALSE);
RenderState::depthWrite(GL_TRUE);
break;
case Blending::overlay:
RenderState::blending(GL_TRUE);
RenderState::blendingFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
RenderState::depthTest(GL_FALSE);
RenderState::depthWrite(GL_FALSE);
break;
case Blending::inlay:
// TODO: inlay does not behave correctly for labels because they don't have a z position
RenderState::blending(GL_TRUE);
RenderState::blendingFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
RenderState::depthTest(GL_TRUE);
RenderState::depthWrite(GL_FALSE);
break;
default:
break;
}
}
void Style::draw(const Tile& _tile) {
auto& styleMesh = _tile.getMesh(*this);
if (styleMesh) {
// TODO: bind all raster textures
// TODO: do for all tile textures
// FIXME: Currently only the first texture (which is the raster datasource's self texture)
UniformTextureArray textureIndexUniform;
UniformArray2f rasterSizeUniform;
if (_tile.textures().size() > 0) {
auto& texture = _tile.textures()[0];
if (texture) {
texture->update(RenderState::nextAvailableTextureUnit());
texture->bind(RenderState::currentTextureUnit());
textureIndexUniform.slots.push_back(RenderState::currentTextureUnit());
rasterSizeUniform.push_back({texture->getWidth(), texture->getHeight()});
m_shaderProgram->setUniformi(m_uRasters, textureIndexUniform);
m_shaderProgram->setUniformf(m_uRasterSizes, rasterSizeUniform);
}
}
m_shaderProgram->setUniformMatrix4f(m_uModel, _tile.getModelMatrix());
m_shaderProgram->setUniformf(m_uProxyDepth, _tile.isProxy() ? 1.f : 0.f);
m_shaderProgram->setUniformf(m_uTileOrigin,
_tile.getOrigin().x,
_tile.getOrigin().y,
_tile.getID().s,
_tile.getID().z);
if (!styleMesh->draw(*m_shaderProgram)) {
LOGN("Mesh built by style %s cannot be drawn", m_name.c_str());
}
for (int i = 0; i < textureIndexUniform.slots.size(); ++i) {
RenderState::releaseTextureUnit();
}
}
}
bool StyleBuilder::checkRule(const DrawRule& _rule) const {
uint32_t checkColor;
uint32_t checkOrder;
if (!_rule.get(StyleParamKey::color, checkColor)) {
if (!m_hasColorShaderBlock) {
return false;
}
}
if (!_rule.get(StyleParamKey::order, checkOrder)) {
return false;
}
return true;
}
void StyleBuilder::addFeature(const Feature& _feat, const DrawRule& _rule) {
if (!checkRule(_rule)) { return; }
switch (_feat.geometryType) {
case GeometryType::points:
for (auto& point : _feat.points) {
addPoint(point, _feat.props, _rule);
}
break;
case GeometryType::lines:
for (auto& line : _feat.lines) {
addLine(line, _feat.props, _rule);
}
break;
case GeometryType::polygons:
for (auto& polygon : _feat.polygons) {
addPolygon(polygon, _feat.props, _rule);
}
break;
default:
break;
}
}
StyleBuilder::StyleBuilder(const Style& _style) {
const auto& blocks = _style.getShaderProgram()->getSourceBlocks();
if (blocks.find("color") != blocks.end() ||
blocks.find("filter") != blocks.end()) {
m_hasColorShaderBlock = true;
}
}
void StyleBuilder::addPoint(const Point& _point, const Properties& _props, const DrawRule& _rule) {
// No-op by default
}
void StyleBuilder::addLine(const Line& _line, const Properties& _props, const DrawRule& _rule) {
// No-op by default
}
void StyleBuilder::addPolygon(const Polygon& _polygon, const Properties& _props, const DrawRule& _rule) {
// No-op by default
}
}
<commit_msg>Bind tile raster textures at draw tile<commit_after>#include "style.h"
#include "material.h"
#include "gl/renderState.h"
#include "gl/shaderProgram.h"
#include "gl/mesh.h"
#include "scene/light.h"
#include "scene/styleParam.h"
#include "scene/drawRule.h"
#include "scene/scene.h"
#include "scene/spriteAtlas.h"
#include "tile/tile.h"
#include "data/dataSource.h"
#include "view/view.h"
#include "tangram.h"
namespace Tangram {
Style::Style(std::string _name, Blending _blendMode, GLenum _drawMode) :
m_name(_name),
m_shaderProgram(std::make_unique<ShaderProgram>()),
m_blend(_blendMode),
m_drawMode(_drawMode) {
m_material.material = std::make_shared<Material>();
}
Style::~Style() {}
Style::LightHandle::LightHandle(Light* _light, std::unique_ptr<LightUniforms> _uniforms)
: light(_light), uniforms(std::move(_uniforms)){}
const std::vector<std::string>& Style::builtInStyleNames() {
static std::vector<std::string> builtInStyleNames{ "points", "lines", "polygons", "text", "debug", "debugtext" };
return builtInStyleNames;
}
void Style::build(const Scene& _scene) {
constructVertexLayout();
constructShaderProgram();
m_shaderProgram->setDescription("{style:" + m_name + "}");
switch (m_lightingType) {
case LightingType::vertex:
m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_LIGHTING_VERTEX\n", false);
break;
case LightingType::fragment:
m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_LIGHTING_FRAGMENT\n", false);
break;
default:
break;
}
if (m_material.material) {
m_material.uniforms = m_material.material->injectOnProgram(*m_shaderProgram);
}
if (m_lightingType != LightingType::none) {
for (auto& light : _scene.lights()) {
auto uniforms = light->injectOnProgram(*m_shaderProgram);
if (uniforms) {
m_lights.emplace_back(light.get(), std::move(uniforms));
}
}
}
setupRasters(_scene.dataSources());
}
void Style::setMaterial(const std::shared_ptr<Material>& _material) {
m_material.material = _material;
m_material.uniforms.reset();
}
void Style::setLightingType(LightingType _type) {
m_lightingType = _type;
}
void Style::setupShaderUniforms(Scene& _scene) {
for (auto& uniformPair : m_styleUniforms) {
const auto& name = uniformPair.first;
auto& value = uniformPair.second;
if (value.is<std::string>()) {
std::shared_ptr<Texture> texture = nullptr;
std::string textureName = value.get<std::string>();
if (!_scene.texture(textureName, texture) || !texture) {
LOGN("Texture with texture name %s is not available to be sent as uniform",
textureName.c_str());
continue;
}
texture->update(RenderState::nextAvailableTextureUnit());
texture->bind(RenderState::currentTextureUnit());
m_shaderProgram->setUniformi(name, RenderState::currentTextureUnit());
} else {
if (value.is<bool>()) {
m_shaderProgram->setUniformi(name, value.get<bool>());
} else if(value.is<float>()) {
m_shaderProgram->setUniformf(name, value.get<float>());
} else if(value.is<glm::vec2>()) {
m_shaderProgram->setUniformf(name, value.get<glm::vec2>());
} else if(value.is<glm::vec3>()) {
m_shaderProgram->setUniformf(name, value.get<glm::vec3>());
} else if(value.is<glm::vec4>()) {
m_shaderProgram->setUniformf(name, value.get<glm::vec4>());
} else if (value.is<UniformArray1f>()) {
m_shaderProgram->setUniformf(name, value.get<UniformArray1f>());
} else if (value.is<UniformTextureArray>()) {
UniformTextureArray& textureUniformArray = value.get<UniformTextureArray>();
textureUniformArray.slots.clear();
for (const auto& textureName : textureUniformArray.names) {
std::shared_ptr<Texture> texture = nullptr;
if (!_scene.texture(textureName, texture) || !texture) {
LOGN("Texture with texture name %s is not available to be sent as uniform",
textureName.c_str());
continue;
}
texture->update(RenderState::nextAvailableTextureUnit());
texture->bind(RenderState::currentTextureUnit());
textureUniformArray.slots.push_back(RenderState::currentTextureUnit());
}
m_shaderProgram->setUniformi(name, textureUniformArray);
}
}
}
}
bool Style::hasRasters() const {
return m_rasterType == RasterType::custom ||
m_rasterType == RasterType::color ||
m_rasterType == RasterType::normal;
}
void Style::setupRasters(const fastmap<std::string, std::shared_ptr<DataSource>>& _dataSources) {
if (!hasRasters()) {
return;
}
if (m_rasterType == RasterType::normal) {
m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_RASTER_TEXTURE_NORMAL\n", false);
} else if (m_rasterType == RasterType::color) {
m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_RASTER_TEXTURE_COLOR\n", false);
}
int numRasterSource = 0;
for (const auto& dataSourcePair : _dataSources) {
if (dataSourcePair.second->isRaster()) {
numRasterSource++;
}
}
m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_NUM_RASTER_SOURCES "
+ std::to_string(numRasterSource) + "\n", false);
m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_MODEL_POSITION_BASE_ZOOM_VARYING\n", false);
std::string rasterBlock = stringFromFile("shaders/rasters.glsl", PathType::internal);
m_shaderProgram->addSourceBlock("raster", rasterBlock);
}
void Style::onBeginDrawFrame(const View& _view, Scene& _scene) {
// Reset the currently used texture unit to 0
RenderState::resetTextureUnit();
// Set time uniforms style's shader programs
m_shaderProgram->setUniformf(m_uTime, Tangram::frameTime());
m_shaderProgram->setUniformf(m_uDevicePixelRatio, m_pixelScale);
if (m_material.uniforms) {
m_material.material->setupProgram(*m_material.uniforms);
}
// Set up lights
for (const auto& light : m_lights) {
light.light->setupProgram(_view, *light.uniforms);
}
// Set Map Position
m_shaderProgram->setUniformf(m_uResolution, _view.getWidth(), _view.getHeight());
const auto& mapPos = _view.getPosition();
m_shaderProgram->setUniformf(m_uMapPosition, mapPos.x, mapPos.y, _view.getZoom());
m_shaderProgram->setUniformMatrix3f(m_uNormalMatrix, _view.getNormalMatrix());
m_shaderProgram->setUniformMatrix3f(m_uInverseNormalMatrix, _view.getInverseNormalMatrix());
m_shaderProgram->setUniformf(m_uMetersPerPixel, 1.0 / _view.pixelsPerMeter());
m_shaderProgram->setUniformMatrix4f(m_uView, _view.getViewMatrix());
m_shaderProgram->setUniformMatrix4f(m_uProj, _view.getProjectionMatrix());
setupShaderUniforms(_scene);
// Configure render state
switch (m_blend) {
case Blending::none:
RenderState::blending(GL_FALSE);
RenderState::blendingFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
RenderState::depthTest(GL_TRUE);
RenderState::depthWrite(GL_TRUE);
break;
case Blending::add:
RenderState::blending(GL_TRUE);
RenderState::blendingFunc(GL_ONE, GL_ONE);
RenderState::depthTest(GL_FALSE);
RenderState::depthWrite(GL_TRUE);
break;
case Blending::multiply:
RenderState::blending(GL_TRUE);
RenderState::blendingFunc(GL_ZERO, GL_SRC_COLOR);
RenderState::depthTest(GL_FALSE);
RenderState::depthWrite(GL_TRUE);
break;
case Blending::overlay:
RenderState::blending(GL_TRUE);
RenderState::blendingFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
RenderState::depthTest(GL_FALSE);
RenderState::depthWrite(GL_FALSE);
break;
case Blending::inlay:
// TODO: inlay does not behave correctly for labels because they don't have a z position
RenderState::blending(GL_TRUE);
RenderState::blendingFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
RenderState::depthTest(GL_TRUE);
RenderState::depthWrite(GL_FALSE);
break;
default:
break;
}
}
void Style::draw(const Tile& _tile) {
auto& styleMesh = _tile.getMesh(*this);
if (styleMesh) {
// TODO: bind all raster textures
// TODO: do for all tile textures
// FIXME: Currently only the first texture (which is the raster datasource's self texture)
UniformTextureArray textureIndexUniform;
UniformArray2f rasterSizeUniform;
for (auto& texture : _tile.textures()) {
if (texture) {
texture->update(RenderState::nextAvailableTextureUnit());
texture->bind(RenderState::currentTextureUnit());
textureIndexUniform.slots.push_back(RenderState::currentTextureUnit());
rasterSizeUniform.push_back({texture->getWidth(), texture->getHeight()});
m_shaderProgram->setUniformi(m_uRasters, textureIndexUniform);
m_shaderProgram->setUniformf(m_uRasterSizes, rasterSizeUniform);
}
}
m_shaderProgram->setUniformMatrix4f(m_uModel, _tile.getModelMatrix());
m_shaderProgram->setUniformf(m_uProxyDepth, _tile.isProxy() ? 1.f : 0.f);
m_shaderProgram->setUniformf(m_uTileOrigin,
_tile.getOrigin().x,
_tile.getOrigin().y,
_tile.getID().s,
_tile.getID().z);
if (!styleMesh->draw(*m_shaderProgram)) {
LOGN("Mesh built by style %s cannot be drawn", m_name.c_str());
}
for (auto& texture : _tile.textures()) {
if (texture) {
RenderState::releaseTextureUnit();
}
}
}
}
bool StyleBuilder::checkRule(const DrawRule& _rule) const {
uint32_t checkColor;
uint32_t checkOrder;
if (!_rule.get(StyleParamKey::color, checkColor)) {
if (!m_hasColorShaderBlock) {
return false;
}
}
if (!_rule.get(StyleParamKey::order, checkOrder)) {
return false;
}
return true;
}
void StyleBuilder::addFeature(const Feature& _feat, const DrawRule& _rule) {
if (!checkRule(_rule)) { return; }
switch (_feat.geometryType) {
case GeometryType::points:
for (auto& point : _feat.points) {
addPoint(point, _feat.props, _rule);
}
break;
case GeometryType::lines:
for (auto& line : _feat.lines) {
addLine(line, _feat.props, _rule);
}
break;
case GeometryType::polygons:
for (auto& polygon : _feat.polygons) {
addPolygon(polygon, _feat.props, _rule);
}
break;
default:
break;
}
}
StyleBuilder::StyleBuilder(const Style& _style) {
const auto& blocks = _style.getShaderProgram()->getSourceBlocks();
if (blocks.find("color") != blocks.end() ||
blocks.find("filter") != blocks.end()) {
m_hasColorShaderBlock = true;
}
}
void StyleBuilder::addPoint(const Point& _point, const Properties& _props, const DrawRule& _rule) {
// No-op by default
}
void StyleBuilder::addLine(const Line& _line, const Properties& _props, const DrawRule& _rule) {
// No-op by default
}
void StyleBuilder::addPolygon(const Polygon& _polygon, const Properties& _props, const DrawRule& _rule) {
// No-op by default
}
}
<|endoftext|>
|
<commit_before>#ifndef UNITTEST11_UTILITY_TOSTRING_HPP
#define UNITTEST11_UTILITY_TOSTRING_HPP
#include <string>
#include <sstream>
namespace ut11
{
namespace Utility
{
template<typename V> struct ParseToString
{
inline std::string operator()(const V& value) const
{
std::stringstream stream;
stream << value;
return stream.str();
}
};
template<typename V> inline std::string ToString(const V& value) { return ParseToString<V>()(value); }
}
}
#endif // UNITTEST11_UTILITY_TOSTRING_HPP
<commit_msg>Added iterable ToString functionality<commit_after>#ifndef UNITTEST11_UTILITY_TOSTRING_HPP
#define UNITTEST11_UTILITY_TOSTRING_HPP
#include <string>
#include <sstream>
namespace ut11
{
namespace Utility
{
template<typename> struct VoidType { typedef void type; };
template<typename T, typename Sfinae = void> struct HasBeginFunction : std::false_type {};
template<typename T> struct HasBeginFunction<T, typename VoidType< decltype( std::declval<const T&>().begin() ) >::type> : std::true_type {};
template<typename T, typename Sfinae = void> struct HasEndFunction : std::false_type {};
template<typename T> struct HasEndFunction<T, typename VoidType< decltype( std::declval<const T&>().end() ) >::type> : std::true_type {};
template<bool First, typename A, typename B> struct IfElseTypes { typedef A type; };
template<typename A, typename B> struct IfElseTypes<false,A,B> { typedef B type; };
template<typename T> struct IsIterable
{
constexpr static bool value = std::is_base_of<std::true_type, HasBeginFunction<T> >::value && std::is_base_of<std::true_type, HasEndFunction<T> >::value;
};
template<typename V> struct ParseToString
{
inline std::string operator()(const V& value) const
{
std::stringstream stream;
stream << value;
return stream.str();
}
};
template<typename V> struct ParseIterableToString
{
inline std::string operator()(const V& value) const
{
std::stringstream stream;
stream << "{ ";
for(const auto& arg : value)
stream << (int)arg << " ";
stream << "}";
return stream.str();
}
};
template<> struct ParseIterableToString<std::string>
{
inline std::string operator()(const std::string& value) const
{
return value;
}
};
template<typename V> inline std::string ToString(const V& value)
{
return typename IfElseTypes< IsIterable<V>::value,
ParseIterableToString<V>,
ParseToString<V>
>::type()(value);
}
}
}
#endif // UNITTEST11_UTILITY_TOSTRING_HPP
<|endoftext|>
|
<commit_before>#include "style.h"
#include "scene/scene.h"
#include "scene/sceneLayer.h"
#include "scene/light.h"
#include "tile/mapTile.h"
#include "util/vboMesh.h"
#include "view/view.h"
#include "csscolorparser.hpp"
#include <sstream>
std::unordered_map<std::bitset<MAX_LAYERS>, StyleParamMap> Style::s_styleParamMapCache;
std::mutex Style::s_cacheMutex;
using namespace Tangram;
Style::Style(std::string _name, GLenum _drawMode) : m_name(_name), m_drawMode(_drawMode) {
}
Style::~Style() {
m_layers.clear();
}
uint32_t Style::parseColorProp(const std::string& _colorPropStr) {
uint32_t color = 0;
if (_colorPropStr.find(',') != std::string::npos) { // try to parse as comma-separated rgba components
std::istringstream stream(_colorPropStr);
std::string token;
unsigned char i = 0;
while (std::getline(stream, token, ',') && i < 4) {
color += (uint32_t(std::stod(token) * 255.)) << (8 * i++);
}
} else { // parse as css color or #hex-num
color = CSSColorParser::parse(_colorPropStr).getInt();
}
return color;
}
void Style::build(const std::vector<std::unique_ptr<Light>>& _lights) {
constructVertexLayout();
constructShaderProgram();
switch (m_lightingType) {
case LightingType::vertex:
m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_LIGHTING_VERTEX\n", false);
break;
case LightingType::fragment:
m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_LIGHTING_FRAGMENT\n", false);
break;
default:
break;
}
m_material->injectOnProgram(m_shaderProgram);
for (auto& light : _lights) {
light->injectOnProgram(m_shaderProgram);
}
}
void Style::setMaterial(const std::shared_ptr<Material>& _material) {
m_material = _material;
}
void Style::setLightingType(LightingType _type){
m_lightingType = _type;
}
void Style::addLayer(std::shared_ptr<SceneLayer> _layer) {
m_layers.push_back(std::move(_layer));
}
void Style::applyLayerFiltering(const Feature& _feature, const Context& _ctx, std::bitset<MAX_LAYERS>& _uniqueID,
StyleParamMap& _styleParamMapMix, std::shared_ptr<SceneLayer> _uberLayer) const {
std::vector<std::shared_ptr<SceneLayer>> sLayers;
sLayers.reserve(_uberLayer->getSublayers().size() + 1);
sLayers.push_back(_uberLayer);
auto sLayerItr = sLayers.begin();
//A BFS traversal of the SceneLayer graph
while (sLayerItr != sLayers.end()) {
auto sceneLyr = *sLayerItr;
if ( sceneLyr->getFilter()->eval(_feature, _ctx)) { // filter matches
_uniqueID.set(sceneLyr->getID());
if(s_styleParamMapCache.find(_uniqueID) != s_styleParamMapCache.end()) {
{
std::lock_guard<std::mutex> lock(s_cacheMutex);
_styleParamMapMix = s_styleParamMapCache.at(_uniqueID);
}
} else {
/* update StyleParam with subLayer parameters */
auto& layerStyleParamMap = sceneLyr->getStyleParamMap();
for(auto& styleParam : layerStyleParamMap) {
_styleParamMapMix[styleParam.first] = styleParam.second;
}
{
std::lock_guard<std::mutex> lock(s_cacheMutex);
s_styleParamMapCache.emplace(_uniqueID, _styleParamMapMix);
}
}
/* append sLayers with sublayers of this layer */
auto& ssLayers = sceneLyr->getSublayers();
sLayerItr = sLayers.insert(sLayers.end(), ssLayers.begin(), ssLayers.end());
} else {
sLayerItr++;
}
}
}
void Style::addData(TileData& _data, MapTile& _tile) {
onBeginBuildTile(_tile);
std::shared_ptr<VboMesh> mesh(newMesh());
Context ctx;
ctx["$zoom"] = new NumValue(_tile.getID().z);
for (auto& layer : _data.layers) {
// Skip any layers that this style doesn't have a rule for
auto it = m_layers.begin();
while (it != m_layers.end() && (*it)->getName() != layer.name) { ++it; }
if (it == m_layers.end()) { continue; }
// Loop over all features
for (auto& feature : layer.features) {
std::bitset<MAX_LAYERS> uniqueID(0);
StyleParamMap styleParamMapMix;
applyLayerFiltering(feature, ctx, uniqueID, styleParamMapMix, (*it));
if(uniqueID.any()) { // if a layer matched then uniqueID should be > 0
feature.props.numericProps["zoom"] = _tile.getID().z;
switch (feature.geometryType) {
case GeometryType::points:
// Build points
for (auto& point : feature.points) {
buildPoint(point, styleParamMapMix, feature.props, *mesh);
}
break;
case GeometryType::lines:
// Build lines
for (auto& line : feature.lines) {
buildLine(line, styleParamMapMix, feature.props, *mesh);
}
break;
case GeometryType::polygons:
// Build polygons
for (auto& polygon : feature.polygons) {
buildPolygon(polygon, styleParamMapMix, feature.props, *mesh);
}
break;
default:
break;
}
}
}
}
onEndBuildTile(_tile, mesh);
if (mesh->numVertices() == 0) {
mesh.reset();
} else {
mesh->compileVertexBuffer();
_tile.addGeometry(*this, mesh);
}
}
void Style::onBeginDrawFrame(const std::shared_ptr<View>& _view, const std::shared_ptr<Scene>& _scene) {
m_material->setupProgram(m_shaderProgram);
// Set up lights
for (const auto& light : _scene->getLights()) {
light->setupProgram(_view, m_shaderProgram);
}
m_shaderProgram->setUniformf("u_zoom", _view->getZoom());
}
void Style::onBeginBuildTile(MapTile& _tile) const {
// No-op by default
}
void Style::onEndBuildTile(MapTile& _tile, std::shared_ptr<VboMesh> _mesh) const {
// No-op by default
}
<commit_msg>Fix: Possible more async read writes to stylecache<commit_after>#include "style.h"
#include "scene/scene.h"
#include "scene/sceneLayer.h"
#include "scene/light.h"
#include "tile/mapTile.h"
#include "util/vboMesh.h"
#include "view/view.h"
#include "csscolorparser.hpp"
#include <sstream>
std::unordered_map<std::bitset<MAX_LAYERS>, StyleParamMap> Style::s_styleParamMapCache;
std::mutex Style::s_cacheMutex;
using namespace Tangram;
Style::Style(std::string _name, GLenum _drawMode) : m_name(_name), m_drawMode(_drawMode) {
}
Style::~Style() {
m_layers.clear();
}
uint32_t Style::parseColorProp(const std::string& _colorPropStr) {
uint32_t color = 0;
if (_colorPropStr.find(',') != std::string::npos) { // try to parse as comma-separated rgba components
std::istringstream stream(_colorPropStr);
std::string token;
unsigned char i = 0;
while (std::getline(stream, token, ',') && i < 4) {
color += (uint32_t(std::stod(token) * 255.)) << (8 * i++);
}
} else { // parse as css color or #hex-num
color = CSSColorParser::parse(_colorPropStr).getInt();
}
return color;
}
void Style::build(const std::vector<std::unique_ptr<Light>>& _lights) {
constructVertexLayout();
constructShaderProgram();
switch (m_lightingType) {
case LightingType::vertex:
m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_LIGHTING_VERTEX\n", false);
break;
case LightingType::fragment:
m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_LIGHTING_FRAGMENT\n", false);
break;
default:
break;
}
m_material->injectOnProgram(m_shaderProgram);
for (auto& light : _lights) {
light->injectOnProgram(m_shaderProgram);
}
}
void Style::setMaterial(const std::shared_ptr<Material>& _material) {
m_material = _material;
}
void Style::setLightingType(LightingType _type){
m_lightingType = _type;
}
void Style::addLayer(std::shared_ptr<SceneLayer> _layer) {
m_layers.push_back(std::move(_layer));
}
void Style::applyLayerFiltering(const Feature& _feature, const Context& _ctx, std::bitset<MAX_LAYERS>& _uniqueID,
StyleParamMap& _styleParamMapMix, std::shared_ptr<SceneLayer> _uberLayer) const {
std::vector<std::shared_ptr<SceneLayer>> sLayers;
sLayers.reserve(_uberLayer->getSublayers().size() + 1);
sLayers.push_back(_uberLayer);
auto sLayerItr = sLayers.begin();
//A BFS traversal of the SceneLayer graph
while (sLayerItr != sLayers.end()) {
auto sceneLyr = *sLayerItr;
if ( sceneLyr->getFilter()->eval(_feature, _ctx)) { // filter matches
_uniqueID.set(sceneLyr->getID());
{
std::lock_guard<std::mutex> lock(s_cacheMutex);
if(s_styleParamMapCache.find(_uniqueID) != s_styleParamMapCache.end()) {
_styleParamMapMix = s_styleParamMapCache.at(_uniqueID);
} else {
/* update StyleParam with subLayer parameters */
auto& layerStyleParamMap = sceneLyr->getStyleParamMap();
for(auto& styleParam : layerStyleParamMap) {
_styleParamMapMix[styleParam.first] = styleParam.second;
}
s_styleParamMapCache.emplace(_uniqueID, _styleParamMapMix);
}
}
/* append sLayers with sublayers of this layer */
auto& ssLayers = sceneLyr->getSublayers();
sLayerItr = sLayers.insert(sLayers.end(), ssLayers.begin(), ssLayers.end());
} else {
sLayerItr++;
}
}
}
void Style::addData(TileData& _data, MapTile& _tile) {
onBeginBuildTile(_tile);
std::shared_ptr<VboMesh> mesh(newMesh());
Context ctx;
ctx["$zoom"] = new NumValue(_tile.getID().z);
for (auto& layer : _data.layers) {
// Skip any layers that this style doesn't have a rule for
auto it = m_layers.begin();
while (it != m_layers.end() && (*it)->getName() != layer.name) { ++it; }
if (it == m_layers.end()) { continue; }
// Loop over all features
for (auto& feature : layer.features) {
std::bitset<MAX_LAYERS> uniqueID(0);
StyleParamMap styleParamMapMix;
applyLayerFiltering(feature, ctx, uniqueID, styleParamMapMix, (*it));
if(uniqueID.any()) { // if a layer matched then uniqueID should be > 0
feature.props.numericProps["zoom"] = _tile.getID().z;
switch (feature.geometryType) {
case GeometryType::points:
// Build points
for (auto& point : feature.points) {
buildPoint(point, styleParamMapMix, feature.props, *mesh);
}
break;
case GeometryType::lines:
// Build lines
for (auto& line : feature.lines) {
buildLine(line, styleParamMapMix, feature.props, *mesh);
}
break;
case GeometryType::polygons:
// Build polygons
for (auto& polygon : feature.polygons) {
buildPolygon(polygon, styleParamMapMix, feature.props, *mesh);
}
break;
default:
break;
}
}
}
}
onEndBuildTile(_tile, mesh);
if (mesh->numVertices() == 0) {
mesh.reset();
} else {
mesh->compileVertexBuffer();
_tile.addGeometry(*this, mesh);
}
}
void Style::onBeginDrawFrame(const std::shared_ptr<View>& _view, const std::shared_ptr<Scene>& _scene) {
m_material->setupProgram(m_shaderProgram);
// Set up lights
for (const auto& light : _scene->getLights()) {
light->setupProgram(_view, m_shaderProgram);
}
m_shaderProgram->setUniformf("u_zoom", _view->getZoom());
}
void Style::onBeginBuildTile(MapTile& _tile) const {
// No-op by default
}
void Style::onEndBuildTile(MapTile& _tile, std::shared_ptr<VboMesh> _mesh) const {
// No-op by default
}
<|endoftext|>
|
<commit_before>/*! \file */ //Copyright 2011-2016 Tyler Gilbert; All Rights Reserved
#ifndef KERNEL_HPP_
#define KERNEL_HPP_
#if !defined __link
#include <sos/sos.h>
#endif
#include <sos/dev/sys.h>
#include <sos/link.h>
#include "File.hpp"
namespace sys {
/*! \brief Sys Class
* \details This class allows access to system attributes and functions.
*/
class Sys : public File {
public:
#if defined __link
Sys(link_transport_mdriver_t * driver);
#else
Sys();
#endif
enum {
LAUNCH_OPTIONS_FLASH /*! Install in flash memory */ = APPFS_FLAG_IS_FLASH,
LAUNCH_OPTIONS_STARTUP /*! Run at startup (must be in flash) */ = APPFS_FLAG_IS_STARTUP,
LAUNCH_OPTIONS_ROOT /*! Run as root (if applicable) */ = APPFS_FLAG_IS_ROOT,
LAUNCH_OPTIONS_REPLACE /*! Delete if application exists */ = APPFS_FLAG_IS_REPLACE,
LAUNCH_OPTIONS_ORPHAN /*! Allow app to become an orphan */ = APPFS_FLAG_IS_ORPHAN,
LAUNCH_OPTIONS_UNIQUE_NAMES /*! Create a unique name on install */ = APPFS_FLAG_IS_UNIQUE,
LAUNCH_RAM_SIZE_DEFAULT = 0
};
/*! \details Launches a new application.
*
* @param path The path to the application
* @param exec_dest A pointer to a buffer where the execution path will be written (null if not needed)
* @param args The arguments to pass to the applications
* @param options For example: LAUNCH_OPTIONS_FLASH | LAUNCH_OPTIONS_STARTUP
* @param ram_size The amount of RAM that will be used by the app
* @param update_progress A callback to show the progress if the app needs to be installed (copied to flash/RAM)
* @param envp Not used (set to zero)
* @return The process ID of the new app if successful
*
* This method must be called locally in an app. It can't be executed over the link protocol.
*/
static int launch(const char * path,
char * exec_dest = 0,
const char * args = 0,
int options = 0, //run in RAM, discard on exit
int ram_size = LAUNCH_RAM_SIZE_DEFAULT,
int (*update_progress)(int, int) = 0,
char *const envp[] = 0
);
/*! \details Frees the RAM associated with the app without deleting the code from flash
* (should not be called when the app is currently running).
*
* @param path The path to the app (use \a exec_dest from launch())
* @param driver Used with link protocol only
* @return Zero on success
*
* This method can causes problems if not used correctly. The RAM associated with
* the app will be free and available for other applications. Any applications
* that are using the RAM must quit before the RAM can be reclaimed using reclaim_ram().
*
* \sa reclaim_ram()
*/
static int free_ram(const char * path, link_transport_mdriver_t * driver = 0);
/*! \details Reclaims RAM that was freed using free_ram().
*
* @param path The path to the app
* @param driver Used with link protocol only
* @return Zero on success
*
* \sa free_ram()
*/
static int reclaim_ram(const char * path, link_transport_mdriver_t * driver = 0);
static void assign_zero_sum32(void * data, int size);
static int verify_zero_sum32(void * data, int size);
#if !defined __link
/*! \details Gets the version (system/board version).
*
* @param version The destination string for the version
* @return Zero on success
*/
static int get_version(var::String & version);
/*! \details Gets the version (kernel version).
*
* @param version The destination string for the version
* @return Zero on success
*/
static int get_kernel_version(var::String & version);
/*! \details Puts the kernel in powerdown mode.
*
* @param timeout_msec The number of milliseconds before the
* device will power on (reset). If this isn't supported,
* the device will power off until reset by an external signal
*/
static void powerdown(int timeout_msec = 0);
/*! \details Puts the kernel in hibernate mode.
*
* @param timeout_msec The number of milliseconds before the
* device will wake up from hibernation. If this isn't supported,
* the device will stay in hibernation until woken up externally
*/
static int hibernate(int timeout_msec = 0);
/*! \details Executes a kernel request.
*
* @param req The request number
* @param arg Argument pointer
* @return The result of the execution of the request. (-1 if request is not available)
*
* The kernel request must
* be defined and implemented by the board support package.
*/
static int request(int req, void * arg = 0);
/*! \details Forces a reset of the device. */
static void reset();
/*! \details Loads the board configuration provided as
* part of the board support package.
*
* @param config A reference to the destination object
* @return Zero on success
*
* The object must be opened before calling this method.
*
* \sa open()
*/
int get_board_config(sos_board_config_t & config);
#endif
/*! \details Opens /dev/sys.
*
* @return Zero on success
*
*/
int open(){
return File::open("/dev/sys", RDWR);
}
using File::open;
/*! \details Loads the current system info.
*
* @param attr A reference to where the data should be stored
* @return Zero on success
*
* The object must be opened before calling this method.
*
* \sa open()
*
*/
int get_info(sys_info_t & attr);
int get_23_info(sys_23_info_t & attr);
int get_26_info(sys_26_info_t & attr);
/*! \details Loads the kernel's task attributes.
*
* @param attr A reference to the destination object
* @param task Which task to load (-1 to auto-increment)
* @return 1 if task is active, 0 if task is not being used, -1 is task is invalid
*
* The object must be opened before calling this method.
*
*/
int get_taskattr(sys_taskattr_t & attr, int task = -1);
inline int get_taskattr(sys_taskattr_t * attr, int task = -1){
return get_taskattr(*attr, task);
}
/*! \details Returns the current task that is accessed by get_taskattr().
*/
int current_task() const { return m_current_task; }
/*! \details Sets the current task to read using get_taskattr(). */
void set_current_task(int v){ m_current_task = v; }
/*! \details Loads the cloud kernel ID.
*
* @param id A reference to the destination data
* @return Less than zero if the operation failed
*
* The object must be opened before calling this method.
*
*/
int get_id(sys_id_t & id);
#if !defined __link
/*! \details Redirects the standard output to the file specified.
*
* @param fd The file descriptor where the standard output should be directed.
*
* The file desriptor should be open and ready for writing. For example,
* to redirect the standard output to the UART:
*
* \code
* #include <sapi/sys.hpp>
* #include <sapi/hal.hpp>
*
* Uart uart(0);
* uart.init(); //initializes uart using default settings (if available)
* Sys::redirect_stdout( uart.fileno() );
* printf("This will be written to UART0\n");
* \endcode
*
*
*/
static void redirect_stdout(int fd){
_impure_ptr->_stdout->_file = fd;
}
/*! \details Redirects the standard input from the specified file descriptor.
*
* @param fd The open and readable file descriptor to use for standard input
*
* See Sys::redirect_stdout() for an example.
*
*/
static void redirect_stdin(int fd){
_impure_ptr->_stdin->_file = fd;
}
/*! \details Redirects the standard error from the specified file descriptor.
*
* @param fd The open and writable file descriptor to use for standard input
*
* See Sys::redirect_stdout() for an example.
*
*/
static void redirect_stderr(int fd){
_impure_ptr->_stderr->_file = fd;
}
#endif
private:
int m_current_task;
};
}
#endif /* KERNEL_HPP_ */
<commit_msg>Added Sys::version()<commit_after>/*! \file */ //Copyright 2011-2016 Tyler Gilbert; All Rights Reserved
#ifndef KERNEL_HPP_
#define KERNEL_HPP_
#if !defined __link
#include <sos/sos.h>
#endif
#include <sos/dev/sys.h>
#include <sos/link.h>
#include "File.hpp"
namespace sys {
/*! \brief Sys Class
* \details This class allows access to system attributes and functions.
*/
class Sys : public File {
public:
#if defined __link
Sys(link_transport_mdriver_t * driver);
#else
Sys();
#endif
/*! \details Returns a c style string pointer
* to the API version.
*
* This version is 2.4.0
*
*/
static const char * version(){ return "2.4.0"; }
enum {
LAUNCH_OPTIONS_FLASH /*! Install in flash memory */ = APPFS_FLAG_IS_FLASH,
LAUNCH_OPTIONS_STARTUP /*! Run at startup (must be in flash) */ = APPFS_FLAG_IS_STARTUP,
LAUNCH_OPTIONS_ROOT /*! Run as root (if applicable) */ = APPFS_FLAG_IS_ROOT,
LAUNCH_OPTIONS_REPLACE /*! Delete if application exists */ = APPFS_FLAG_IS_REPLACE,
LAUNCH_OPTIONS_ORPHAN /*! Allow app to become an orphan */ = APPFS_FLAG_IS_ORPHAN,
LAUNCH_OPTIONS_UNIQUE_NAMES /*! Create a unique name on install */ = APPFS_FLAG_IS_UNIQUE,
LAUNCH_RAM_SIZE_DEFAULT = 0
};
/*! \details Launches a new application.
*
* @param path The path to the application
* @param exec_dest A pointer to a buffer where the execution path will be written (null if not needed)
* @param args The arguments to pass to the applications
* @param options For example: LAUNCH_OPTIONS_FLASH | LAUNCH_OPTIONS_STARTUP
* @param ram_size The amount of RAM that will be used by the app
* @param update_progress A callback to show the progress if the app needs to be installed (copied to flash/RAM)
* @param envp Not used (set to zero)
* @return The process ID of the new app if successful
*
* This method must be called locally in an app. It can't be executed over the link protocol.
*/
static int launch(const char * path,
char * exec_dest = 0,
const char * args = 0,
int options = 0, //run in RAM, discard on exit
int ram_size = LAUNCH_RAM_SIZE_DEFAULT,
int (*update_progress)(int, int) = 0,
char *const envp[] = 0
);
/*! \details Frees the RAM associated with the app without deleting the code from flash
* (should not be called when the app is currently running).
*
* @param path The path to the app (use \a exec_dest from launch())
* @param driver Used with link protocol only
* @return Zero on success
*
* This method can causes problems if not used correctly. The RAM associated with
* the app will be free and available for other applications. Any applications
* that are using the RAM must quit before the RAM can be reclaimed using reclaim_ram().
*
* \sa reclaim_ram()
*/
static int free_ram(const char * path, link_transport_mdriver_t * driver = 0);
/*! \details Reclaims RAM that was freed using free_ram().
*
* @param path The path to the app
* @param driver Used with link protocol only
* @return Zero on success
*
* \sa free_ram()
*/
static int reclaim_ram(const char * path, link_transport_mdriver_t * driver = 0);
static void assign_zero_sum32(void * data, int size);
static int verify_zero_sum32(void * data, int size);
#if !defined __link
/*! \details Gets the version (system/board version).
*
* @param version The destination string for the version
* @return Zero on success
*/
static int get_version(var::String & version);
/*! \details Gets the version (kernel version).
*
* @param version The destination string for the version
* @return Zero on success
*/
static int get_kernel_version(var::String & version);
/*! \details Puts the kernel in powerdown mode.
*
* @param timeout_msec The number of milliseconds before the
* device will power on (reset). If this isn't supported,
* the device will power off until reset by an external signal
*/
static void powerdown(int timeout_msec = 0);
/*! \details Puts the kernel in hibernate mode.
*
* @param timeout_msec The number of milliseconds before the
* device will wake up from hibernation. If this isn't supported,
* the device will stay in hibernation until woken up externally
*/
static int hibernate(int timeout_msec = 0);
/*! \details Executes a kernel request.
*
* @param req The request number
* @param arg Argument pointer
* @return The result of the execution of the request. (-1 if request is not available)
*
* The kernel request must
* be defined and implemented by the board support package.
*/
static int request(int req, void * arg = 0);
/*! \details Forces a reset of the device. */
static void reset();
/*! \details Loads the board configuration provided as
* part of the board support package.
*
* @param config A reference to the destination object
* @return Zero on success
*
* The object must be opened before calling this method.
*
* \sa open()
*/
int get_board_config(sos_board_config_t & config);
#endif
/*! \details Opens /dev/sys.
*
* @return Zero on success
*
*/
int open(){
return File::open("/dev/sys", RDWR);
}
using File::open;
/*! \details Loads the current system info.
*
* @param attr A reference to where the data should be stored
* @return Zero on success
*
* The object must be opened before calling this method.
*
* \sa open()
*
*/
int get_info(sys_info_t & attr);
int get_23_info(sys_23_info_t & attr);
int get_26_info(sys_26_info_t & attr);
/*! \details Loads the kernel's task attributes.
*
* @param attr A reference to the destination object
* @param task Which task to load (-1 to auto-increment)
* @return 1 if task is active, 0 if task is not being used, -1 is task is invalid
*
* The object must be opened before calling this method.
*
*/
int get_taskattr(sys_taskattr_t & attr, int task = -1);
inline int get_taskattr(sys_taskattr_t * attr, int task = -1){
return get_taskattr(*attr, task);
}
/*! \details Returns the current task that is accessed by get_taskattr().
*/
int current_task() const { return m_current_task; }
/*! \details Sets the current task to read using get_taskattr(). */
void set_current_task(int v){ m_current_task = v; }
/*! \details Loads the cloud kernel ID.
*
* @param id A reference to the destination data
* @return Less than zero if the operation failed
*
* The object must be opened before calling this method.
*
*/
int get_id(sys_id_t & id);
#if !defined __link
/*! \details Redirects the standard output to the file specified.
*
* @param fd The file descriptor where the standard output should be directed.
*
* The file desriptor should be open and ready for writing. For example,
* to redirect the standard output to the UART:
*
* \code
* #include <sapi/sys.hpp>
* #include <sapi/hal.hpp>
*
* Uart uart(0);
* uart.init(); //initializes uart using default settings (if available)
* Sys::redirect_stdout( uart.fileno() );
* printf("This will be written to UART0\n");
* \endcode
*
*
*/
static void redirect_stdout(int fd){
_impure_ptr->_stdout->_file = fd;
}
/*! \details Redirects the standard input from the specified file descriptor.
*
* @param fd The open and readable file descriptor to use for standard input
*
* See Sys::redirect_stdout() for an example.
*
*/
static void redirect_stdin(int fd){
_impure_ptr->_stdin->_file = fd;
}
/*! \details Redirects the standard error from the specified file descriptor.
*
* @param fd The open and writable file descriptor to use for standard input
*
* See Sys::redirect_stdout() for an example.
*
*/
static void redirect_stderr(int fd){
_impure_ptr->_stderr->_file = fd;
}
#endif
private:
int m_current_task;
};
}
#endif /* KERNEL_HPP_ */
<|endoftext|>
|
<commit_before>
#include <iostream>
#include <fbxsdk.h>
#include "common.h"
using namespace std;
const char* GetTypeName(EFbxType tid)
{
switch (tid)
{
case eFbxUndefined: return "eFbxUndefined";
case eFbxChar: return "eFbxChar";
case eFbxUChar: return "eFbxUChar";
case eFbxShort: return "eFbxShort";
case eFbxUShort: return "eFbxUShort";
case eFbxUInt: return "eFbxUInt";
case eFbxLongLong: return "eFbxLongLong";
case eFbxULongLong: return "eFbxULongLong";
case eFbxHalfFloat: return "eFbxHalfFloat";
case eFbxBool: return "eFbxBool";
case eFbxInt: return "eFbxInt";
case eFbxFloat: return "eFbxFloat";
case eFbxDouble: return "eFbxDouble";
case eFbxDouble2: return "eFbxDouble2";
case eFbxDouble3: return "eFbxDouble3";
case eFbxDouble4: return "eFbxDouble4";
case eFbxDouble4x4: return "eFbxDouble4x4";
case eFbxEnum: return "eFbxEnum";
case eFbxString: return "eFbxString";
case eFbxTime: return "eFbxTime";
case eFbxReference: return "eFbxReference";
case eFbxBlob: return "eFbxBlob";
case eFbxDistance: return "eFbxDistance";
case eFbxDateTime: return "eFbxDateTime";
case eFbxTypeCount: return "eFbxTypeCount";
}
return "<<unknown>>";
}
void PrintProperty(FbxProperty* prop, bool indent)
{
const char * prefix = indent ? " " : " ";
cout << prefix << "Name = " << prop->GetName() << endl;
FbxDataType type = prop->GetPropertyDataType();
cout << prefix << "Type = " << type.GetName() << " (" << GetTypeName(type.GetType()) << ")" << endl;
cout << prefix << "HierName = " << prop->GetHierarchicalName() << endl;
cout << prefix << "Label = " << prop->GetLabel() << endl;
char n[1024];
int i;
for (i = 0; i < 1024; i++)
{
n[i] = 0;
}
char ch;
unsigned char uch;
unsigned int ui;
short sh;
unsigned short ush;
long long ll;
unsigned long long ull;
bool b;
float f;
double d;
FbxString fstr;
FbxDouble2 v2;
FbxDouble3 v3;
FbxDouble4 v4;
std::string s;
std::stringstream ss;
bool printValue = true;
switch (type.GetType())
{
case eFbxUndefined:
printValue = false;
break;
case eFbxChar:
ch = prop->Get<char>();
sprintf(n, "%i ('%c')", (int)ch, ch);
break;
case eFbxUChar:
uch = prop->Get<unsigned char>();
sprintf(n, "%i ('%c')", (unsigned int)uch, uch);
break;
case eFbxShort:
sh = prop->Get<short>();
sprintf(n, "%i", (int)sh);
break;
case eFbxUShort:
ush = prop->Get<unsigned short>();
sprintf(n, "%ui", (unsigned int)ush);
break;
case eFbxUInt:
ui = prop->Get<unsigned int>();
sprintf(n, "%ui", ui);
break;
case eFbxLongLong:
ll = prop->Get<long long>();
sprintf(n, "%lli", ll);
break;
case eFbxULongLong:
ull = prop->Get<unsigned long long>();
sprintf(n, "%llu", ull);
break;
case eFbxHalfFloat:
printValue = false;
break;
case eFbxBool:
b = prop->Get<bool>();
if (b)
sprintf(n, "true");
else
sprintf(n, "false");
break;
case eFbxInt:
i = prop->Get<int>();
sprintf(n, "%i", i);
break;
case eFbxFloat:
f = prop->Get<float>();
sprintf(n, "%f", f);
break;
case eFbxDouble:
d = prop->Get<double>();
sprintf(n, "%lf", d);
break;
case eFbxDouble2:
v2 = prop->Get<FbxDouble2>();
sprintf(n, "%lf, %lf", v2[0], v2[1]);
break;
case eFbxDouble3:
v3 = prop->Get<FbxDouble3>();
sprintf(n, "%lf, %lf, %lf", v3[0], v3[1], v3[1]);
break;
case eFbxDouble4:
v4 = prop->Get<FbxDouble4>();
sprintf(n, "%lf, %lf, %lf, %lf", v4[0], v4[1], v4[1], v4[1]);
break;
case eFbxDouble4x4:
case eFbxEnum:
printValue = false;
break;
case eFbxString:
fstr = prop->Get<FbxString>();
sprintf(n, "%s", fstr.Buffer());
s = (fstr.Buffer());
s = quote(s.c_str());
sprintf(n, "%s", s.c_str());
break;
case eFbxTime:
ss << prop->Get<FbxTime>();
sprintf(n, "%s", ss.str().c_str());
break;
case eFbxReference:
// FbxObject* obj;
// obj = prop->Get<FbxObject*>();
// cout << prefix << ".Value = " << obj->GetRuntimeClassId().GetName() << ", uid=" << obj->GetUniqueID() << endl;
// break;
case eFbxBlob:
case eFbxDistance:
case eFbxDateTime:
case eFbxTypeCount:
printValue = false;
break;
}
if (printValue)
{
cout << prefix << "Value = " << n << endl;
}
cout << prefix << "SrcObjectCount = " << prop->GetSrcObjectCount() << endl;
for (i = 0; i < prop->GetSrcObjectCount(); i++)
{
FbxObject* srcObj = prop->GetSrcObject(i);
cout << prefix << " #" << i << " ";
PrintObjectID(srcObj);
cout << endl;
}
cout << prefix << "DstObjectCount = " << prop->GetDstObjectCount() << endl;
for (i = 0; i < prop->GetDstObjectCount(); i++)
{
FbxObject* dstObj = prop->GetDstObject(i);
cout << prefix << " #" << i << " ";
PrintObjectID(dstObj);
cout << endl;
}
cout << prefix << "SrcPropertyCount = " << prop->GetSrcPropertyCount() << endl;
for (i = 0; i < prop->GetSrcPropertyCount(); i++)
{
FbxProperty prop2 = prop->GetSrcProperty(i);
cout << prefix << " #" << i << " ";
PrintPropertyID(&prop2);
cout << endl;
}
cout << prefix << "DstPropertyCount = " << prop->GetDstPropertyCount() << endl;
for (i = 0; i < prop->GetDstPropertyCount(); i++)
{
FbxProperty prop2 = prop->GetDstProperty(i);
cout << prefix << " #" << i << " ";
PrintPropertyID(&prop2);
cout << endl;
}
}<commit_msg>Fix how vectors are printed.<commit_after>
#include <iostream>
#include <fbxsdk.h>
#include "common.h"
using namespace std;
const char* GetTypeName(EFbxType tid)
{
switch (tid)
{
case eFbxUndefined: return "eFbxUndefined";
case eFbxChar: return "eFbxChar";
case eFbxUChar: return "eFbxUChar";
case eFbxShort: return "eFbxShort";
case eFbxUShort: return "eFbxUShort";
case eFbxUInt: return "eFbxUInt";
case eFbxLongLong: return "eFbxLongLong";
case eFbxULongLong: return "eFbxULongLong";
case eFbxHalfFloat: return "eFbxHalfFloat";
case eFbxBool: return "eFbxBool";
case eFbxInt: return "eFbxInt";
case eFbxFloat: return "eFbxFloat";
case eFbxDouble: return "eFbxDouble";
case eFbxDouble2: return "eFbxDouble2";
case eFbxDouble3: return "eFbxDouble3";
case eFbxDouble4: return "eFbxDouble4";
case eFbxDouble4x4: return "eFbxDouble4x4";
case eFbxEnum: return "eFbxEnum";
case eFbxString: return "eFbxString";
case eFbxTime: return "eFbxTime";
case eFbxReference: return "eFbxReference";
case eFbxBlob: return "eFbxBlob";
case eFbxDistance: return "eFbxDistance";
case eFbxDateTime: return "eFbxDateTime";
case eFbxTypeCount: return "eFbxTypeCount";
}
return "<<unknown>>";
}
void PrintProperty(FbxProperty* prop, bool indent)
{
const char * prefix = indent ? " " : " ";
cout << prefix << "Name = " << prop->GetName() << endl;
FbxDataType type = prop->GetPropertyDataType();
cout << prefix << "Type = " << type.GetName() << " (" << GetTypeName(type.GetType()) << ")" << endl;
cout << prefix << "HierName = " << prop->GetHierarchicalName() << endl;
cout << prefix << "Label = " << prop->GetLabel() << endl;
char n[1024];
int i;
for (i = 0; i < 1024; i++)
{
n[i] = 0;
}
char ch;
unsigned char uch;
unsigned int ui;
short sh;
unsigned short ush;
long long ll;
unsigned long long ull;
bool b;
float f;
double d;
FbxString fstr;
FbxDouble2 v2;
FbxDouble3 v3;
FbxDouble4 v4;
std::string s;
std::stringstream ss;
bool printValue = true;
switch (type.GetType())
{
case eFbxUndefined:
printValue = false;
break;
case eFbxChar:
ch = prop->Get<char>();
sprintf(n, "%i ('%c')", (int)ch, ch);
break;
case eFbxUChar:
uch = prop->Get<unsigned char>();
sprintf(n, "%i ('%c')", (unsigned int)uch, uch);
break;
case eFbxShort:
sh = prop->Get<short>();
sprintf(n, "%i", (int)sh);
break;
case eFbxUShort:
ush = prop->Get<unsigned short>();
sprintf(n, "%ui", (unsigned int)ush);
break;
case eFbxUInt:
ui = prop->Get<unsigned int>();
sprintf(n, "%ui", ui);
break;
case eFbxLongLong:
ll = prop->Get<long long>();
sprintf(n, "%lli", ll);
break;
case eFbxULongLong:
ull = prop->Get<unsigned long long>();
sprintf(n, "%llu", ull);
break;
case eFbxHalfFloat:
printValue = false;
break;
case eFbxBool:
b = prop->Get<bool>();
if (b)
sprintf(n, "true");
else
sprintf(n, "false");
break;
case eFbxInt:
i = prop->Get<int>();
sprintf(n, "%i", i);
break;
case eFbxFloat:
f = prop->Get<float>();
sprintf(n, "%f", f);
break;
case eFbxDouble:
d = prop->Get<double>();
sprintf(n, "%lf", d);
break;
case eFbxDouble2:
v2 = prop->Get<FbxDouble2>();
sprintf(n, "%lf, %lf", v2[0], v2[1]);
break;
case eFbxDouble3:
v3 = prop->Get<FbxDouble3>();
sprintf(n, "%lf, %lf, %lf", v3[0], v3[1], v3[2]);
break;
case eFbxDouble4:
v4 = prop->Get<FbxDouble4>();
sprintf(n, "%lf, %lf, %lf, %lf", v4[0], v4[1], v4[2], v4[3]);
break;
case eFbxDouble4x4:
case eFbxEnum:
printValue = false;
break;
case eFbxString:
fstr = prop->Get<FbxString>();
sprintf(n, "%s", fstr.Buffer());
s = (fstr.Buffer());
s = quote(s.c_str());
sprintf(n, "%s", s.c_str());
break;
case eFbxTime:
ss << prop->Get<FbxTime>();
sprintf(n, "%s", ss.str().c_str());
break;
case eFbxReference:
// FbxObject* obj;
// obj = prop->Get<FbxObject*>();
// cout << prefix << ".Value = " << obj->GetRuntimeClassId().GetName() << ", uid=" << obj->GetUniqueID() << endl;
// break;
case eFbxBlob:
case eFbxDistance:
case eFbxDateTime:
case eFbxTypeCount:
printValue = false;
break;
}
if (printValue)
{
cout << prefix << "Value = " << n << endl;
}
cout << prefix << "SrcObjectCount = " << prop->GetSrcObjectCount() << endl;
for (i = 0; i < prop->GetSrcObjectCount(); i++)
{
FbxObject* srcObj = prop->GetSrcObject(i);
cout << prefix << " #" << i << " ";
PrintObjectID(srcObj);
cout << endl;
}
cout << prefix << "DstObjectCount = " << prop->GetDstObjectCount() << endl;
for (i = 0; i < prop->GetDstObjectCount(); i++)
{
FbxObject* dstObj = prop->GetDstObject(i);
cout << prefix << " #" << i << " ";
PrintObjectID(dstObj);
cout << endl;
}
cout << prefix << "SrcPropertyCount = " << prop->GetSrcPropertyCount() << endl;
for (i = 0; i < prop->GetSrcPropertyCount(); i++)
{
FbxProperty prop2 = prop->GetSrcProperty(i);
cout << prefix << " #" << i << " ";
PrintPropertyID(&prop2);
cout << endl;
}
cout << prefix << "DstPropertyCount = " << prop->GetDstPropertyCount() << endl;
for (i = 0; i < prop->GetDstPropertyCount(); i++)
{
FbxProperty prop2 = prop->GetDstProperty(i);
cout << prefix << " #" << i << " ";
PrintPropertyID(&prop2);
cout << endl;
}
}<|endoftext|>
|
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "OpenSimSceneWidget.h"
#include "Entity.h"
#include "EC_Highlight.h"
#include <QFileDialog>
namespace WorldBuilding
{
OpenSimSceneWidget::OpenSimSceneWidget() :
UiProxyWidget(new QWidget(), Qt::Dialog),
exporting_(false)
{
internal_widget_ = widget();
setupUi(internal_widget_);
setWindowTitle(internal_widget_->windowTitle());
label_caps_fail->hide();
label_export_help->setText("Click 'Start Exporting' and start selecting inworld object");
connect(button_toggle_tracking, SIGNAL(clicked()), SLOT(ToggleExporting()));
connect(button_reset_tracking, SIGNAL(clicked()), SLOT(ResetExporting()));
connect(button_export, SIGNAL(clicked()), SLOT(PublishFile()));
connect(button_create_scene, SIGNAL(clicked()), SLOT(ExportSelected()));
connect(button_browse_scene, SIGNAL(clicked()), SLOT(SelectScene()));
connect(this, SIGNAL(Visible(bool)), SLOT(VisibilityChange(bool)));
selected_entities_.clear();
}
OpenSimSceneWidget::~OpenSimSceneWidget()
{
}
void OpenSimSceneWidget::ShowFunctionality(bool enabled)
{
label_caps_fail->setVisible(!enabled);
label_title->setEnabled(enabled);
label_title_2->setEnabled(enabled);
label_export_help->setEnabled(enabled);
lineedit_scene->setEnabled(enabled);
entity_list->setEnabled(enabled);
radioButton_av_pos->setEnabled(enabled);
radioButton_original_pos->setEnabled(enabled);
button_browse_scene->setEnabled(enabled);
button_export->setEnabled(enabled);
button_toggle_tracking->setEnabled(enabled);
button_reset_tracking->setEnabled(enabled);
button_create_scene->setEnabled(enabled);
}
void OpenSimSceneWidget::VisibilityChange(bool visible)
{
if (!visible && exporting_)
button_toggle_tracking->click();
else
ShowAllHightLights(visible);
}
void OpenSimSceneWidget::AddEntityToList(QList<Scene::Entity *> entity_list)
{
QString ent_id;
foreach(Scene::Entity *entity, entity_list)
{
ent_id = QString::number(entity->GetId());
AddEntityToList(ent_id, entity);
}
}
bool OpenSimSceneWidget::AddEntityToList(const QString &ent_id, Scene::Entity *entity)
{
if (IsEntityListed(ent_id))
return false;
entity_list->addItem(ent_id);
selected_entities_.append(entity);
AddHighLight(entity);
return true;
}
void OpenSimSceneWidget::RemoveEntityFromList(QList<Scene::Entity *> entity_list)
{
QString ent_id;
foreach(Scene::Entity *entity, entity_list)
{
ent_id = QString::number(entity->GetId());
RemoveEntityFromList(ent_id, entity);
}
}
void OpenSimSceneWidget::RemoveEntityFromList(const QString &ent_id, Scene::Entity *entity)
{
QList<QListWidgetItem*> found_items = entity_list->findItems(ent_id, Qt::MatchExactly);
foreach(QListWidgetItem *item, found_items)
{
QListWidgetItem *removed = entity_list->takeItem(entity_list->row(item));
SAFE_DELETE(removed);
}
RemoveHightLight(entity);
selected_entities_.removeAll(entity);
}
bool OpenSimSceneWidget::IsEntityListed(const QString &ent_id)
{
QList<QListWidgetItem*> found_items = entity_list->findItems(ent_id, Qt::MatchExactly);
if (found_items.count() > 0)
return true;
else
return false;
}
void OpenSimSceneWidget::ToggleExporting()
{
exporting_ = !exporting_;
ShowAllHightLights(exporting_);
if (exporting_)
{
label_export_help->setText("Click 'Stop Exporting' when your set is selected");
button_toggle_tracking->setText("Stop exporting");
}
else
{
label_export_help->setText("Click 'Export to file' to store the set you have selected \nor add more objects with 'Start Exporting'");
button_toggle_tracking->setText("Start exporting");
}
}
void OpenSimSceneWidget::ResetExporting()
{
foreach(Scene::Entity *entity, selected_entities_)
RemoveHightLight(entity);
selected_entities_.clear();
entity_list->clear();
if (exporting_)
button_toggle_tracking->click();
}
void OpenSimSceneWidget::ShowAllHightLights(bool visible)
{
foreach(Scene::Entity *entity, selected_entities_)
{
EC_Highlight *light = entity->GetComponent<EC_Highlight>().get();
if (!light)
continue;
if (visible)
light->Show();
else
light->Hide();
}
}
void OpenSimSceneWidget::AddHighLight(Scene::Entity *entity)
{
if (!entity)
return;
EC_Highlight *light = dynamic_cast<EC_Highlight*>(entity->GetOrCreateComponent(EC_Highlight::TypeNameStatic(), AttributeChange::LocalOnly, false).get());
if (light)
light->Show();
}
void OpenSimSceneWidget::RemoveHightLight(Scene::Entity *entity)
{
if (!entity)
return;
entity->RemoveComponent(EC_Highlight::TypeNameStatic(), AttributeChange::LocalOnly);
}
void OpenSimSceneWidget::SelectScene()
{
QString filename = QFileDialog::getOpenFileName(internal_widget_, "Select scene", "./", "*.xml");
if (!filename.isEmpty())
lineedit_scene->setText(filename);
}
void OpenSimSceneWidget::ExportSelected()
{
if (selected_entities_.empty())
{
QMessageBox::information(internal_widget_, "No Export Entities", "There are no entities to export. Press 'Start Tracking' and click on objects to select them.");
return;
}
QString filename = QFileDialog::getSaveFileName(internal_widget_, "Select export file", "./", "*.xml");
if (filename.isEmpty())
return;
emit ExportToFile(filename, selected_entities_);
}
void OpenSimSceneWidget::PublishFile()
{
if (lineedit_scene->text().isEmpty())
{
QMessageBox::information(internal_widget_, "Import File", "Import scene file is empty, please select one first.");
return;
}
emit PublishFromFile(lineedit_scene->text(), radioButton_av_pos->isChecked());
}
}<commit_msg>OpenSim Scene Service linux build fixes part 4<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "OpenSimSceneWidget.h"
#include "Entity.h"
#include "EC_Highlight.h"
#include <QFileDialog>
#include <QMessageBox>
namespace WorldBuilding
{
OpenSimSceneWidget::OpenSimSceneWidget() :
UiProxyWidget(new QWidget(), Qt::Dialog),
exporting_(false)
{
internal_widget_ = widget();
setupUi(internal_widget_);
setWindowTitle(internal_widget_->windowTitle());
label_caps_fail->hide();
label_export_help->setText("Click 'Start Exporting' and start selecting inworld object");
connect(button_toggle_tracking, SIGNAL(clicked()), SLOT(ToggleExporting()));
connect(button_reset_tracking, SIGNAL(clicked()), SLOT(ResetExporting()));
connect(button_export, SIGNAL(clicked()), SLOT(PublishFile()));
connect(button_create_scene, SIGNAL(clicked()), SLOT(ExportSelected()));
connect(button_browse_scene, SIGNAL(clicked()), SLOT(SelectScene()));
connect(this, SIGNAL(Visible(bool)), SLOT(VisibilityChange(bool)));
selected_entities_.clear();
}
OpenSimSceneWidget::~OpenSimSceneWidget()
{
}
void OpenSimSceneWidget::ShowFunctionality(bool enabled)
{
label_caps_fail->setVisible(!enabled);
label_title->setEnabled(enabled);
label_title_2->setEnabled(enabled);
label_export_help->setEnabled(enabled);
lineedit_scene->setEnabled(enabled);
entity_list->setEnabled(enabled);
radioButton_av_pos->setEnabled(enabled);
radioButton_original_pos->setEnabled(enabled);
button_browse_scene->setEnabled(enabled);
button_export->setEnabled(enabled);
button_toggle_tracking->setEnabled(enabled);
button_reset_tracking->setEnabled(enabled);
button_create_scene->setEnabled(enabled);
}
void OpenSimSceneWidget::VisibilityChange(bool visible)
{
if (!visible && exporting_)
button_toggle_tracking->click();
else
ShowAllHightLights(visible);
}
void OpenSimSceneWidget::AddEntityToList(QList<Scene::Entity *> entity_list)
{
QString ent_id;
foreach(Scene::Entity *entity, entity_list)
{
ent_id = QString::number(entity->GetId());
AddEntityToList(ent_id, entity);
}
}
bool OpenSimSceneWidget::AddEntityToList(const QString &ent_id, Scene::Entity *entity)
{
if (IsEntityListed(ent_id))
return false;
entity_list->addItem(ent_id);
selected_entities_.append(entity);
AddHighLight(entity);
return true;
}
void OpenSimSceneWidget::RemoveEntityFromList(QList<Scene::Entity *> entity_list)
{
QString ent_id;
foreach(Scene::Entity *entity, entity_list)
{
ent_id = QString::number(entity->GetId());
RemoveEntityFromList(ent_id, entity);
}
}
void OpenSimSceneWidget::RemoveEntityFromList(const QString &ent_id, Scene::Entity *entity)
{
QList<QListWidgetItem*> found_items = entity_list->findItems(ent_id, Qt::MatchExactly);
foreach(QListWidgetItem *item, found_items)
{
QListWidgetItem *removed = entity_list->takeItem(entity_list->row(item));
SAFE_DELETE(removed);
}
RemoveHightLight(entity);
selected_entities_.removeAll(entity);
}
bool OpenSimSceneWidget::IsEntityListed(const QString &ent_id)
{
QList<QListWidgetItem*> found_items = entity_list->findItems(ent_id, Qt::MatchExactly);
if (found_items.count() > 0)
return true;
else
return false;
}
void OpenSimSceneWidget::ToggleExporting()
{
exporting_ = !exporting_;
ShowAllHightLights(exporting_);
if (exporting_)
{
label_export_help->setText("Click 'Stop Exporting' when your set is selected");
button_toggle_tracking->setText("Stop exporting");
}
else
{
label_export_help->setText("Click 'Export to file' to store the set you have selected \nor add more objects with 'Start Exporting'");
button_toggle_tracking->setText("Start exporting");
}
}
void OpenSimSceneWidget::ResetExporting()
{
foreach(Scene::Entity *entity, selected_entities_)
RemoveHightLight(entity);
selected_entities_.clear();
entity_list->clear();
if (exporting_)
button_toggle_tracking->click();
}
void OpenSimSceneWidget::ShowAllHightLights(bool visible)
{
foreach(Scene::Entity *entity, selected_entities_)
{
EC_Highlight *light = entity->GetComponent<EC_Highlight>().get();
if (!light)
continue;
if (visible)
light->Show();
else
light->Hide();
}
}
void OpenSimSceneWidget::AddHighLight(Scene::Entity *entity)
{
if (!entity)
return;
EC_Highlight *light = dynamic_cast<EC_Highlight*>(entity->GetOrCreateComponent(EC_Highlight::TypeNameStatic(), AttributeChange::LocalOnly, false).get());
if (light)
light->Show();
}
void OpenSimSceneWidget::RemoveHightLight(Scene::Entity *entity)
{
if (!entity)
return;
entity->RemoveComponent(EC_Highlight::TypeNameStatic(), AttributeChange::LocalOnly);
}
void OpenSimSceneWidget::SelectScene()
{
QString filename = QFileDialog::getOpenFileName(internal_widget_, "Select scene", "./", "*.xml");
if (!filename.isEmpty())
lineedit_scene->setText(filename);
}
void OpenSimSceneWidget::ExportSelected()
{
if (selected_entities_.empty())
{
QMessageBox::information(internal_widget_, "No Export Entities", "There are no entities to export. Press 'Start Tracking' and click on objects to select them.");
return;
}
QString filename = QFileDialog::getSaveFileName(internal_widget_, "Select export file", "./", "*.xml");
if (filename.isEmpty())
return;
emit ExportToFile(filename, selected_entities_);
}
void OpenSimSceneWidget::PublishFile()
{
if (lineedit_scene->text().isEmpty())
{
QMessageBox::information(internal_widget_, "Import File", "Import scene file is empty, please select one first.");
return;
}
emit PublishFromFile(lineedit_scene->text(), radioButton_av_pos->isChecked());
}
}<|endoftext|>
|
<commit_before>#include "SimpleField.hpp"
#include <stdexcept>
#include <iostream>
#include <string>
SimpleField::SimpleField(std::vector<std::string> strs)
{
for (int i = 0; i < 32; ++i) {
for(int j = 0; j < 32; ++j) {
mat[i][j] = strs[i][j] == '1';
ok[i][j] = false;
is_first = true;
}
}
}
SimpleField::SimpleField(const bool mat[32][32], const bool ok[32][32] = {}, const decltype(((Field *)nullptr)->get_history()) & src = {}) : Field(src)
{
for (int i = 0; i < 32; ++i) {
for (int j = 0; j < 32; ++j) {
this -> mat[i][j] = mat[i][j];
this -> ok[i][j] = ok[i][j];
}
}
}
bool SimpleField::at(int x, int y) const
{
return mat[y][x];
}
bool SimpleField::appliable(std::shared_ptr<Stone> s, int x, int y, int reverse, int angle) const
{
bool adjf = false;
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
if (y + i < 0 || 32 <= y + i || x + j < 0 || 32 <= x + j) {
if (s->at(j, i, reverse, angle)) {
return false;
}
continue;
}
if (mat[y + i][x + j] && s->at(j, i, reverse, angle)) {
return false;
}
adjf |= s->at(j, i, reverse, angle) && (is_first || ok[y + i][x + j]);
}
}
return adjf;
}
void SimpleField::apply(std::shared_ptr<Stone> s, int x, int y, int reverse, int angle)
{
Field::apply(s, x, y, reverse, angle);
#ifdef _DEBUG
if(!appliable(s, x, y, reverse, angle)) {
throw std::runtime_error("cannot apply");
}
#endif
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
if ( x + j < 0 || 32 <= x + j || y + i < 0 || 32 <= y + i) continue;
mat[y + i][x + j] |= s -> at(j, i, reverse, angle);
if (!s->at(j, i, reverse, angle)) continue;
for (int k = 0; k < 4; ++k) {
static const int ofs[4][2] = {
{0, 1},
{1, 0},
{-1, 0},
{0, -1}
};
int nx = x + j + ofs[k][0];
int ny = y + i + ofs[k][1];
if (nx < 0 || 32 <= nx || ny < 0 || 32 <= ny) {
continue;
}
ok[ny][nx] |= true;
}
}
}
value = -1;
is_first |= true;
}
std::unique_ptr<Field> SimpleField::clone() const
{
auto ptr = std::unique_ptr<Field>(new SimpleField(mat, ok, history));
return std::move(ptr);
}
const int SimpleField::tx[] = { 1, 0, -1, 0 };
const int SimpleField::ty[] = { 0, -1, 0, 1 };
int SimpleField::h(){
if (value == -1){
int count = 0;
for (int i = 0; i < 8; i++){
for (int j = 0; j < 8; j++){
if (mat[i][j] == 0)continue;
bool f = false;
for (int t = 0; t < 4; t++){
int nx = j + tx[t];
int ny = i + ty[t];
if (nx < 0 || 32 <= nx || ny < 0 || 32 <= ny) {
continue;
}
if (mat[nx][ny] == 0){
f = true;
}
}
if (f)count++;
}
}
value = count;
}
return value;
}
<commit_msg>間違えました<commit_after>#include "SimpleField.hpp"
#include <stdexcept>
#include <iostream>
#include <string>
SimpleField::SimpleField(std::vector<std::string> strs)
{
for (int i = 0; i < 32; ++i) {
for(int j = 0; j < 32; ++j) {
mat[i][j] = strs[i][j] == '1';
ok[i][j] = false;
}
}
is_first = true;
}
SimpleField::SimpleField(const bool mat[32][32], const bool ok[32][32] = {}, const decltype(((Field *)nullptr)->get_history()) & src = {}) : Field(src)
{
for (int i = 0; i < 32; ++i) {
for (int j = 0; j < 32; ++j) {
this -> mat[i][j] = mat[i][j];
this -> ok[i][j] = ok[i][j];
}
}
is_first = src.size() == 0;
}
bool SimpleField::at(int x, int y) const
{
return mat[y][x];
}
bool SimpleField::appliable(std::shared_ptr<Stone> s, int x, int y, int reverse, int angle) const
{
bool adjf = false;
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
if (y + i < 0 || 32 <= y + i || x + j < 0 || 32 <= x + j) {
if (s->at(j, i, reverse, angle)) {
return false;
}
continue;
}
if (mat[y + i][x + j] && s->at(j, i, reverse, angle)) {
return false;
}
adjf |= s->at(j, i, reverse, angle) && (is_first || ok[y + i][x + j]);
}
}
return adjf;
}
void SimpleField::apply(std::shared_ptr<Stone> s, int x, int y, int reverse, int angle)
{
Field::apply(s, x, y, reverse, angle);
#ifdef _DEBUG
if(!appliable(s, x, y, reverse, angle)) {
throw std::runtime_error("cannot apply");
}
#endif
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
if ( x + j < 0 || 32 <= x + j || y + i < 0 || 32 <= y + i) continue;
mat[y + i][x + j] |= s -> at(j, i, reverse, angle);
if (!s->at(j, i, reverse, angle)) continue;
for (int k = 0; k < 4; ++k) {
static const int ofs[4][2] = {
{0, 1},
{1, 0},
{-1, 0},
{0, -1}
};
int nx = x + j + ofs[k][0];
int ny = y + i + ofs[k][1];
if (nx < 0 || 32 <= nx || ny < 0 || 32 <= ny) {
continue;
}
ok[ny][nx] |= true;
}
}
}
value = -1;
is_first &= false;
}
std::unique_ptr<Field> SimpleField::clone() const
{
auto ptr = std::unique_ptr<Field>(new SimpleField(mat, ok, history));
return std::move(ptr);
}
const int SimpleField::tx[] = { 1, 0, -1, 0 };
const int SimpleField::ty[] = { 0, -1, 0, 1 };
int SimpleField::h(){
if (value == -1){
int count = 0;
for (int i = 0; i < 8; i++){
for (int j = 0; j < 8; j++){
if (mat[i][j] == 0)continue;
bool f = false;
for (int t = 0; t < 4; t++){
int nx = j + tx[t];
int ny = i + ty[t];
if (nx < 0 || 32 <= nx || ny < 0 || 32 <= ny) {
continue;
}
if (mat[nx][ny] == 0){
f = true;
}
}
if (f)count++;
}
}
value = count;
}
return value;
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) DataStax, Inc.
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 "session_base.hpp"
#include "cluster_config.hpp"
#include "metrics.hpp"
#include "prepare_all_handler.hpp"
#include "random.hpp"
#include "request_handler.hpp"
namespace cass {
SessionBase::SessionBase()
: state_(SESSION_STATE_CLOSED) {
uv_mutex_init(&mutex_);
}
SessionBase::~SessionBase() {
uv_mutex_destroy(&mutex_);
}
void SessionBase::connect(const Config& config,
const String& keyspace,
const Future::Ptr& future) {
ScopedMutex l(&mutex_);
if (state_ != SESSION_STATE_CLOSED) {
future->set_error(CASS_ERROR_LIB_UNABLE_TO_CONNECT,
"Already connecting, closing, or connected");
return;
}
if (!event_loop_) {
int rc = 0;
event_loop_.reset(Memory::allocate<EventLoop>());
rc = event_loop_->init("Session/Control Connection");
if (rc != 0) {
future->set_error(CASS_ERROR_LIB_UNABLE_TO_INIT,
"Unable to initialize cluster event loop");
return;
}
rc = event_loop_->run();
if (rc != 0) {
future->set_error(CASS_ERROR_LIB_UNABLE_TO_INIT,
"Unable to run cluster event loop");
return;
}
}
config_ = config.new_instance();
connect_keyspace_ = keyspace;
connect_future_ = future;
state_ = SESSION_STATE_CONNECTING;
if (config.use_randomized_contact_points()) {
random_.reset(Memory::allocate<Random>());
} else {
random_.reset();
}
metrics_.reset(Memory::allocate<Metrics>(config.thread_count_io() + 1));
cluster_connector_.reset(
Memory::allocate<ClusterConnector>(config_.contact_points(),
config_.protocol_version(),
bind_callback(&SessionBase::on_initialize, this)));
cluster_connector_
->with_listener(this)
->with_settings(ClusterSettings(config_))
->with_random(random_.get())
->with_metrics(metrics_.get())
->connect(event_loop_.get());
}
void SessionBase::close(const Future::Ptr& future) {
ScopedMutex l(&mutex_);
if (state_ == SESSION_STATE_CLOSED ||
state_ == SESSION_STATE_CLOSING) {
future->set();
return;
}
state_ = SESSION_STATE_CLOSING;
close_future_ = future;
cluster_->close();
}
void SessionBase::join() {
if (event_loop_) {
event_loop_->close_handles();
event_loop_->join();
}
}
void SessionBase::notify_connected() {
ScopedMutex l(&mutex_);
if (state_ == SESSION_STATE_CONNECTING) {
state_ = SESSION_STATE_CONNECTED;
connect_future_->set();
connect_future_.reset();
}
}
void SessionBase::notify_connect_failed(CassError code, const String& message) {
ScopedMutex l(&mutex_);
if (state_ == SESSION_STATE_CONNECTING) {
state_ = SESSION_STATE_CLOSED;
connect_future_->set_error(code, message);
connect_future_.reset();
}
}
void SessionBase::notify_closed() {
ScopedMutex l(&mutex_);
if (state_ == SESSION_STATE_CLOSING) {
state_ = SESSION_STATE_CLOSED;
close_future_->set();
close_future_.reset();
l.unlock();
}
}
void SessionBase::on_connect(const Host::Ptr& connected_host,
int protocol_version,
const HostMap& hosts,
const TokenMap::Ptr& token_map) {
notify_connected();
}
void SessionBase::on_connect_failed(CassError code, const String& message) {
notify_connect_failed(code, message);
}
void SessionBase::on_close(Cluster* cluster) {
notify_closed();
}
void SessionBase::on_initialize(ClusterConnector* connector) {
if (connector->is_ok()) {
cluster_ = connector->release_cluster();
on_connect(cluster_->connected_host(),
cluster_->protocol_version(),
cluster_->hosts(),
cluster_->token_map());
} else {
assert(!connector->is_canceled() && "Cluster connection process canceled");
switch (connector->error_code()) {
case ClusterConnector::CLUSTER_ERROR_INVALID_PROTOCOL:
on_connect_failed(CASS_ERROR_LIB_UNABLE_TO_DETERMINE_PROTOCOL,
connector->error_message());
break;
case ClusterConnector::CLUSTER_ERROR_SSL_ERROR:
on_connect_failed(connector->ssl_error_code(),
connector->error_message());
break;
case ClusterConnector::CLUSTER_ERROR_AUTH_ERROR:
on_connect_failed(CASS_ERROR_SERVER_BAD_CREDENTIALS,
connector->error_message());
break;
case ClusterConnector::CLUSTER_ERROR_NO_HOSTS_AVILABLE:
on_connect_failed(CASS_ERROR_LIB_NO_HOSTS_AVAILABLE,
connector->error_message());
break;
default:
// This shouldn't happen, but let's handle it
on_connect_failed(CASS_ERROR_LIB_UNABLE_TO_CONNECT,
connector->error_message());
break;
}
}
}
} // namespace cass
<commit_msg>CPP-650 - Fix session close error when already closed (#150)<commit_after>/*
Copyright (c) DataStax, Inc.
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 "session_base.hpp"
#include "cluster_config.hpp"
#include "metrics.hpp"
#include "prepare_all_handler.hpp"
#include "random.hpp"
#include "request_handler.hpp"
namespace cass {
SessionBase::SessionBase()
: state_(SESSION_STATE_CLOSED) {
uv_mutex_init(&mutex_);
}
SessionBase::~SessionBase() {
uv_mutex_destroy(&mutex_);
}
void SessionBase::connect(const Config& config,
const String& keyspace,
const Future::Ptr& future) {
ScopedMutex l(&mutex_);
if (state_ != SESSION_STATE_CLOSED) {
future->set_error(CASS_ERROR_LIB_UNABLE_TO_CONNECT,
"Already connecting, closing, or connected");
return;
}
if (!event_loop_) {
int rc = 0;
event_loop_.reset(Memory::allocate<EventLoop>());
rc = event_loop_->init("Session/Control Connection");
if (rc != 0) {
future->set_error(CASS_ERROR_LIB_UNABLE_TO_INIT,
"Unable to initialize cluster event loop");
return;
}
rc = event_loop_->run();
if (rc != 0) {
future->set_error(CASS_ERROR_LIB_UNABLE_TO_INIT,
"Unable to run cluster event loop");
return;
}
}
config_ = config.new_instance();
connect_keyspace_ = keyspace;
connect_future_ = future;
state_ = SESSION_STATE_CONNECTING;
if (config.use_randomized_contact_points()) {
random_.reset(Memory::allocate<Random>());
} else {
random_.reset();
}
metrics_.reset(Memory::allocate<Metrics>(config.thread_count_io() + 1));
cluster_connector_.reset(
Memory::allocate<ClusterConnector>(config_.contact_points(),
config_.protocol_version(),
bind_callback(&SessionBase::on_initialize, this)));
cluster_connector_
->with_listener(this)
->with_settings(ClusterSettings(config_))
->with_random(random_.get())
->with_metrics(metrics_.get())
->connect(event_loop_.get());
}
void SessionBase::close(const Future::Ptr& future) {
ScopedMutex l(&mutex_);
if (state_ == SESSION_STATE_CLOSED ||
state_ == SESSION_STATE_CLOSING) {
future->set_error(CASS_ERROR_LIB_UNABLE_TO_CLOSE,
"Already closing or closed");
return;
}
state_ = SESSION_STATE_CLOSING;
close_future_ = future;
cluster_->close();
}
void SessionBase::join() {
if (event_loop_) {
event_loop_->close_handles();
event_loop_->join();
}
}
void SessionBase::notify_connected() {
ScopedMutex l(&mutex_);
if (state_ == SESSION_STATE_CONNECTING) {
state_ = SESSION_STATE_CONNECTED;
connect_future_->set();
connect_future_.reset();
}
}
void SessionBase::notify_connect_failed(CassError code, const String& message) {
ScopedMutex l(&mutex_);
if (state_ == SESSION_STATE_CONNECTING) {
state_ = SESSION_STATE_CLOSED;
connect_future_->set_error(code, message);
connect_future_.reset();
}
}
void SessionBase::notify_closed() {
ScopedMutex l(&mutex_);
if (state_ == SESSION_STATE_CLOSING) {
state_ = SESSION_STATE_CLOSED;
close_future_->set();
close_future_.reset();
l.unlock();
}
}
void SessionBase::on_connect(const Host::Ptr& connected_host,
int protocol_version,
const HostMap& hosts,
const TokenMap::Ptr& token_map) {
notify_connected();
}
void SessionBase::on_connect_failed(CassError code, const String& message) {
notify_connect_failed(code, message);
}
void SessionBase::on_close(Cluster* cluster) {
notify_closed();
}
void SessionBase::on_initialize(ClusterConnector* connector) {
if (connector->is_ok()) {
cluster_ = connector->release_cluster();
on_connect(cluster_->connected_host(),
cluster_->protocol_version(),
cluster_->hosts(),
cluster_->token_map());
} else {
assert(!connector->is_canceled() && "Cluster connection process canceled");
switch (connector->error_code()) {
case ClusterConnector::CLUSTER_ERROR_INVALID_PROTOCOL:
on_connect_failed(CASS_ERROR_LIB_UNABLE_TO_DETERMINE_PROTOCOL,
connector->error_message());
break;
case ClusterConnector::CLUSTER_ERROR_SSL_ERROR:
on_connect_failed(connector->ssl_error_code(),
connector->error_message());
break;
case ClusterConnector::CLUSTER_ERROR_AUTH_ERROR:
on_connect_failed(CASS_ERROR_SERVER_BAD_CREDENTIALS,
connector->error_message());
break;
case ClusterConnector::CLUSTER_ERROR_NO_HOSTS_AVILABLE:
on_connect_failed(CASS_ERROR_LIB_NO_HOSTS_AVAILABLE,
connector->error_message());
break;
default:
// This shouldn't happen, but let's handle it
on_connect_failed(CASS_ERROR_LIB_UNABLE_TO_CONNECT,
connector->error_message());
break;
}
}
}
} // namespace cass
<|endoftext|>
|
<commit_before>/** \brief Adds local MARC data from a database to MARC title records w/o local data.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
*
* \copyright 2020 Universitätsbibliothek Tübingen. 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 <cstdio>
#include <cstdlib>
#include "Compiler.h"
#include "DbConnection.h"
#include "MARC.h"
#include "StringUtil.h"
#include "UBTools.h"
#include "util.h"
namespace {
[[noreturn]] void Usage() {
::Usage("input_marc_title_data output_marc_title_data");
}
// Appends local data for each record, for which local data will be found in our database.
// The local data is store in a format where the contents of each field is preceeded by a 4-character
// hex string indicating the length of the immediately following field contents.
// Multiple local fields may occur per record.
void AddLocalData(DbConnection * const db_connection, MARC::Reader * const reader, MARC::Writer * const writer) {
unsigned total_record_count(0), added_count(0);
while (auto record = reader->read()) {
++total_record_count;
db_connection->queryOrDie("SELECT local_fields FROM local_data WHERE ppn = "
+ db_connection->escapeAndQuoteString(record.getControlNumber()));
auto result_set(db_connection->getLastResultSet());
if (not result_set.empty()) {
const auto row(result_set.getNextRow());
const auto local_fields_blob(row["local_fields"]);
size_t processed_size(0);
do {
// Convert the 4 character hex string to size of the following field contents:
const size_t field_contents_size(StringUtil::ToUnsignedLong(local_fields_blob.substr(processed_size, 4), 16));
processed_size += 4;
if (unlikely(processed_size + field_contents_size > local_fields_blob.size()))
LOG_ERROR("Inconsitent blob length for record with PPN " + record.getControlNumber());
record.appendField("LOK", local_fields_blob.substr(processed_size, field_contents_size));
processed_size += field_contents_size;
} while (processed_size < local_fields_blob.size());
}
writer->write(record);
}
LOG_INFO("Added local data to " + std::to_string(added_count) + " out of " + std::to_string(total_record_count) + " record(s).");
}
} // unnamed namespace
int Main(int argc, char *argv[]) {
if (argc != 3)
Usage();
auto marc_reader(MARC::Reader::Factory(argv[1]));
auto marc_writer(MARC::Writer::Factory(argv[2]));
DbConnection db_connection(UBTools::GetTuelibPath() + "local_data.sq3", DbConnection::READONLY);
AddLocalData(&db_connection, marc_reader.get(), marc_writer.get());
return EXIT_SUCCESS;
}
<commit_msg>More typo fixes.<commit_after>/** \brief Adds local MARC data from a database to MARC title records w/o local data.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
*
* \copyright 2020 Universitätsbibliothek Tübingen. 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 <cstdio>
#include <cstdlib>
#include "Compiler.h"
#include "DbConnection.h"
#include "MARC.h"
#include "StringUtil.h"
#include "UBTools.h"
#include "util.h"
namespace {
[[noreturn]] void Usage() {
::Usage("input_marc_title_data output_marc_title_data");
}
// Appends local data for each record, for which local data will be found in our database.
// The local data is store in a format where the contents of each field is preceeded by a 4-character
// hex string indicating the length of the immediately following field contents.
// Multiple local fields may occur per record.
void AddLocalData(DbConnection * const db_connection, MARC::Reader * const reader, MARC::Writer * const writer) {
unsigned total_record_count(0), added_count(0);
while (auto record = reader->read()) {
++total_record_count;
db_connection->queryOrDie("SELECT local_fields FROM local_data WHERE ppn = "
+ db_connection->escapeAndQuoteString(record.getControlNumber()));
auto result_set(db_connection->getLastResultSet());
if (not result_set.empty()) {
const auto row(result_set.getNextRow());
const auto local_fields_blob(row["local_fields"]);
size_t processed_size(0);
do {
// Convert the 4 character hex string to the size of the following field contents:
const size_t field_contents_size(StringUtil::ToUnsignedLong(local_fields_blob.substr(processed_size, 4), 16));
processed_size += 4;
if (unlikely(processed_size + field_contents_size > local_fields_blob.size()))
LOG_ERROR("Inconsistent blob length for record with PPN " + record.getControlNumber());
record.appendField("LOK", local_fields_blob.substr(processed_size, field_contents_size));
processed_size += field_contents_size;
} while (processed_size < local_fields_blob.size());
}
writer->write(record);
}
LOG_INFO("Added local data to " + std::to_string(added_count) + " out of " + std::to_string(total_record_count) + " record(s).");
}
} // unnamed namespace
int Main(int argc, char *argv[]) {
if (argc != 3)
Usage();
auto marc_reader(MARC::Reader::Factory(argv[1]));
auto marc_writer(MARC::Writer::Factory(argv[2]));
DbConnection db_connection(UBTools::GetTuelibPath() + "local_data.sq3", DbConnection::READONLY);
AddLocalData(&db_connection, marc_reader.get(), marc_writer.get());
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include <cap/default_inspector.h>
#include <cap/supercapacitor.h>
namespace cap {
template <int dim>
std::map<std::string, double>
extract_data_from_super_capacitor(EnergyStorageDevice *device)
{
std::map<std::string, double> data;
auto super_capacitor = dynamic_cast<SuperCapacitor<dim>*>(device);
if (super_capacitor) {
// get some values from the post processor
auto post_processor = super_capacitor->get_post_processor();
double value;
for (std::string const & key : {
"anode_electrode_interfacial_surface_area",
"anode_electrode_mass_of_active_material",
"cathode_electrode_interfacial_surface_area",
"cathode_electrode_mass_of_active_material",
})
{
post_processor->get(key, value);
data[key] = value;
}
// get other values from the property tree
boost::property_tree::ptree const* ptree =
super_capacitor->get_property_tree();
data["geometric_area"] =
ptree->get<double>("geometry.geometric_area");
data["anode_electrode_thickness"] =
ptree->get<double>("geometry.anode_electrode_thickness");
data["cathode_electrode_thickness"] =
ptree->get<double>("geometry.cathode_electrode_thickness");
// TODO
for (std::string const & electrode : {"anode", "cathode"})
{
std::string tmp =
ptree->get<std::string>("material_properties."+electrode+".matrix_phase");
data[electrode+"_electrode_double_layer_capacitance"] =
ptree->get<double>("material_properties."+tmp+".differential_capacitance");
}
} else {
throw std::runtime_error("Downcasting failed");
}
return data;
}
void DefaultInspector::inspect(EnergyStorageDevice *device)
{
if (dynamic_cast<SuperCapacitor<2>*>(device)) {
_data = extract_data_from_super_capacitor<2>(device);
} else if (dynamic_cast<SuperCapacitor<3>*>(device)) {
_data = extract_data_from_super_capacitor<3>(device);
} else {
// do nothing
}
}
std::map<std::string, double> DefaultInspector::get_data()
{
return _data;
}
} // end namespace cap
<commit_msg>removed outdated TODO comment<commit_after>#include <cap/default_inspector.h>
#include <cap/supercapacitor.h>
namespace cap {
template <int dim>
std::map<std::string, double>
extract_data_from_super_capacitor(EnergyStorageDevice *device)
{
std::map<std::string, double> data;
auto super_capacitor = dynamic_cast<SuperCapacitor<dim>*>(device);
if (super_capacitor) {
// get some values from the post processor
auto post_processor = super_capacitor->get_post_processor();
double value;
for (std::string const & key : {
"anode_electrode_interfacial_surface_area",
"anode_electrode_mass_of_active_material",
"cathode_electrode_interfacial_surface_area",
"cathode_electrode_mass_of_active_material",
})
{
post_processor->get(key, value);
data[key] = value;
}
// get other values from the property tree
boost::property_tree::ptree const* ptree =
super_capacitor->get_property_tree();
data["geometric_area"] =
ptree->get<double>("geometry.geometric_area");
data["anode_electrode_thickness"] =
ptree->get<double>("geometry.anode_electrode_thickness");
data["cathode_electrode_thickness"] =
ptree->get<double>("geometry.cathode_electrode_thickness");
for (std::string const & electrode : {"anode", "cathode"})
{
std::string tmp =
ptree->get<std::string>("material_properties."+electrode+".matrix_phase");
data[electrode+"_electrode_double_layer_capacitance"] =
ptree->get<double>("material_properties."+tmp+".differential_capacitance");
}
} else {
throw std::runtime_error("Downcasting failed");
}
return data;
}
void DefaultInspector::inspect(EnergyStorageDevice *device)
{
if (dynamic_cast<SuperCapacitor<2>*>(device)) {
_data = extract_data_from_super_capacitor<2>(device);
} else if (dynamic_cast<SuperCapacitor<3>*>(device)) {
_data = extract_data_from_super_capacitor<3>(device);
} else {
// do nothing
}
}
std::map<std::string, double> DefaultInspector::get_data()
{
return _data;
}
} // end namespace cap
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* 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.
*/
#pragma once
#include <graphene/chain/protocol/operations.hpp>
#include <graphene/db/generic_index.hpp>
#include <boost/multi_index/composite_key.hpp>
namespace graphene { namespace chain {
class database;
/**
* @class account_statistics_object
* @ingroup object
* @ingroup implementation
*
* This object contains regularly updated statistical data about an account. It is provided for the purpose of
* separating the account data that changes frequently from the account data that is mostly static, which will
* minimize the amount of data that must be backed up as part of the undo history everytime a transfer is made.
*/
class account_statistics_object : public graphene::db::abstract_object<account_statistics_object>
{
public:
static const uint8_t space_id = implementation_ids;
static const uint8_t type_id = impl_account_statistics_object_type;
account_id_type owner;
/**
* Keep the most recent operation as a root pointer to a linked list of the transaction history.
*/
account_transaction_history_id_type most_recent_op;
/**
* When calculating votes it is necessary to know how much is stored in orders (and thus unavailable for
* transfers). Rather than maintaining an index of [asset,owner,order_id] we will simply maintain the running
* total here and update it every time an order is created or modified.
*/
share_type total_core_in_orders;
/**
* Tracks the total fees paid by this account for the purpose of calculating bulk discounts.
*/
share_type lifetime_fees_paid;
/**
* Tracks the fees paid by this account which have not been disseminated to the various parties that receive
* them yet (registrar, referrer, lifetime referrer, network, etc). This is used as an optimization to avoid
* doing massive amounts of uint128 arithmetic on each and every operation.
*
* These fees will be paid out as vesting cash-back, and this counter will reset during the maintenance
* interval.
*/
share_type pending_fees;
/**
* Same as @ref pending_fees, except these fees will be paid out as pre-vested cash-back (immediately
* available for withdrawal) rather than requiring the normal vesting period.
*/
share_type pending_vested_fees;
/// @brief Split up and pay out @ref pending_fees and @ref pending_vested_fees
void process_fees(const account_object& a, database& d) const;
/**
* Core fees are paid into the account_statistics_object by this method
*/
void pay_fee( share_type core_fee, share_type cashback_vesting_threshold );
};
/**
* @brief Tracks the balance of a single account/asset pair
* @ingroup object
*
* This object is indexed on owner and asset_type so that black swan
* events in asset_type can be processed quickly.
*/
class account_balance_object : public abstract_object<account_balance_object>
{
public:
static const uint8_t space_id = implementation_ids;
static const uint8_t type_id = impl_account_balance_object_type;
account_id_type owner;
asset_id_type asset_type;
share_type balance;
asset get_balance()const { return asset(balance, asset_type); }
void adjust_balance(const asset& delta);
};
/**
* @brief This class represents an account on the object graph
* @ingroup object
* @ingroup protocol
*
* Accounts are the primary unit of authority on the graphene system. Users must have an account in order to use
* assets, trade in the markets, vote for committee_members, etc.
*/
class account_object : public graphene::db::abstract_object<account_object>
{
public:
static const uint8_t space_id = protocol_ids;
static const uint8_t type_id = account_object_type;
/**
* The time at which this account's membership expires.
* If set to any time in the past, the account is a basic account.
* If set to time_point_sec::maximum(), the account is a lifetime member.
* If set to any time not in the past less than time_point_sec::maximum(), the account is an annual member.
*
* See @ref is_lifetime_member, @ref is_basic_account, @ref is_annual_member, and @ref is_member
*/
time_point_sec membership_expiration_date;
///The account that paid the fee to register this account. Receives a percentage of referral rewards.
account_id_type registrar;
/// The account credited as referring this account. Receives a percentage of referral rewards.
account_id_type referrer;
/// The lifetime member at the top of the referral tree. Receives a percentage of referral rewards.
account_id_type lifetime_referrer;
/// Percentage of fee which should go to network.
uint16_t network_fee_percentage = GRAPHENE_DEFAULT_NETWORK_PERCENT_OF_FEE;
/// Percentage of fee which should go to lifetime referrer.
uint16_t lifetime_referrer_fee_percentage = 0;
/// Percentage of referral rewards (leftover fee after paying network and lifetime referrer) which should go
/// to referrer. The remainder of referral rewards goes to the registrar.
uint16_t referrer_rewards_percentage = 0;
/// The account's name. This name must be unique among all account names on the graph. May not be empty.
string name;
/**
* The owner authority represents absolute control over the account. Usually the keys in this authority will
* be kept in cold storage, as they should not be needed very often and compromise of these keys constitutes
* complete and irrevocable loss of the account. Generally the only time the owner authority is required is to
* update the active authority.
*/
authority owner;
/// The owner authority contains the hot keys of the account. This authority has control over nearly all
/// operations the account may perform.
authority active;
typedef account_options options_type;
account_options options;
/// The reference implementation records the account's statistics in a separate object. This field contains the
/// ID of that object.
account_statistics_id_type statistics;
/**
* This is a set of all accounts which have 'whitelisted' this account. Whitelisting is only used in core
* validation for the purpose of authorizing accounts to hold and transact in whitelisted assets. This
* account cannot update this set, except by transferring ownership of the account, which will clear it. Other
* accounts may add or remove their IDs from this set.
*/
flat_set<account_id_type> whitelisting_accounts;
/**
* Optionally track all of the accounts this account has whitelisted or blacklisted, these should
* be made Immutable so that when the account object is cloned no deep copy is required. This state is
* tracked for GUI display purposes.
*
* TODO: move white list tracking to its own multi-index container rather than having 4 fields on an
* account. This will scale better because under the current design if you whitelist 2000 accounts,
* then every time someone fetches this account object they will get the full list of 2000 accounts.
*/
///@{
set<account_id_type> whitelisted_accounts;
set<account_id_type> blacklisted_accounts;
///@}
/**
* This is a set of all accounts which have 'blacklisted' this account. Blacklisting is only used in core
* validation for the purpose of forbidding accounts from holding and transacting in whitelisted assets. This
* account cannot update this set, and it will be preserved even if the account is transferred. Other accounts
* may add or remove their IDs from this set.
*/
flat_set<account_id_type> blacklisting_accounts;
/**
* Vesting balance which receives cashback_reward deposits.
*/
optional<vesting_balance_id_type> cashback_vb;
template<typename DB>
const vesting_balance_object& cashback_balance(const DB& db)const
{
FC_ASSERT(cashback_vb);
return db.get(*cashback_vb);
}
/// @return true if this is a lifetime member account; false otherwise.
bool is_lifetime_member()const
{
return membership_expiration_date == time_point_sec::maximum();
}
/// @return true if this is a basic account; false otherwise.
bool is_basic_account(time_point_sec now)const
{
return now > membership_expiration_date;
}
/// @return true if the account is an unexpired annual member; false otherwise.
/// @note This method will return false for lifetime members.
bool is_annual_member(time_point_sec now)const
{
return !is_lifetime_member() && !is_basic_account(now);
}
/// @return true if the account is an annual or lifetime member; false otherwise.
bool is_member(time_point_sec now)const
{
return !is_basic_account(now);
}
/**
* @return true if this account is whitelisted and not blacklisted to transact in the provided asset; false
* otherwise.
*/
bool is_authorized_asset(const asset_object& asset_obj, const database& d)const;
account_id_type get_id()const { return id; }
};
/**
* @brief This secondary index will allow a reverse lookup of all accounts that a particular key or account
* is an potential signing authority.
*/
class account_member_index : public secondary_index
{
public:
virtual void object_inserted( const object& obj ) override;
virtual void object_removed( const object& obj ) override;
virtual void about_to_modify( const object& before ) override;
virtual void object_modified( const object& after ) override;
/** given an account or key, map it to the set of accounts that reference it in an active or owner authority */
map< account_id_type, set<account_id_type> > account_to_account_memberships;
map< public_key_type, set<account_id_type> > account_to_key_memberships;
/** some accounts use address authorities in the genesis block */
map< address, set<account_id_type> > account_to_address_memberships;
protected:
set<account_id_type> get_account_members( const account_object& a )const;
set<public_key_type> get_key_members( const account_object& a )const;
set<address> get_address_members( const account_object& a )const;
set<account_id_type> before_account_members;
set<public_key_type> before_key_members;
set<address> before_address_members;
};
/**
* @brief This secondary index will allow a reverse lookup of all accounts that have been referred by
* a particular account.
*/
class account_referrer_index : public secondary_index
{
public:
virtual void object_inserted( const object& obj ) override;
virtual void object_removed( const object& obj ) override;
virtual void about_to_modify( const object& before ) override;
virtual void object_modified( const object& after ) override;
/** maps the referrer to the set of accounts that they have referred */
map< account_id_type, set<account_id_type> > referred_by;
};
struct by_asset;
struct by_account_asset;
/**
* @ingroup object_index
*/
typedef multi_index_container<
account_balance_object,
indexed_by<
ordered_unique< tag<by_id>, member< object, object_id_type, &object::id > >,
ordered_unique< tag<by_account_asset>, composite_key<
account_balance_object,
member<account_balance_object, account_id_type, &account_balance_object::owner>,
member<account_balance_object, asset_id_type, &account_balance_object::asset_type> >
>,
ordered_non_unique< tag<by_asset>, member<account_balance_object, asset_id_type, &account_balance_object::asset_type> >
>
> account_balance_object_multi_index_type;
/**
* @ingroup object_index
*/
typedef generic_index<account_balance_object, account_balance_object_multi_index_type> account_balance_index;
struct by_name{};
/**
* @ingroup object_index
*/
typedef multi_index_container<
account_object,
indexed_by<
ordered_unique< tag<by_id>, member< object, object_id_type, &object::id > >,
ordered_unique< tag<by_name>, member<account_object, string, &account_object::name> >
>
> account_multi_index_type;
/**
* @ingroup object_index
*/
typedef generic_index<account_object, account_multi_index_type> account_index;
}}
FC_REFLECT_DERIVED( graphene::chain::account_object,
(graphene::db::object),
(membership_expiration_date)(registrar)(referrer)(lifetime_referrer)
(network_fee_percentage)(lifetime_referrer_fee_percentage)(referrer_rewards_percentage)
(name)(owner)(active)(options)(statistics)(whitelisting_accounts)(blacklisting_accounts)
(whitelisting_accounts)(blacklisted_accounts)
(cashback_vb) )
FC_REFLECT_DERIVED( graphene::chain::account_balance_object,
(graphene::db::object),
(owner)(asset_type)(balance) )
FC_REFLECT_DERIVED( graphene::chain::account_statistics_object,
(graphene::chain::object),
(owner)
(most_recent_op)
(total_core_in_orders)
(lifetime_fees_paid)
(pending_fees)(pending_vested_fees)
)
<commit_msg>Implement by_asset_balance index #529<commit_after>/*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* 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.
*/
#pragma once
#include <graphene/chain/protocol/operations.hpp>
#include <graphene/db/generic_index.hpp>
#include <boost/multi_index/composite_key.hpp>
namespace graphene { namespace chain {
class database;
/**
* @class account_statistics_object
* @ingroup object
* @ingroup implementation
*
* This object contains regularly updated statistical data about an account. It is provided for the purpose of
* separating the account data that changes frequently from the account data that is mostly static, which will
* minimize the amount of data that must be backed up as part of the undo history everytime a transfer is made.
*/
class account_statistics_object : public graphene::db::abstract_object<account_statistics_object>
{
public:
static const uint8_t space_id = implementation_ids;
static const uint8_t type_id = impl_account_statistics_object_type;
account_id_type owner;
/**
* Keep the most recent operation as a root pointer to a linked list of the transaction history.
*/
account_transaction_history_id_type most_recent_op;
/**
* When calculating votes it is necessary to know how much is stored in orders (and thus unavailable for
* transfers). Rather than maintaining an index of [asset,owner,order_id] we will simply maintain the running
* total here and update it every time an order is created or modified.
*/
share_type total_core_in_orders;
/**
* Tracks the total fees paid by this account for the purpose of calculating bulk discounts.
*/
share_type lifetime_fees_paid;
/**
* Tracks the fees paid by this account which have not been disseminated to the various parties that receive
* them yet (registrar, referrer, lifetime referrer, network, etc). This is used as an optimization to avoid
* doing massive amounts of uint128 arithmetic on each and every operation.
*
* These fees will be paid out as vesting cash-back, and this counter will reset during the maintenance
* interval.
*/
share_type pending_fees;
/**
* Same as @ref pending_fees, except these fees will be paid out as pre-vested cash-back (immediately
* available for withdrawal) rather than requiring the normal vesting period.
*/
share_type pending_vested_fees;
/// @brief Split up and pay out @ref pending_fees and @ref pending_vested_fees
void process_fees(const account_object& a, database& d) const;
/**
* Core fees are paid into the account_statistics_object by this method
*/
void pay_fee( share_type core_fee, share_type cashback_vesting_threshold );
};
/**
* @brief Tracks the balance of a single account/asset pair
* @ingroup object
*
* This object is indexed on owner and asset_type so that black swan
* events in asset_type can be processed quickly.
*/
class account_balance_object : public abstract_object<account_balance_object>
{
public:
static const uint8_t space_id = implementation_ids;
static const uint8_t type_id = impl_account_balance_object_type;
account_id_type owner;
asset_id_type asset_type;
share_type balance;
asset get_balance()const { return asset(balance, asset_type); }
void adjust_balance(const asset& delta);
};
/**
* @brief This class represents an account on the object graph
* @ingroup object
* @ingroup protocol
*
* Accounts are the primary unit of authority on the graphene system. Users must have an account in order to use
* assets, trade in the markets, vote for committee_members, etc.
*/
class account_object : public graphene::db::abstract_object<account_object>
{
public:
static const uint8_t space_id = protocol_ids;
static const uint8_t type_id = account_object_type;
/**
* The time at which this account's membership expires.
* If set to any time in the past, the account is a basic account.
* If set to time_point_sec::maximum(), the account is a lifetime member.
* If set to any time not in the past less than time_point_sec::maximum(), the account is an annual member.
*
* See @ref is_lifetime_member, @ref is_basic_account, @ref is_annual_member, and @ref is_member
*/
time_point_sec membership_expiration_date;
///The account that paid the fee to register this account. Receives a percentage of referral rewards.
account_id_type registrar;
/// The account credited as referring this account. Receives a percentage of referral rewards.
account_id_type referrer;
/// The lifetime member at the top of the referral tree. Receives a percentage of referral rewards.
account_id_type lifetime_referrer;
/// Percentage of fee which should go to network.
uint16_t network_fee_percentage = GRAPHENE_DEFAULT_NETWORK_PERCENT_OF_FEE;
/// Percentage of fee which should go to lifetime referrer.
uint16_t lifetime_referrer_fee_percentage = 0;
/// Percentage of referral rewards (leftover fee after paying network and lifetime referrer) which should go
/// to referrer. The remainder of referral rewards goes to the registrar.
uint16_t referrer_rewards_percentage = 0;
/// The account's name. This name must be unique among all account names on the graph. May not be empty.
string name;
/**
* The owner authority represents absolute control over the account. Usually the keys in this authority will
* be kept in cold storage, as they should not be needed very often and compromise of these keys constitutes
* complete and irrevocable loss of the account. Generally the only time the owner authority is required is to
* update the active authority.
*/
authority owner;
/// The owner authority contains the hot keys of the account. This authority has control over nearly all
/// operations the account may perform.
authority active;
typedef account_options options_type;
account_options options;
/// The reference implementation records the account's statistics in a separate object. This field contains the
/// ID of that object.
account_statistics_id_type statistics;
/**
* This is a set of all accounts which have 'whitelisted' this account. Whitelisting is only used in core
* validation for the purpose of authorizing accounts to hold and transact in whitelisted assets. This
* account cannot update this set, except by transferring ownership of the account, which will clear it. Other
* accounts may add or remove their IDs from this set.
*/
flat_set<account_id_type> whitelisting_accounts;
/**
* Optionally track all of the accounts this account has whitelisted or blacklisted, these should
* be made Immutable so that when the account object is cloned no deep copy is required. This state is
* tracked for GUI display purposes.
*
* TODO: move white list tracking to its own multi-index container rather than having 4 fields on an
* account. This will scale better because under the current design if you whitelist 2000 accounts,
* then every time someone fetches this account object they will get the full list of 2000 accounts.
*/
///@{
set<account_id_type> whitelisted_accounts;
set<account_id_type> blacklisted_accounts;
///@}
/**
* This is a set of all accounts which have 'blacklisted' this account. Blacklisting is only used in core
* validation for the purpose of forbidding accounts from holding and transacting in whitelisted assets. This
* account cannot update this set, and it will be preserved even if the account is transferred. Other accounts
* may add or remove their IDs from this set.
*/
flat_set<account_id_type> blacklisting_accounts;
/**
* Vesting balance which receives cashback_reward deposits.
*/
optional<vesting_balance_id_type> cashback_vb;
template<typename DB>
const vesting_balance_object& cashback_balance(const DB& db)const
{
FC_ASSERT(cashback_vb);
return db.get(*cashback_vb);
}
/// @return true if this is a lifetime member account; false otherwise.
bool is_lifetime_member()const
{
return membership_expiration_date == time_point_sec::maximum();
}
/// @return true if this is a basic account; false otherwise.
bool is_basic_account(time_point_sec now)const
{
return now > membership_expiration_date;
}
/// @return true if the account is an unexpired annual member; false otherwise.
/// @note This method will return false for lifetime members.
bool is_annual_member(time_point_sec now)const
{
return !is_lifetime_member() && !is_basic_account(now);
}
/// @return true if the account is an annual or lifetime member; false otherwise.
bool is_member(time_point_sec now)const
{
return !is_basic_account(now);
}
/**
* @return true if this account is whitelisted and not blacklisted to transact in the provided asset; false
* otherwise.
*/
bool is_authorized_asset(const asset_object& asset_obj, const database& d)const;
account_id_type get_id()const { return id; }
};
/**
* @brief This secondary index will allow a reverse lookup of all accounts that a particular key or account
* is an potential signing authority.
*/
class account_member_index : public secondary_index
{
public:
virtual void object_inserted( const object& obj ) override;
virtual void object_removed( const object& obj ) override;
virtual void about_to_modify( const object& before ) override;
virtual void object_modified( const object& after ) override;
/** given an account or key, map it to the set of accounts that reference it in an active or owner authority */
map< account_id_type, set<account_id_type> > account_to_account_memberships;
map< public_key_type, set<account_id_type> > account_to_key_memberships;
/** some accounts use address authorities in the genesis block */
map< address, set<account_id_type> > account_to_address_memberships;
protected:
set<account_id_type> get_account_members( const account_object& a )const;
set<public_key_type> get_key_members( const account_object& a )const;
set<address> get_address_members( const account_object& a )const;
set<account_id_type> before_account_members;
set<public_key_type> before_key_members;
set<address> before_address_members;
};
/**
* @brief This secondary index will allow a reverse lookup of all accounts that have been referred by
* a particular account.
*/
class account_referrer_index : public secondary_index
{
public:
virtual void object_inserted( const object& obj ) override;
virtual void object_removed( const object& obj ) override;
virtual void about_to_modify( const object& before ) override;
virtual void object_modified( const object& after ) override;
/** maps the referrer to the set of accounts that they have referred */
map< account_id_type, set<account_id_type> > referred_by;
};
struct by_account_asset;
struct by_asset_balance;
/**
* @ingroup object_index
*/
typedef multi_index_container<
account_balance_object,
indexed_by<
ordered_unique< tag<by_id>, member< object, object_id_type, &object::id > >,
ordered_unique< tag<by_account_asset>,
composite_key<
account_balance_object,
member<account_balance_object, account_id_type, &account_balance_object::owner>,
member<account_balance_object, asset_id_type, &account_balance_object::asset_type>
>
>,
ordered_unique< tag<by_asset_balance>,
composite_key<
account_balance_object,
member<account_balance_object, asset_id_type, &account_balance_object::asset_type>,
member<account_balance_object, share_type, &account_balance_object::balance>,
member<account_balance_object, account_id_type, &account_balance_object::owner>
>,
composite_key_compare<
std::less< asset_id_type >,
std::greater< share_type >,
std::less< account_id_type >
>
>
>
> account_balance_object_multi_index_type;
/**
* @ingroup object_index
*/
typedef generic_index<account_balance_object, account_balance_object_multi_index_type> account_balance_index;
struct by_name{};
/**
* @ingroup object_index
*/
typedef multi_index_container<
account_object,
indexed_by<
ordered_unique< tag<by_id>, member< object, object_id_type, &object::id > >,
ordered_unique< tag<by_name>, member<account_object, string, &account_object::name> >
>
> account_multi_index_type;
/**
* @ingroup object_index
*/
typedef generic_index<account_object, account_multi_index_type> account_index;
}}
FC_REFLECT_DERIVED( graphene::chain::account_object,
(graphene::db::object),
(membership_expiration_date)(registrar)(referrer)(lifetime_referrer)
(network_fee_percentage)(lifetime_referrer_fee_percentage)(referrer_rewards_percentage)
(name)(owner)(active)(options)(statistics)(whitelisting_accounts)(blacklisting_accounts)
(whitelisting_accounts)(blacklisted_accounts)
(cashback_vb) )
FC_REFLECT_DERIVED( graphene::chain::account_balance_object,
(graphene::db::object),
(owner)(asset_type)(balance) )
FC_REFLECT_DERIVED( graphene::chain::account_statistics_object,
(graphene::chain::object),
(owner)
(most_recent_op)
(total_core_in_orders)
(lifetime_fees_paid)
(pending_fees)(pending_vested_fees)
)
<|endoftext|>
|
<commit_before>#line 12 "network.nw"
#include "network.h"
#include <QAbstractSocket>
#include <QTcpSocket>
#include <QTcpServer>
#include <QWebSocket>
#line 22 "network.nw"
// TcpClient functions/*{{{*/
int network_tcp_client(lua_State *L) {/*{{{*/
QTcpSocket *tcpSocket = new QTcpSocket();
QTcpSocket **p = static_cast<QTcpSocket**>(lua_newuserdata(L, sizeof(QTcpServer*)));
*p = tcpSocket;
luaL_getmetatable(L, "network.TcpSocket");
lua_setmetatable(L, -2);
return 1;
}/*}}}*/
int tcp_socket_connect(lua_State *L) {/*{{{*/
#line 65 "network.nw"
QTcpSocket *tcpSocket =
*static_cast<QTcpSocket**>(luaL_checkudata(L, 1, "network.TcpSocket"));
#line 33 "network.nw"
const char* ip = luaL_checkstring(L, 2);
int port = luaL_checkinteger(L, 3);
tcpSocket->connectToHost(ip, port);
return 0;
}/*}}}*/
int tcp_socket_read(lua_State *L) {/*{{{*/
#line 65 "network.nw"
QTcpSocket *tcpSocket =
*static_cast<QTcpSocket**>(luaL_checkudata(L, 1, "network.TcpSocket"));
#line 40 "network.nw"
int maxSize = luaL_checkinteger(L, 2);
QByteArray result = tcpSocket->read(maxSize);
lua_pushlstring(L, result.data(), result.count());
return 1;
}/*}}}*/
int tcp_socket_read_all(lua_State *L) {/*{{{*/
#line 65 "network.nw"
QTcpSocket *tcpSocket =
*static_cast<QTcpSocket**>(luaL_checkudata(L, 1, "network.TcpSocket"));
#line 40 "network.nw"
QByteArray result = tcpSocket->readAll();
lua_pushlstring(L, result.data(), result.count());
return 1;
}/*}}}*/
int tcp_socket_write(lua_State *L) {/*{{{*/
#line 65 "network.nw"
QTcpSocket *tcpSocket =
*static_cast<QTcpSocket**>(luaL_checkudata(L, 1, "network.TcpSocket"));
#line 47 "network.nw"
size_t size;
const char* data = luaL_checklstring(L, 2, &size);
int result = tcpSocket->write(data, size);
lua_pushinteger(L, result);
return 1;
}/*}}}*/
int tcp_socket_close(lua_State *L) {/*{{{*/
#line 65 "network.nw"
QTcpSocket *tcpSocket =
*static_cast<QTcpSocket**>(luaL_checkudata(L, 1, "network.TcpSocket"));
#line 55 "network.nw"
tcpSocket->close();
return 0;
}/*}}}*/
int tcp_socket_delete(lua_State *L) {/*{{{*/
#line 65 "network.nw"
QTcpSocket *tcpSocket =
*static_cast<QTcpSocket**>(luaL_checkudata(L, 1, "network.TcpSocket"));
#line 60 "network.nw"
delete tcpSocket;
return 0;
}/*}}}*/
/*}}}*/
#line 69 "network.nw"
// TcpServer functions/*{{{*/
int network_tcp_server(lua_State *L) {/*{{{*/
QTcpServer *tcpServer = new QTcpServer();
QTcpServer **p = static_cast<QTcpServer**>(lua_newuserdata(L, sizeof(QTcpServer*)));
*p = tcpServer;
luaL_getmetatable(L, "network.TcpServer");
lua_setmetatable(L, -2);
return 1;
}/*}}}*/
int tcp_server_listen(lua_State *L)/*{{{*/
{
#line 111 "network.nw"
QTcpServer *tcpServer =
*static_cast<QTcpServer**>(luaL_checkudata(L, 1, "network.TcpServer"));
#line 81 "network.nw"
const char * ip = luaL_checkstring(L, 2);
QHostAddress addr(ip);
int port = luaL_checkinteger(L, 3);
lua_pushboolean(L, tcpServer->listen(QHostAddress::Any, port));
return 1;
}/*}}}*/
int tcp_server_get_connection(lua_State *L)/*{{{*/
{
#line 111 "network.nw"
QTcpServer *tcpServer =
*static_cast<QTcpServer**>(luaL_checkudata(L, 1, "network.TcpServer"));
#line 91 "network.nw"
QTcpSocket *tcpSocket = tcpServer->nextPendingConnection();
if (tcpSocket) {
QTcpSocket **p = static_cast<QTcpSocket**>(lua_newuserdata(L, sizeof(QTcpServer*)));
*p = tcpSocket;
luaL_getmetatable(L, "network.TcpSocket");
lua_setmetatable(L, -2);
} else {
lua_pushnil(L);
}
return 1;
}/*}}}*/
int tcp_server_delete(lua_State *L) {/*{{{*/
#line 111 "network.nw"
QTcpServer *tcpServer =
*static_cast<QTcpServer**>(luaL_checkudata(L, 1, "network.TcpServer"));
#line 105 "network.nw"
delete tcpServer;
return 0;
}/*}}}*/
/*}}}*/
#line 115 "network.nw"
// WebSocket functions/*{{{*/
int network_web_socket(lua_State *L) {/*{{{*/
QWebSocket *webSocket = new QWebSocket();
QWebSocket **p = static_cast<QWebSocket**>(lua_newuserdata(L, sizeof(QWebSocket*)));
*p = webSocket;
luaL_getmetatable(L, "network.WebSocket");
lua_setmetatable(L, -2);
return 1;
}/*}}}*/
int web_socket_open(lua_State *L) {/*{{{*/
#line 153 "network.nw"
QWebSocket *webSocket =
*static_cast<QWebSocket**>(luaL_checkudata(L, 1, "network.WebSocket"));
#line 126 "network.nw"
QUrl url(luaL_checkstring(L, 2));
url.setPort(lua_tointegerx(L, 3, NULL));
webSocket->open(url);
return 0;
}/*}}}*/
int web_socket_close(lua_State *L) {/*{{{*/
#line 153 "network.nw"
QWebSocket *webSocket =
*static_cast<QWebSocket**>(luaL_checkudata(L, 1, "network.WebSocket"));
#line 133 "network.nw"
webSocket->close();
return 0;
}/*}}}*/
int web_socket_write(lua_State *L) {/*{{{*/
#line 153 "network.nw"
QWebSocket *webSocket =
*static_cast<QWebSocket**>(luaL_checkudata(L, 1, "network.WebSocket"));
#line 138 "network.nw"
size_t size;
const char* data = luaL_checklstring(L, 2, &size);
QByteArray b(data, size);
int res = webSocket->sendTextMessage(b);
lua_pushinteger(L, res);
return 1;
}/*}}}*/
int web_socket_delete(lua_State *L) {/*{{{*/
#line 153 "network.nw"
QWebSocket *webSocket =
*static_cast<QWebSocket**>(luaL_checkudata(L, 1, "network.WebSocket"));
#line 148 "network.nw"
delete webSocket;
return 0;
}/*}}}*/
/*}}}*/
#line 158 "network.nw"
int luaopen_network(lua_State *L) {
lua_newtable(L);
// TcpServer metatable/*{{{*/
luaL_newmetatable(L, "network.TcpServer");
lua_newtable(L);
luaL_Reg tcp_server_functions[] = {
{ "listen", &tcp_server_listen },
{ "get_connection", &tcp_server_get_connection },
{ NULL, NULL }
};
luaL_setfuncs(L, tcp_server_functions, 0);
lua_setfield(L, -2, "__index");
lua_pushcfunction(L, tcp_server_delete);
lua_setfield(L, -2, "__gc");/*}}}*/
// TcpSocket metatable/*{{{*/
luaL_newmetatable(L, "network.TcpSocket");
lua_newtable(L);
luaL_Reg tcp_socket_functions[] = {
{ "connect", &tcp_socket_connect },
{ "read", &tcp_socket_read },
{ "read_all", &tcp_socket_read_all },
{ "write", &tcp_socket_write },
{ "close", &tcp_socket_close },
{ NULL, NULL }
};
luaL_setfuncs(L, tcp_socket_functions, 0);
lua_setfield(L, -2, "__index");
lua_pushcfunction(L, tcp_socket_delete);
lua_setfield(L, -2, "__gc");/*}}}*/
// WebSocket metatable/*{{{*/
luaL_newmetatable(L, "network.WebSocket");
lua_newtable(L);
luaL_Reg web_socket_functions[] = {
{ "open", &web_socket_open },
{ "close", &web_socket_close },
{ "write", &web_socket_write },
{ NULL, NULL }
};
luaL_setfuncs(L, web_socket_functions, 0);
lua_setfield(L, -2, "__index");
lua_pushcfunction(L, web_socket_delete);
lua_setfield(L, -2, "__gc");/*}}}*/
luaL_Reg network_functions[] = {
{ "TcpClient", &network_tcp_client },
{ "TcpServer", &network_tcp_server },
{ "WebSocket", &network_web_socket },
{ NULL, NULL }
};
luaL_newlib(L, network_functions);
return 1;
}
<commit_msg>Fix QIODevice error message<commit_after>#line 12 "network.nw"
#include "network.h"
#include <QAbstractSocket>
#include <QTcpSocket>
#include <QTcpServer>
#include <QWebSocket>
#line 22 "network.nw"
// TcpClient functions/*{{{*/
int network_tcp_client(lua_State *L) {/*{{{*/
QTcpSocket *tcpSocket = new QTcpSocket();
QTcpSocket **p = static_cast<QTcpSocket**>(lua_newuserdata(L, sizeof(QTcpServer*)));
*p = tcpSocket;
luaL_getmetatable(L, "network.TcpSocket");
lua_setmetatable(L, -2);
return 1;
}/*}}}*/
int tcp_socket_connect(lua_State *L) {/*{{{*/
#line 65 "network.nw"
QTcpSocket *tcpSocket =
*static_cast<QTcpSocket**>(luaL_checkudata(L, 1, "network.TcpSocket"));
#line 33 "network.nw"
const char* ip = luaL_checkstring(L, 2);
int port = luaL_checkinteger(L, 3);
tcpSocket->connectToHost(ip, port);
return 0;
}/*}}}*/
int tcp_socket_read(lua_State *L) {/*{{{*/
#line 65 "network.nw"
QTcpSocket *tcpSocket =
*static_cast<QTcpSocket**>(luaL_checkudata(L, 1, "network.TcpSocket"));
#line 40 "network.nw"
int maxSize = luaL_checkinteger(L, 2);
if(tcpSocket->isOpen()){
QByteArray result = tcpSocket->read(maxSize);
lua_pushlstring(L, result.data(), result.count());
}
return 1;
}/*}}}*/
int tcp_socket_read_all(lua_State *L) {/*{{{*/
#line 65 "network.nw"
QTcpSocket *tcpSocket =
*static_cast<QTcpSocket**>(luaL_checkudata(L, 1, "network.TcpSocket"));
#line 40 "network.nw"
QByteArray result = tcpSocket->readAll();
lua_pushlstring(L, result.data(), result.count());
return 1;
}/*}}}*/
int tcp_socket_write(lua_State *L) {/*{{{*/
#line 65 "network.nw"
QTcpSocket *tcpSocket =
*static_cast<QTcpSocket**>(luaL_checkudata(L, 1, "network.TcpSocket"));
#line 47 "network.nw"
size_t size;
const char* data = luaL_checklstring(L, 2, &size);
if(tcpSocket->isOpen()) {
int result = tcpSocket->write(data, size);
lua_pushinteger(L, result);
}
return 1;
}/*}}}*/
int tcp_socket_close(lua_State *L) {/*{{{*/
#line 65 "network.nw"
QTcpSocket *tcpSocket =
*static_cast<QTcpSocket**>(luaL_checkudata(L, 1, "network.TcpSocket"));
#line 55 "network.nw"
tcpSocket->close();
return 0;
}/*}}}*/
int tcp_socket_delete(lua_State *L) {/*{{{*/
#line 65 "network.nw"
QTcpSocket *tcpSocket =
*static_cast<QTcpSocket**>(luaL_checkudata(L, 1, "network.TcpSocket"));
#line 60 "network.nw"
delete tcpSocket;
return 0;
}/*}}}*/
/*}}}*/
#line 69 "network.nw"
// TcpServer functions/*{{{*/
int network_tcp_server(lua_State *L) {/*{{{*/
QTcpServer *tcpServer = new QTcpServer();
QTcpServer **p = static_cast<QTcpServer**>(lua_newuserdata(L, sizeof(QTcpServer*)));
*p = tcpServer;
luaL_getmetatable(L, "network.TcpServer");
lua_setmetatable(L, -2);
return 1;
}/*}}}*/
int tcp_server_listen(lua_State *L)/*{{{*/
{
#line 111 "network.nw"
QTcpServer *tcpServer =
*static_cast<QTcpServer**>(luaL_checkudata(L, 1, "network.TcpServer"));
#line 81 "network.nw"
const char * ip = luaL_checkstring(L, 2);
QHostAddress addr(ip);
int port = luaL_checkinteger(L, 3);
lua_pushboolean(L, tcpServer->listen(QHostAddress::Any, port));
return 1;
}/*}}}*/
int tcp_server_get_connection(lua_State *L)/*{{{*/
{
#line 111 "network.nw"
QTcpServer *tcpServer =
*static_cast<QTcpServer**>(luaL_checkudata(L, 1, "network.TcpServer"));
#line 91 "network.nw"
QTcpSocket *tcpSocket = tcpServer->nextPendingConnection();
if (tcpSocket) {
QTcpSocket **p = static_cast<QTcpSocket**>(lua_newuserdata(L, sizeof(QTcpServer*)));
*p = tcpSocket;
luaL_getmetatable(L, "network.TcpSocket");
lua_setmetatable(L, -2);
} else {
lua_pushnil(L);
}
return 1;
}/*}}}*/
int tcp_server_delete(lua_State *L) {/*{{{*/
#line 111 "network.nw"
QTcpServer *tcpServer =
*static_cast<QTcpServer**>(luaL_checkudata(L, 1, "network.TcpServer"));
#line 105 "network.nw"
delete tcpServer;
return 0;
}/*}}}*/
/*}}}*/
#line 115 "network.nw"
// WebSocket functions/*{{{*/
int network_web_socket(lua_State *L) {/*{{{*/
QWebSocket *webSocket = new QWebSocket();
QWebSocket **p = static_cast<QWebSocket**>(lua_newuserdata(L, sizeof(QWebSocket*)));
*p = webSocket;
luaL_getmetatable(L, "network.WebSocket");
lua_setmetatable(L, -2);
return 1;
}/*}}}*/
int web_socket_open(lua_State *L) {/*{{{*/
#line 153 "network.nw"
QWebSocket *webSocket =
*static_cast<QWebSocket**>(luaL_checkudata(L, 1, "network.WebSocket"));
#line 126 "network.nw"
QUrl url(luaL_checkstring(L, 2));
url.setPort(lua_tointegerx(L, 3, NULL));
webSocket->open(url);
return 0;
}/*}}}*/
int web_socket_close(lua_State *L) {/*{{{*/
#line 153 "network.nw"
QWebSocket *webSocket =
*static_cast<QWebSocket**>(luaL_checkudata(L, 1, "network.WebSocket"));
#line 133 "network.nw"
webSocket->close();
return 0;
}/*}}}*/
int web_socket_write(lua_State *L) {/*{{{*/
#line 153 "network.nw"
QWebSocket *webSocket =
*static_cast<QWebSocket**>(luaL_checkudata(L, 1, "network.WebSocket"));
#line 138 "network.nw"
size_t size;
const char* data = luaL_checklstring(L, 2, &size);
QByteArray b(data, size);
int res = webSocket->sendTextMessage(b);
lua_pushinteger(L, res);
return 1;
}/*}}}*/
int web_socket_delete(lua_State *L) {/*{{{*/
#line 153 "network.nw"
QWebSocket *webSocket =
*static_cast<QWebSocket**>(luaL_checkudata(L, 1, "network.WebSocket"));
#line 148 "network.nw"
delete webSocket;
return 0;
}/*}}}*/
/*}}}*/
#line 158 "network.nw"
int luaopen_network(lua_State *L) {
lua_newtable(L);
// TcpServer metatable/*{{{*/
luaL_newmetatable(L, "network.TcpServer");
lua_newtable(L);
luaL_Reg tcp_server_functions[] = {
{ "listen", &tcp_server_listen },
{ "get_connection", &tcp_server_get_connection },
{ NULL, NULL }
};
luaL_setfuncs(L, tcp_server_functions, 0);
lua_setfield(L, -2, "__index");
lua_pushcfunction(L, tcp_server_delete);
lua_setfield(L, -2, "__gc");/*}}}*/
// TcpSocket metatable/*{{{*/
luaL_newmetatable(L, "network.TcpSocket");
lua_newtable(L);
luaL_Reg tcp_socket_functions[] = {
{ "connect", &tcp_socket_connect },
{ "read", &tcp_socket_read },
{ "read_all", &tcp_socket_read_all },
{ "write", &tcp_socket_write },
{ "close", &tcp_socket_close },
{ NULL, NULL }
};
luaL_setfuncs(L, tcp_socket_functions, 0);
lua_setfield(L, -2, "__index");
lua_pushcfunction(L, tcp_socket_delete);
lua_setfield(L, -2, "__gc");/*}}}*/
// WebSocket metatable/*{{{*/
luaL_newmetatable(L, "network.WebSocket");
lua_newtable(L);
luaL_Reg web_socket_functions[] = {
{ "open", &web_socket_open },
{ "close", &web_socket_close },
{ "write", &web_socket_write },
{ NULL, NULL }
};
luaL_setfuncs(L, web_socket_functions, 0);
lua_setfield(L, -2, "__index");
lua_pushcfunction(L, web_socket_delete);
lua_setfield(L, -2, "__gc");/*}}}*/
luaL_Reg network_functions[] = {
{ "TcpClient", &network_tcp_client },
{ "TcpServer", &network_tcp_server },
{ "WebSocket", &network_web_socket },
{ NULL, NULL }
};
luaL_newlib(L, network_functions);
return 1;
}
<|endoftext|>
|
<commit_before>/*
* seqinfo.cc
*
* Created on: Feb 27, 2015
* Author: mimitantono
*/
#include "seqinfo.h"
#include <stddef.h>
pthread_mutex_t seqinfo_t::mutex;
seqinfo_t::seqinfo_t() {
header = 0;
seq = 0;
headerlen = 0;
hdrhash = 0;
seqlen = 0;
abundance = 0;
visited = false;
// pthread_mutex_init(&mutex, NULL);
}
seqinfo_t::~seqinfo_t() {
// pthread_mutex_destroy(&mutex);
}
bool seqinfo_t::is_visited() {
bool result;
// pthread_mutex_lock(&mutex);
result = visited;
// pthread_mutex_unlock(&mutex);
return result;
}
void seqinfo_t::set_visited() {
// pthread_mutex_lock(&mutex);
visited = true;
// pthread_mutex_unlock(&mutex);
}
<commit_msg>remove mutex<commit_after>/*
* seqinfo.cc
*
* Created on: Feb 27, 2015
* Author: mimitantono
*/
#include "seqinfo.h"
#include <stddef.h>
//pthread_mutex_t seqinfo_t::mutex;
seqinfo_t::seqinfo_t() {
header = 0;
seq = 0;
headerlen = 0;
hdrhash = 0;
seqlen = 0;
abundance = 0;
visited = false;
// pthread_mutex_init(&mutex, NULL);
}
seqinfo_t::~seqinfo_t() {
// pthread_mutex_destroy(&mutex);
}
bool seqinfo_t::is_visited() {
bool result;
// pthread_mutex_lock(&mutex);
result = visited;
// pthread_mutex_unlock(&mutex);
return result;
}
void seqinfo_t::set_visited() {
// pthread_mutex_lock(&mutex);
visited = true;
// pthread_mutex_unlock(&mutex);
}
<|endoftext|>
|
<commit_before>#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "server.h"
#include "http.tab.hpp"
#define SERV_PORT 8080
using namespace sock;
using namespace hcppd;
using namespace std;
extern int yyparse();
extern int yylex_destroy();
extern int yy_scan_string(const char *str);
extern HttpRequest *request;
HttpResponse HttpServer::handleRequest(const HttpRequest& request) {
HttpResponse response;
response.status_line.protocol_version = "HTTP/1.1";
unique_ptr<string> uri = move(request.request_line->uri);
syslog(LOG_INFO, "Responding to request for: %s", uri->c_str());
struct stat st;
if (stat(uri->c_str(), &st) == -1) {
if (errno == ENOENT) {
response.status_line.status_code = 404;
response.status_line.reason_phrase = "Not Found!";
return response;
}
response.status_line.status_code = 500;
syslog(LOG_ERR, "Error stat-ing directory %s: %m", uri->c_str());
response.status_line.reason_phrase = "Error stat-ing directory";
return response;
}
stringstream res_ss;
if (st.st_mode & S_IFDIR) {
if (uri->at(uri->size()-1) != '/') {
uri->push_back('/');
}
DIR* d;
if ((d = opendir(uri->c_str())) == NULL) {
response.status_line.status_code = 500;
syslog(LOG_ERR, "Error opening directory %s: %m", uri->c_str());
response.status_line.reason_phrase = "Error opening directory";
return response;
}
struct dirent* dir;
while ((dir = readdir(d))) {
string d_name(dir->d_name);
if (d_name == "." || d_name == "..") {
continue;
}
struct stat st2;
string d_uri;
stringstream ss;
ss << *uri << d_name;
d_uri = ss.str();
if (stat(d_uri.c_str(), &st2) == -1) {
syslog(LOG_ERR, "Could not stat file in directory; %m");
continue;
}
if (st.st_mode & S_IFDIR) {
res_ss << "<a href=" << d_uri << ">"
<< d_uri << "</a><br>" << endl;
}
}
}
else if (st.st_mode & S_IFREG) {
ifstream fin{*uri, ifstream::in};
string line;
while (getline(fin, line)) {
res_ss << line << " <br>" << endl;
}
}
else {
res_ss << "somethin' else";
}
response.status_line.status_code = 200;
response.status_line.reason_phrase = "OK";
response.message = res_ss.str();
return response;
}
HttpRequest HttpServer::parseRequest(const string& requestString) {
yy_scan_string(requestString.c_str());
yyparse();
yylex_destroy();
return move(*request);
}
HttpResponse HttpServer::handleConnection() {
std::string msg;
sock_.Read(&msg);
return handleRequest(parseRequest(msg));
}
void HttpServer::sendResponse(const HttpResponse& response) {
sock_.Write(response.format());
}
void HttpServer::serve() {
sock_.Bind(SERV_PORT);
sock_.Listen();
for ( ; ; ) {
socklen_t clilen;
sock_.Accept(&clilen);
sock_.getConnFd();
int pid = fork();
if (pid < 0) {
// error
syslog(LOG_WARNING, "failed to fork child to handle connection");
} else if (pid == 0) {
// child
close(sock_.getListenFd());
sendResponse(handleConnection());
exit(0);
}
else {
// parent
close(sock_.getConnFd());
}
}
}
<commit_msg>didnt even need to get connFd there... dumb<commit_after>#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "server.h"
#include "http.tab.hpp"
#define SERV_PORT 8080
using namespace sock;
using namespace hcppd;
using namespace std;
extern int yyparse();
extern int yylex_destroy();
extern int yy_scan_string(const char *str);
extern HttpRequest *request;
HttpResponse HttpServer::handleRequest(const HttpRequest& request) {
HttpResponse response;
response.status_line.protocol_version = "HTTP/1.1";
unique_ptr<string> uri = move(request.request_line->uri);
syslog(LOG_INFO, "Responding to request for: %s", uri->c_str());
struct stat st;
if (stat(uri->c_str(), &st) == -1) {
if (errno == ENOENT) {
response.status_line.status_code = 404;
response.status_line.reason_phrase = "Not Found!";
return response;
}
response.status_line.status_code = 500;
syslog(LOG_ERR, "Error stat-ing directory %s: %m", uri->c_str());
response.status_line.reason_phrase = "Error stat-ing directory";
return response;
}
stringstream res_ss;
if (st.st_mode & S_IFDIR) {
if (uri->at(uri->size()-1) != '/') {
uri->push_back('/');
}
DIR* d;
if ((d = opendir(uri->c_str())) == NULL) {
response.status_line.status_code = 500;
syslog(LOG_ERR, "Error opening directory %s: %m", uri->c_str());
response.status_line.reason_phrase = "Error opening directory";
return response;
}
struct dirent* dir;
while ((dir = readdir(d))) {
string d_name(dir->d_name);
if (d_name == "." || d_name == "..") {
continue;
}
struct stat st2;
string d_uri;
stringstream ss;
ss << *uri << d_name;
d_uri = ss.str();
if (stat(d_uri.c_str(), &st2) == -1) {
syslog(LOG_ERR, "Could not stat file in directory; %m");
continue;
}
if (st.st_mode & S_IFDIR) {
res_ss << "<a href=" << d_uri << ">"
<< d_uri << "</a><br>" << endl;
}
}
}
else if (st.st_mode & S_IFREG) {
ifstream fin{*uri, ifstream::in};
string line;
while (getline(fin, line)) {
res_ss << line << " <br>" << endl;
}
}
else {
res_ss << "somethin' else";
}
response.status_line.status_code = 200;
response.status_line.reason_phrase = "OK";
response.message = res_ss.str();
return response;
}
HttpRequest HttpServer::parseRequest(const string& requestString) {
yy_scan_string(requestString.c_str());
yyparse();
yylex_destroy();
return move(*request);
}
HttpResponse HttpServer::handleConnection() {
std::string msg;
sock_.Read(&msg);
return handleRequest(parseRequest(msg));
}
void HttpServer::sendResponse(const HttpResponse& response) {
sock_.Write(response.format());
}
void HttpServer::serve() {
sock_.Bind(SERV_PORT);
sock_.Listen();
for ( ; ; ) {
socklen_t clilen;
sock_.Accept(&clilen);
int pid = fork();
if (pid < 0) {
// error
syslog(LOG_WARNING, "failed to fork child to handle connection");
} else if (pid == 0) {
// child
close(sock_.getListenFd());
sendResponse(handleConnection());
exit(0);
}
else {
// parent
close(sock_.getConnFd());
}
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
#include <cstdlib>
#include <getopt.h>
#include <cassert>
#include <cmath>
#include "ntHashIterator.hpp"
#include "Uncompress.h"
#ifdef _OPENMP
# include <omp.h>
#endif
#define PROGRAM "ntcard"
static const char VERSION_MESSAGE[] =
PROGRAM " Version 1.0.0 \n"
"Written by Hamid Mohamadi.\n"
"Copyright 2016 Canada's Michael Smith Genome Science Centre\n";
static const char USAGE_MESSAGE[] =
"Usage: " PROGRAM " [OPTION]... FILES...\n"
"Estimates the number of k-mers in FILES(>=1).\n"
"Accepatble file formats: fastq, fasta, sam, bam, gz, bz, zip.\n"
"\n"
" Options:\n"
"\n"
" -t, --threads=N use N parallel threads [1]\n"
" -k, --kmer=N the length of kmer [64]\n"
" -c, --cov=N the maximum coverage of kmer in output [64]\n"
" --help display this help and exit\n"
" --version output version information and exit\n"
"\n"
"Report bugs to hmohamadi@bcgsc.ca.\n";
using namespace std;
namespace opt {
unsigned nThrd=1;
unsigned kmLen=64;
unsigned rBuck;
unsigned rBits=27;
unsigned sBits=11;
unsigned sMask;
unsigned covMax=64;
unsigned nSamp=2;
unsigned nK=0;
bool samH=true;
}
static const char shortopts[] = "t:s:r:k:c:l:f:";
enum { OPT_HELP = 1, OPT_VERSION };
static const struct option longopts[] = {
{ "threads", required_argument, NULL, 't' },
{ "kmer", required_argument, NULL, 'k' },
{ "cov", required_argument, NULL, 'c' },
{ "rbit", required_argument, NULL, 'r' },
{ "sbit", required_argument, NULL, 's' },
{ "help", no_argument, NULL, OPT_HELP },
{ "version", no_argument, NULL, OPT_VERSION },
{ NULL, 0, NULL, 0 }
};
size_t getInf(const char* inFile) {
std::ifstream in(inFile, std::ifstream::ate | std::ifstream::binary);
return in.tellg();
}
unsigned getftype(std::ifstream &in, std::string &samSeq) {
std::string hseq;
getline(in,hseq);
if(hseq[0]=='>') {
return 1;
}
if(hseq[0]=='@') {
if( (hseq[1]=='H'&& hseq[2]=='D') ||
(hseq[1]=='S'&& hseq[2]=='Q') ||
(hseq[1]=='R'&& hseq[2]=='G') ||
(hseq[1]=='P'&& hseq[2]=='G') ||
(hseq[1]=='C'&& hseq[2]=='O') ) {
return 2;
}
else
return 0;
}
opt::samH=false;
samSeq=hseq;
return 2;
}
inline void ntComp(const uint64_t hVal, uint16_t *t_Counter) {
uint64_t indBit=opt::nSamp;
if(hVal>>(63-opt::sBits) == 1) indBit=0;
if(hVal>>(64-opt::sBits) == opt::sMask) indBit=1;
if(indBit < opt::nSamp) {
size_t shVal=hVal&(opt::rBuck-1);
#pragma omp atomic
++t_Counter[indBit*opt::rBuck+shVal];
}
}
inline void ntRead(const string &seq, const std::vector<unsigned> &kList, uint16_t *t_Counter, size_t totKmer[]) {
for(unsigned k=0; k<kList.size(); k++) {
ntHashIterator itr(seq, kList[k]);
while (itr != itr.end()) {
ntComp((*itr),t_Counter+k*opt::nSamp*opt::rBuck);
++itr;
++totKmer[k];
}
}
}
void getEfq(std::ifstream &in, const std::vector<unsigned> &kList, uint16_t *t_Counter, size_t totKmer[]) {
bool good = true;
for(string seq, hseq; good;) {
good = static_cast<bool>(getline(in, seq));
good = static_cast<bool>(getline(in, hseq));
good = static_cast<bool>(getline(in, hseq));
if(good)
ntRead(seq, kList, t_Counter, totKmer);
good = static_cast<bool>(getline(in, hseq));
}
}
void getEfa(std::ifstream &in, const std::vector<unsigned> &kList, uint16_t *t_Counter, size_t totKmer[]) {
bool good = true;
for(string seq, hseq; good;) {
string line;
good = static_cast<bool>(getline(in, seq));
while(good&&seq[0]!='>') {
line+=seq;
good = static_cast<bool>(getline(in, seq));
}
ntRead(line, kList, t_Counter, totKmer);
}
}
void getEsm(std::ifstream &in, const std::vector<unsigned> &kList, const std::string &samSeq, uint16_t *t_Counter, size_t totKmer[]) {
std::string samLine,seq;
std::string s1,s2,s3,s4,s5,s6,s7,s8,s9,s11;
if(opt::samH) {
while(getline(in,samLine))
if (samLine[0]!='@') break;
}
else
samLine=samSeq;
do {
std::istringstream iss(samLine);
iss>>s1>>s2>>s3>>s4>>s5>>s6>>s7>>s8>>s9>>seq>>s11;
ntRead(seq, kList, t_Counter, totKmer);
} while(getline(in,samLine));
}
void compEst(const uint16_t *t_Counter, double &F0Mean, double fMean[]) {
unsigned p[opt::nSamp][65536];
for(size_t i=0; i<opt::nSamp; i++)
for(size_t j=0; j<65536; j++)
p[i][j]=0;
for(size_t i=0; i<opt::nSamp; i++)
for(size_t j=0; j<opt::rBuck; j++)
++p[i][t_Counter[i*opt::rBuck+j]];
double pMean[65536];
for(size_t i=0; i<65536; i++) pMean[i]=0.0;
for(size_t i=0; i<65536; i++) {
for(size_t j=0; j<opt::nSamp; j++)
pMean[i]+=p[j][i];
pMean[i] /= 1.0*opt::nSamp;
}
F0Mean= (ssize_t)((opt::rBits*log(2)-log(pMean[0])) * 1.0* ((size_t)1<<(opt::sBits+opt::rBits)));
for(size_t i=0; i<65536; i++) fMean[i]=0;
fMean[1]= -1.0*pMean[1]/(pMean[0]*(log(pMean[0])-opt::rBits*log(2)));
for(size_t i=2; i<65536; i++) {
double sum=0.0;
for(size_t j=1; j<i; j++)
sum+=j*pMean[i-j]*fMean[j];
fMean[i]=-1.0*pMean[i]/(pMean[0]*(log(pMean[0])-opt::rBits*log(2)))-sum/(i*pMean[0]);
}
for(size_t i=1; i<65536; i++)
fMean[i]=abs((ssize_t)(fMean[i]*F0Mean));
}
int main(int argc, char** argv) {
double sTime = omp_get_wtime();
vector<unsigned> kList;
bool die = false;
for (int c; (c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1;) {
std::istringstream arg(optarg != NULL ? optarg : "");
switch (c) {
case '?':
die = true;
break;
case 't':
arg >> opt::nThrd;
break;
case 's':
arg >> opt::sBits;
break;
case 'r':
arg >> opt::rBits;
break;
case 'c':
arg >> opt::covMax;
break;
case 'k':
{
std::string token;
while(getline(arg, token, ',')) {
unsigned myK;
std::stringstream ss(token);
ss >> myK;
kList.push_back(myK);
++opt::nK;
}
break;
}
case OPT_HELP:
std::cerr << USAGE_MESSAGE;
exit(EXIT_SUCCESS);
case OPT_VERSION:
std::cerr << VERSION_MESSAGE;
exit(EXIT_SUCCESS);
}
if (optarg != NULL && !arg.eof()) {
std::cerr << PROGRAM ": invalid option: `-"
<< (char)c << optarg << "'\n";
exit(EXIT_FAILURE);
}
}
if (argc - optind < 1) {
std::cerr << PROGRAM ": missing arguments\n";
die = true;
}
if (die) {
std::cerr << "Try `" << PROGRAM << " --help' for more information.\n";
exit(EXIT_FAILURE);
}
vector<string> inFiles;
for (int i = optind; i < argc; ++i) {
string file(argv[i]);
if(file[0]=='@') {
string inName;
ifstream inList(file.substr(1,file.length()).c_str());
while(getline(inList,inName))
inFiles.push_back(inName);
}
else
inFiles.push_back(file);
}
size_t totalSize=0;
for (unsigned file_i = 0; file_i < inFiles.size(); ++file_i)
totalSize += getInf(inFiles[file_i].c_str());
if(totalSize<50000000000) opt::sBits=7;
size_t totalKmers[kList.size()];
for(unsigned k=0; k<kList.size(); k++) totalKmers[k]=0;
opt::rBuck = ((size_t)1) << opt::rBits;
opt::sMask = (((size_t)1) << (opt::sBits-1))-1;
uint16_t *t_Counter = new uint16_t [opt::nK*opt::nSamp*opt::rBuck]();
#ifdef _OPENMP
omp_set_num_threads(opt::nThrd);
#endif
#pragma omp parallel for schedule(dynamic)
for (unsigned file_i = 0; file_i < inFiles.size(); ++file_i) {
size_t totKmer[kList.size()];
for(unsigned k=0; k<kList.size(); k++) totKmer[k]=0;
std::ifstream in(inFiles[file_i].c_str());
std::string samSeq;
unsigned ftype = getftype(in,samSeq);
if(ftype==0)
getEfq(in, kList, t_Counter, totKmer);
else if (ftype==1)
getEfa(in, kList, t_Counter, totKmer);
else if (ftype==2)
getEsm(in, kList, samSeq, t_Counter, totKmer);
in.close();
for(unsigned k=0; k<kList.size(); k++)
#pragma omp atomic
totalKmers[k]+=totKmer[k];
}
std::ofstream histFiles[opt::nK];
for (unsigned k=0; k<opt::nK; k++) {
std::stringstream hstm;
hstm << "freq_k" << kList[k] << ".hist";
histFiles[k].open((hstm.str()).c_str());
}
#pragma omp parallel for schedule(dynamic)
for(unsigned k=0; k<kList.size(); k++) {
double F0Mean=0.0;
double fMean[65536];
compEst(t_Counter+k*opt::nSamp*opt::rBuck, F0Mean, fMean);
histFiles[k] << "F1\t" << totalKmers[k] << "\n";
histFiles[k] << "F0\t" << (size_t)F0Mean << "\n";
for(size_t i=1; i<= opt::covMax; i++)
histFiles[k] << "f" << i << "\t" << (size_t)fMean[i] << "\n";
}
for (unsigned k=0; k<opt::nK; k++)
histFiles[k].close();
delete [] t_Counter;
std::cerr << "Runtime(sec): " <<setprecision(4) << fixed << omp_get_wtime() - sTime << "\n";
return 0;
}
<commit_msg>Added feature: specify prefix for output histogram files<commit_after>#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
#include <cstdlib>
#include <getopt.h>
#include <cassert>
#include <cmath>
#include "ntHashIterator.hpp"
#include "Uncompress.h"
#ifdef _OPENMP
# include <omp.h>
#endif
#define PROGRAM "ntcard"
static const char VERSION_MESSAGE[] =
PROGRAM " Version 1.0.0 \n"
"Written by Hamid Mohamadi.\n"
"Copyright 2016 Canada's Michael Smith Genome Science Centre\n";
static const char USAGE_MESSAGE[] =
"Usage: " PROGRAM " [OPTION]... FILES...\n"
"Estimates the number of k-mers in FILES(>=1).\n"
"Accepatble file formats: fastq, fasta, sam, bam, gz, bz, zip.\n"
"\n"
" Options:\n"
"\n"
" -t, --threads=N use N parallel threads [1]\n"
" -k, --kmer=N the length of kmer [64]\n"
" -c, --cov=N the maximum coverage of kmer in output [64]\n"
" -p, --pref=STRING the prefix for output file name [freq]\n"
" --help display this help and exit\n"
" --version output version information and exit\n"
"\n"
"Report bugs to hmohamadi@bcgsc.ca.\n";
using namespace std;
namespace opt {
unsigned nThrd=1;
unsigned kmLen=64;
unsigned rBuck;
unsigned rBits=27;
unsigned sBits=11;
unsigned sMask;
unsigned covMax=64;
unsigned nSamp=2;
unsigned nK=0;
string prefix;
bool samH=true;
}
static const char shortopts[] = "t:s:r:k:c:l:p:f:";
enum { OPT_HELP = 1, OPT_VERSION };
static const struct option longopts[] = {
{ "threads", required_argument, NULL, 't' },
{ "kmer", required_argument, NULL, 'k' },
{ "cov", required_argument, NULL, 'c' },
{ "rbit", required_argument, NULL, 'r' },
{ "sbit", required_argument, NULL, 's' },
{ "pref", required_argument, NULL, 'p' },
{ "help", no_argument, NULL, OPT_HELP },
{ "version", no_argument, NULL, OPT_VERSION },
{ NULL, 0, NULL, 0 }
};
size_t getInf(const char* inFile) {
std::ifstream in(inFile, std::ifstream::ate | std::ifstream::binary);
return in.tellg();
}
unsigned getftype(std::ifstream &in, std::string &samSeq) {
std::string hseq;
getline(in,hseq);
if(hseq[0]=='>') {
return 1;
}
if(hseq[0]=='@') {
if( (hseq[1]=='H'&& hseq[2]=='D') ||
(hseq[1]=='S'&& hseq[2]=='Q') ||
(hseq[1]=='R'&& hseq[2]=='G') ||
(hseq[1]=='P'&& hseq[2]=='G') ||
(hseq[1]=='C'&& hseq[2]=='O') ) {
return 2;
}
else
return 0;
}
opt::samH=false;
samSeq=hseq;
return 2;
}
inline void ntComp(const uint64_t hVal, uint16_t *t_Counter) {
uint64_t indBit=opt::nSamp;
if(hVal>>(63-opt::sBits) == 1) indBit=0;
if(hVal>>(64-opt::sBits) == opt::sMask) indBit=1;
if(indBit < opt::nSamp) {
size_t shVal=hVal&(opt::rBuck-1);
#pragma omp atomic
++t_Counter[indBit*opt::rBuck+shVal];
}
}
inline void ntRead(const string &seq, const std::vector<unsigned> &kList, uint16_t *t_Counter, size_t totKmer[]) {
for(unsigned k=0; k<kList.size(); k++) {
ntHashIterator itr(seq, kList[k]);
while (itr != itr.end()) {
ntComp((*itr),t_Counter+k*opt::nSamp*opt::rBuck);
++itr;
++totKmer[k];
}
}
}
void getEfq(std::ifstream &in, const std::vector<unsigned> &kList, uint16_t *t_Counter, size_t totKmer[]) {
bool good = true;
for(string seq, hseq; good;) {
good = static_cast<bool>(getline(in, seq));
good = static_cast<bool>(getline(in, hseq));
good = static_cast<bool>(getline(in, hseq));
if(good)
ntRead(seq, kList, t_Counter, totKmer);
good = static_cast<bool>(getline(in, hseq));
}
}
void getEfa(std::ifstream &in, const std::vector<unsigned> &kList, uint16_t *t_Counter, size_t totKmer[]) {
bool good = true;
for(string seq, hseq; good;) {
string line;
good = static_cast<bool>(getline(in, seq));
while(good&&seq[0]!='>') {
line+=seq;
good = static_cast<bool>(getline(in, seq));
}
ntRead(line, kList, t_Counter, totKmer);
}
}
void getEsm(std::ifstream &in, const std::vector<unsigned> &kList, const std::string &samSeq, uint16_t *t_Counter, size_t totKmer[]) {
std::string samLine,seq;
std::string s1,s2,s3,s4,s5,s6,s7,s8,s9,s11;
if(opt::samH) {
while(getline(in,samLine))
if (samLine[0]!='@') break;
}
else
samLine=samSeq;
do {
std::istringstream iss(samLine);
iss>>s1>>s2>>s3>>s4>>s5>>s6>>s7>>s8>>s9>>seq>>s11;
ntRead(seq, kList, t_Counter, totKmer);
} while(getline(in,samLine));
}
void compEst(const uint16_t *t_Counter, double &F0Mean, double fMean[]) {
unsigned p[opt::nSamp][65536];
for(size_t i=0; i<opt::nSamp; i++)
for(size_t j=0; j<65536; j++)
p[i][j]=0;
for(size_t i=0; i<opt::nSamp; i++)
for(size_t j=0; j<opt::rBuck; j++)
++p[i][t_Counter[i*opt::rBuck+j]];
double pMean[65536];
for(size_t i=0; i<65536; i++) pMean[i]=0.0;
for(size_t i=0; i<65536; i++) {
for(size_t j=0; j<opt::nSamp; j++)
pMean[i]+=p[j][i];
pMean[i] /= 1.0*opt::nSamp;
}
F0Mean= (ssize_t)((opt::rBits*log(2)-log(pMean[0])) * 1.0* ((size_t)1<<(opt::sBits+opt::rBits)));
for(size_t i=0; i<65536; i++) fMean[i]=0;
fMean[1]= -1.0*pMean[1]/(pMean[0]*(log(pMean[0])-opt::rBits*log(2)));
for(size_t i=2; i<65536; i++) {
double sum=0.0;
for(size_t j=1; j<i; j++)
sum+=j*pMean[i-j]*fMean[j];
fMean[i]=-1.0*pMean[i]/(pMean[0]*(log(pMean[0])-opt::rBits*log(2)))-sum/(i*pMean[0]);
}
for(size_t i=1; i<65536; i++)
fMean[i]=abs((ssize_t)(fMean[i]*F0Mean));
}
int main(int argc, char** argv) {
double sTime = omp_get_wtime();
vector<unsigned> kList;
bool die = false;
for (int c; (c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1;) {
std::istringstream arg(optarg != NULL ? optarg : "");
switch (c) {
case '?':
die = true;
break;
case 't':
arg >> opt::nThrd;
break;
case 's':
arg >> opt::sBits;
break;
case 'r':
arg >> opt::rBits;
break;
case 'c':
arg >> opt::covMax;
break;
case 'p':
arg >> opt::prefix;
break;
case 'k':
{
std::string token;
while(getline(arg, token, ',')) {
unsigned myK;
std::stringstream ss(token);
ss >> myK;
kList.push_back(myK);
++opt::nK;
}
break;
}
case OPT_HELP:
std::cerr << USAGE_MESSAGE;
exit(EXIT_SUCCESS);
case OPT_VERSION:
std::cerr << VERSION_MESSAGE;
exit(EXIT_SUCCESS);
}
if (optarg != NULL && !arg.eof()) {
std::cerr << PROGRAM ": invalid option: `-"
<< (char)c << optarg << "'\n";
exit(EXIT_FAILURE);
}
}
if (argc - optind < 1) {
std::cerr << PROGRAM ": missing arguments\n";
die = true;
}
if (die) {
std::cerr << "Try `" << PROGRAM << " --help' for more information.\n";
exit(EXIT_FAILURE);
}
vector<string> inFiles;
for (int i = optind; i < argc; ++i) {
string file(argv[i]);
if(file[0]=='@') {
string inName;
ifstream inList(file.substr(1,file.length()).c_str());
while(getline(inList,inName))
inFiles.push_back(inName);
}
else
inFiles.push_back(file);
}
size_t totalSize=0;
for (unsigned file_i = 0; file_i < inFiles.size(); ++file_i)
totalSize += getInf(inFiles[file_i].c_str());
if(totalSize<50000000000) opt::sBits=7;
size_t totalKmers[kList.size()];
for(unsigned k=0; k<kList.size(); k++) totalKmers[k]=0;
opt::rBuck = ((size_t)1) << opt::rBits;
opt::sMask = (((size_t)1) << (opt::sBits-1))-1;
uint16_t *t_Counter = new uint16_t [opt::nK*opt::nSamp*opt::rBuck]();
#ifdef _OPENMP
omp_set_num_threads(opt::nThrd);
#endif
#pragma omp parallel for schedule(dynamic)
for (unsigned file_i = 0; file_i < inFiles.size(); ++file_i) {
size_t totKmer[kList.size()];
for(unsigned k=0; k<kList.size(); k++) totKmer[k]=0;
std::ifstream in(inFiles[file_i].c_str());
std::string samSeq;
unsigned ftype = getftype(in,samSeq);
if(ftype==0)
getEfq(in, kList, t_Counter, totKmer);
else if (ftype==1)
getEfa(in, kList, t_Counter, totKmer);
else if (ftype==2)
getEsm(in, kList, samSeq, t_Counter, totKmer);
in.close();
for(unsigned k=0; k<kList.size(); k++)
#pragma omp atomic
totalKmers[k]+=totKmer[k];
}
std::ofstream histFiles[opt::nK];
for (unsigned k=0; k<opt::nK; k++) {
std::stringstream hstm;
if(opt::prefix.empty())
hstm << "freq_k" << kList[k] << ".hist";
else
hstm << opt::prefix << "_k" << kList[k] << ".hist";
histFiles[k].open((hstm.str()).c_str());
}
#pragma omp parallel for schedule(dynamic)
for(unsigned k=0; k<kList.size(); k++) {
double F0Mean=0.0;
double fMean[65536];
compEst(t_Counter+k*opt::nSamp*opt::rBuck, F0Mean, fMean);
histFiles[k] << "F1\t" << totalKmers[k] << "\n";
histFiles[k] << "F0\t" << (size_t)F0Mean << "\n";
for(size_t i=1; i<= opt::covMax; i++)
histFiles[k] << "f" << i << "\t" << (size_t)fMean[i] << "\n";
}
for (unsigned k=0; k<opt::nK; k++)
histFiles[k].close();
delete [] t_Counter;
std::cerr << "Runtime(sec): " <<setprecision(4) << fixed << omp_get_wtime() - sTime << "\n";
return 0;
}
<|endoftext|>
|
<commit_before>/*
** Author(s):
** - Herve Cuche <hcuche@aldebaran-robotics.com>
**
** Copyright (C) 2012 Aldebaran Robotics
*/
#include <iostream>
#include <string>
#include <boost/program_options.hpp>
#include <qi/os.hpp>
#include <qimessaging/session.hpp>
#include <qimessaging/server.hpp>
#include <qimessaging/object.hpp>
//#include "qiservicetest.hpp"
std::string reply(const std::string &msg) {
return msg + "bim";
}
namespace po = boost::program_options;
int main(int argc, char *argv[])
{
// declare the program options
po::options_description desc("Usage:\n qi-service masterAddress [options]\nOptions");
desc.add_options()
("help", "Print this help.")
("master-address",
po::value<std::string>()->default_value(std::string("127.0.0.1:5555")),
"The master address");
// allow master address to be specified as the first arg
po::positional_options_description pos;
pos.add("master-address", 1);
// parse and store
po::variables_map vm;
try
{
po::store(po::command_line_parser(argc, argv).
options(desc).positional(pos).run(), vm);
po::notify(vm);
if (vm.count("help"))
{
std::cout << desc << "\n";
return 0;
}
if (vm.count("master-address") == 1)
{
qi::Session session;
qi::Object obj;
qi::Server srv;
obj.advertiseMethod("reply", &reply);
srv.advertiseService("serviceTest", &obj);
srv.start("127.0.0.1", 9571, session._nthd);
//qi::ServiceTest st;
//st.start("127.0.0.1:9571");
std::cout << "ready." << std::endl;
qi::EndpointInfo e;
e.ip = "127.0.0.1";
e.port = 9571;
e.type = "tcp";
std::string masterAddress = vm["master-address"].as<std::string>();
session.setName("serviceTest");
session.setDestination("qi.master");
session.connect(masterAddress);
session.waitForConnected();
session.registerEndpoint(e);
while (1)
qi::os::sleep(1);
session.unregisterEndpoint(e);
}
else
{
std::cout << desc << "\n";
}
}
catch (const boost::program_options::error&)
{
std::cout << desc << "\n";
}
return 0;
}
<commit_msg>qiservicetest: add a debug printf<commit_after>/*
** Author(s):
** - Herve Cuche <hcuche@aldebaran-robotics.com>
**
** Copyright (C) 2012 Aldebaran Robotics
*/
#include <iostream>
#include <string>
#include <boost/program_options.hpp>
#include <qi/os.hpp>
#include <qimessaging/session.hpp>
#include <qimessaging/server.hpp>
#include <qimessaging/object.hpp>
//#include "qiservicetest.hpp"
std::string reply(const std::string &msg) {
std::cout << "Message recv:" << msg << std::endl;
return msg + "bim";
}
namespace po = boost::program_options;
int main(int argc, char *argv[])
{
// declare the program options
po::options_description desc("Usage:\n qi-service masterAddress [options]\nOptions");
desc.add_options()
("help", "Print this help.")
("master-address",
po::value<std::string>()->default_value(std::string("127.0.0.1:5555")),
"The master address");
// allow master address to be specified as the first arg
po::positional_options_description pos;
pos.add("master-address", 1);
// parse and store
po::variables_map vm;
try
{
po::store(po::command_line_parser(argc, argv).
options(desc).positional(pos).run(), vm);
po::notify(vm);
if (vm.count("help"))
{
std::cout << desc << "\n";
return 0;
}
if (vm.count("master-address") == 1)
{
qi::Session session;
qi::Object obj;
qi::Server srv;
obj.advertiseMethod("reply", &reply);
srv.advertiseService("serviceTest", &obj);
srv.start("127.0.0.1", 9571, session._nthd);
//qi::ServiceTest st;
//st.start("127.0.0.1:9571");
std::cout << "ready." << std::endl;
qi::EndpointInfo e;
e.ip = "127.0.0.1";
e.port = 9571;
e.type = "tcp";
std::string masterAddress = vm["master-address"].as<std::string>();
session.setName("serviceTest");
session.setDestination("qi.master");
session.connect(masterAddress);
session.waitForConnected();
session.registerEndpoint(e);
while (1)
qi::os::sleep(1);
session.unregisterEndpoint(e);
}
else
{
std::cout << desc << "\n";
}
}
catch (const boost::program_options::error&)
{
std::cout << desc << "\n";
}
return 0;
}
<|endoftext|>
|
<commit_before>#pragma once
#include <cstdint>
#include <chrono>
#include <ratio>
#include <uv.h>
#include "stream.hpp"
#include "error.hpp"
namespace uvw {
class Tcp final: public Stream<Tcp> {
static void protoConnect(uv_connect_t* req, int status) {
auto handle = req->handle;
delete req;
static_cast<Tcp*>(handle->data)->connCb(UVWError{status});
}
public:
using Time = std::chrono::duration<uint64_t>;
using CallbackConnect = std::function<void(UVWError)>;
enum { IPv4, IPv6 };
explicit Tcp(uv_loop_t *loop): Stream<Tcp>{&handle} {
uv_tcp_init(loop, &handle);
}
~Tcp() {
close([](UVWError){});
}
bool noDelay(bool value = false) noexcept {
return (uv_tcp_nodelay(&handle, value ? 1 : 0) == 0);
}
bool keepAlive(bool enable = false, Time time = Time{0}) noexcept {
return (uv_tcp_keepalive(&handle, enable ? 1 : 0, time.count()) == 0);
}
template<int>
void connect(std::string, int, CallbackConnect) noexcept;
private:
CallbackConnect connCb;
uv_tcp_t handle;
};
template<>
void Tcp::connect<Tcp::IPv4>(std::string ip, int port, CallbackConnect cb) noexcept {
uv_connect_t *conn = new uv_connect_t;
sockaddr_in addr;
uv_ip4_addr(ip.c_str(), port, &addr);
connCb = cb;
auto err = uv_tcp_connect(conn, &handle, reinterpret_cast<const sockaddr*>(&addr), &protoConnect);
if(err) {
connCb(UVWError{err});
}
}
template<>
void Tcp::connect<Tcp::IPv6>(std::string ip, int port, CallbackConnect cb) noexcept {
uv_connect_t *conn = new uv_connect_t;
sockaddr_in6 addr;
uv_ip6_addr(ip.c_str(), port, &addr);
connCb = cb;
auto err = uv_tcp_connect(conn, &handle, reinterpret_cast<const sockaddr*>(&addr), &protoConnect);
if(err) {
connCb(UVWError{err});
}
}
}
<commit_msg>fix dependencies<commit_after>#pragma once
#include <string>
#include <cstdint>
#include <chrono>
#include <ratio>
#include <uv.h>
#include "stream.hpp"
#include "error.hpp"
namespace uvw {
class Tcp final: public Stream<Tcp> {
static void protoConnect(uv_connect_t* req, int status) {
auto handle = req->handle;
delete req;
static_cast<Tcp*>(handle->data)->connCb(UVWError{status});
}
public:
using Time = std::chrono::duration<uint64_t>;
using CallbackConnect = std::function<void(UVWError)>;
enum { IPv4, IPv6 };
explicit Tcp(uv_loop_t *loop): Stream<Tcp>{&handle} {
uv_tcp_init(loop, &handle);
}
~Tcp() {
close([](UVWError){});
}
bool noDelay(bool value = false) noexcept {
return (uv_tcp_nodelay(&handle, value ? 1 : 0) == 0);
}
bool keepAlive(bool enable = false, Time time = Time{0}) noexcept {
return (uv_tcp_keepalive(&handle, enable ? 1 : 0, time.count()) == 0);
}
template<int>
void connect(std::string, int, CallbackConnect) noexcept;
private:
CallbackConnect connCb;
uv_tcp_t handle;
};
template<>
void Tcp::connect<Tcp::IPv4>(std::string ip, int port, CallbackConnect cb) noexcept {
uv_connect_t *conn = new uv_connect_t;
sockaddr_in addr;
uv_ip4_addr(ip.c_str(), port, &addr);
connCb = cb;
auto err = uv_tcp_connect(conn, &handle, reinterpret_cast<const sockaddr*>(&addr), &protoConnect);
if(err) {
connCb(UVWError{err});
}
}
template<>
void Tcp::connect<Tcp::IPv6>(std::string ip, int port, CallbackConnect cb) noexcept {
uv_connect_t *conn = new uv_connect_t;
sockaddr_in6 addr;
uv_ip6_addr(ip.c_str(), port, &addr);
connCb = cb;
auto err = uv_tcp_connect(conn, &handle, reinterpret_cast<const sockaddr*>(&addr), &protoConnect);
if(err) {
connCb(UVWError{err});
}
}
}
<|endoftext|>
|
<commit_before>/* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| https://www.mrpt.org/ |
| |
| Copyright (c) 2005-2019, Individual contributors, see AUTHORS file |
| See: https://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See: https://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include <gtest/gtest.h>
#include <mrpt/maps/CLogOddsGridMapLUT.h>
#include <numeric>
template <typename cell_t>
void test_monotonic()
{
mrpt::maps::CLogOddsGridMapLUT<cell_t> lut;
float last_p=.0f;
const auto i_init = std::numeric_limits<cell_t>::min();
const auto i_end = std::numeric_limits<cell_t>::max();
for (int64_t i=i_init;i<=i_end;i++)
{
// Ensure LUT is monotonic:
const float new_p = lut.l2p(i);
EXPECT_GE(new_p, last_p) << " i=" << i;
last_p = new_p;
}
EXPECT_NEAR(lut.l2p(i_init), .0f, 0.05);
EXPECT_NEAR(lut.l2p(i_end), 1.0f, 0.05);
// Expect internal table to be monotonic:
int64_t last_logodd = std::numeric_limits<int64_t>::min();
for (size_t idx = 0; idx < lut.p2lTable.size(); idx++)
{
const int64_t next_logodd = lut.p2lTable[idx];
EXPECT_GE(next_logodd, last_logodd) << "idx=" << idx;
last_logodd = next_logodd;
}
}
TEST(CLogOddsGridMapLUT, monotonic_8bit)
{
test_monotonic<int8_t>();
}
TEST(CLogOddsGridMapLUT, monotonic_16bit)
{
test_monotonic<int16_t>();
}
<commit_msg>clang-format fix<commit_after>/* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| https://www.mrpt.org/ |
| |
| Copyright (c) 2005-2019, Individual contributors, see AUTHORS file |
| See: https://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See: https://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include <gtest/gtest.h>
#include <mrpt/maps/CLogOddsGridMapLUT.h>
#include <numeric>
template <typename cell_t>
void test_monotonic()
{
mrpt::maps::CLogOddsGridMapLUT<cell_t> lut;
float last_p = .0f;
const auto i_init = std::numeric_limits<cell_t>::min();
const auto i_end = std::numeric_limits<cell_t>::max();
for (int64_t i = i_init; i <= i_end; i++)
{
// Ensure LUT is monotonic:
const float new_p = lut.l2p(i);
EXPECT_GE(new_p, last_p) << " i=" << i;
last_p = new_p;
}
EXPECT_NEAR(lut.l2p(i_init), .0f, 0.05);
EXPECT_NEAR(lut.l2p(i_end), 1.0f, 0.05);
// Expect internal table to be monotonic:
int64_t last_logodd = std::numeric_limits<int64_t>::min();
for (size_t idx = 0; idx < lut.p2lTable.size(); idx++)
{
const int64_t next_logodd = lut.p2lTable[idx];
EXPECT_GE(next_logodd, last_logodd) << "idx=" << idx;
last_logodd = next_logodd;
}
}
TEST(CLogOddsGridMapLUT, monotonic_8bit) { test_monotonic<int8_t>(); }
TEST(CLogOddsGridMapLUT, monotonic_16bit) { test_monotonic<int16_t>(); }
<|endoftext|>
|
<commit_before>#include "PuffinApp.h"
#include "Moose.h"
#include "AppFactory.h"
#include "ModulesApp.h"
#include "MooseSyntax.h"
//PUFFIN
//POSTPROCESSORS
#include "IMCFraction.h"
template<>
InputParameters validParams<PuffinApp>()
{
InputParameters params = validParams<MooseApp>();
return params;
}
PuffinApp::PuffinApp(InputParameters parameters) :
MooseApp(parameters)
{
Moose::registerObjects(_factory);
ModulesApp::registerObjects(_factory);
PuffinApp::registerObjects(_factory);
Moose::associateSyntax(_syntax, _action_factory);
ModulesApp::associateSyntax(_syntax, _action_factory);
PuffinApp::associateSyntax(_syntax, _action_factory);
}
PuffinApp::~PuffinApp()
{
}
// External entry point for dynamic application loading
extern "C" void PuffinApp__registerApps() { PuffinApp::registerApps(); }
void
PuffinApp::registerApps()
{
registerApp(PuffinApp);
}
// External entry point for dynamic object registration
extern "C" void PuffinApp__registerObjects(Factory & factory) { PuffinApp::registerObjects(factory); }
void
PuffinApp::registerObjects(Factory & factory)
{
// Register new stuff here
registerPostprocessor(IMCFraction);
}
// External entry point for dynamic syntax association
extern "C" void PuffinApp__associateSyntax(Syntax & syntax, ActionFactory & action_factory) { PuffinApp::associateSyntax(syntax, action_factory); }
void
PuffinApp::associateSyntax(Syntax & /*syntax*/, ActionFactory & /*action_factory*/)
{
}
<commit_msg>added PuffinApp.C and .h<commit_after>#include "PuffinApp.h"
#include "Moose.h"
#include "AppFactory.h"
#include "ModulesApp.h"
#include "MooseSyntax.h"
//PUFFIN
//POSTPROCESSORS
#include "IMCFraction.h"
//InitialConditions
#include "VarDepIC.h"
#include "UnitySubVarIC.h"
//Actions
#include "KKSMultiACKernelAction.h"
template<>
InputParameters validParams<PuffinApp>()
{
InputParameters params = validParams<MooseApp>();
return params;
}
PuffinApp::PuffinApp(InputParameters parameters) :
MooseApp(parameters)
{
Moose::registerObjects(_factory);
ModulesApp::registerObjects(_factory);
PuffinApp::registerObjects(_factory);
Moose::associateSyntax(_syntax, _action_factory);
ModulesApp::associateSyntax(_syntax, _action_factory);
PuffinApp::associateSyntax(_syntax, _action_factory);
}
PuffinApp::~PuffinApp()
{
}
// External entry point for dynamic application loading
extern "C" void PuffinApp__registerApps() { PuffinApp::registerApps(); }
void
PuffinApp::registerApps()
{
registerApp(PuffinApp);
}
// External entry point for dynamic object registration
extern "C" void PuffinApp__registerObjects(Factory & factory) { PuffinApp::registerObjects(factory); }
void
PuffinApp::registerObjects(Factory & factory)
{
// Register new stuff here
registerPostprocessor(IMCFraction);
registerInitialCondition(VarDepIC);
registerInitialCondition(UnitySubVarIC);
}
// External entry point for dynamic syntax association
extern "C" void PuffinApp__associateSyntax(Syntax & syntax, ActionFactory & action_factory) { PuffinApp::associateSyntax(syntax, action_factory); }
void
PuffinApp::associateSyntax(Syntax & syntax, ActionFactory & action_factory)
{
// Register Action stuff here
registerAction(KKSMultiACKernelAction, "add_kernel");
registerSyntax("KKSMultiACKernelAction","Kernels/KKSMultiACKernel");
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2010 - 2015 Leonid Kostrykin
*
* Chair of Medical Engineering (mediTEC)
* RWTH Aachen University
* Pauwelsstr. 20
* 52074 Aachen
* Germany
*
*/
#include <Carna/base/Spatial.h>
#include <Carna/base/Node.h>
#include <Carna/base/CarnaException.h>
namespace Carna
{
namespace base
{
// ----------------------------------------------------------------------------------
// Spatial
// ----------------------------------------------------------------------------------
Spatial::Spatial( const std::string& tag )
: myParent( nullptr )
, localTransform( math::identity4f() )
, myUserData( nullptr )
, movable( true )
, myTag( tag )
{
}
Spatial::~Spatial()
{
}
void Spatial::updateParent( Node& parent )
{
CARNA_ASSERT( &parent != this );
CARNA_ASSERT( parent.hasChild( *this ) );
myParent = &parent;
}
bool Spatial::hasParent() const
{
return myParent != nullptr;
}
Spatial* Spatial::detachFromParent()
{
CARNA_ASSERT( hasParent() );
Spatial* const result = myParent->detachChild( *this );
myParent = nullptr;
return result;
}
Node& Spatial::parent()
{
CARNA_ASSERT( hasParent() );
return *myParent;
}
const Node& Spatial::parent() const
{
CARNA_ASSERT( hasParent() );
return *myParent;
}
Node& Spatial::findRoot()
{
if( hasParent() )
{
return parent().findRoot();
}
else
{
Node* const node = dynamic_cast< Node* >( this );
CARNA_ASSERT( node != nullptr );
return *node;
}
}
const Node& Spatial::findRoot() const
{
if( hasParent() )
{
return parent().findRoot();
}
else
{
const Node* const node = dynamic_cast< const Node* >( this );
CARNA_ASSERT( node != nullptr );
return *node;
}
}
void Spatial::updateWorldTransform()
{
if( hasParent() )
{
myWorldTransform = myParent->worldTransform() * localTransform;
}
else
{
myWorldTransform = localTransform;
}
}
const math::Matrix4f& Spatial::worldTransform() const
{
return myWorldTransform;
}
void Spatial::removeUserData()
{
myUserData = nullptr;
CARNA_ASSERT( !hasUserData() );
}
bool Spatial::hasUserData() const
{
return myUserData != nullptr;
}
void Spatial::setMovable( bool movable )
{
this->movable = movable;
}
bool Spatial::isMovable() const
{
return movable;
}
void Spatial::invalidate()
{
if( hasParent() )
{
parent().invalidate();
}
}
void Spatial::setTag( const std::string& tag )
{
myTag = tag;
}
const std::string& Spatial::tag() const
{
return myTag;
}
} // namespace Carna :: base
} // namespace Carna
<commit_msg>Fixed bug in Spatial::detachFromParent.<commit_after>/*
* Copyright (C) 2010 - 2015 Leonid Kostrykin
*
* Chair of Medical Engineering (mediTEC)
* RWTH Aachen University
* Pauwelsstr. 20
* 52074 Aachen
* Germany
*
*/
#include <Carna/base/Spatial.h>
#include <Carna/base/Node.h>
#include <Carna/base/CarnaException.h>
namespace Carna
{
namespace base
{
// ----------------------------------------------------------------------------------
// Spatial
// ----------------------------------------------------------------------------------
Spatial::Spatial( const std::string& tag )
: myParent( nullptr )
, localTransform( math::identity4f() )
, myUserData( nullptr )
, movable( true )
, myTag( tag )
{
}
Spatial::~Spatial()
{
}
void Spatial::updateParent( Node& parent )
{
CARNA_ASSERT( &parent != this );
CARNA_ASSERT( parent.hasChild( *this ) );
myParent = &parent;
}
bool Spatial::hasParent() const
{
return myParent != nullptr;
}
Spatial* Spatial::detachFromParent()
{
if( hasParent() )
{
Spatial* const result = myParent->detachChild( *this );
myParent = nullptr;
return result;
}
else
{
return nullptr;
}
}
Node& Spatial::parent()
{
CARNA_ASSERT( hasParent() );
return *myParent;
}
const Node& Spatial::parent() const
{
CARNA_ASSERT( hasParent() );
return *myParent;
}
Node& Spatial::findRoot()
{
if( hasParent() )
{
return parent().findRoot();
}
else
{
Node* const node = dynamic_cast< Node* >( this );
CARNA_ASSERT( node != nullptr );
return *node;
}
}
const Node& Spatial::findRoot() const
{
if( hasParent() )
{
return parent().findRoot();
}
else
{
const Node* const node = dynamic_cast< const Node* >( this );
CARNA_ASSERT( node != nullptr );
return *node;
}
}
void Spatial::updateWorldTransform()
{
if( hasParent() )
{
myWorldTransform = myParent->worldTransform() * localTransform;
}
else
{
myWorldTransform = localTransform;
}
}
const math::Matrix4f& Spatial::worldTransform() const
{
return myWorldTransform;
}
void Spatial::removeUserData()
{
myUserData = nullptr;
CARNA_ASSERT( !hasUserData() );
}
bool Spatial::hasUserData() const
{
return myUserData != nullptr;
}
void Spatial::setMovable( bool movable )
{
this->movable = movable;
}
bool Spatial::isMovable() const
{
return movable;
}
void Spatial::invalidate()
{
if( hasParent() )
{
parent().invalidate();
}
}
void Spatial::setTag( const std::string& tag )
{
myTag = tag;
}
const std::string& Spatial::tag() const
{
return myTag;
}
} // namespace Carna :: base
} // namespace Carna
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 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 <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("HoboNickels");
// Client version number
#define CLIENT_VERSION_SUFFIX "-hobo"
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID "e43cb68"
# define GIT_COMMIT_DATE "Sat Dec 14 14:19:45 2013"
#endif
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>Update version.cpp<commit_after>// Copyright (c) 2012 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 <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("HoboNickels");
// Client version number
#define CLIENT_VERSION_SUFFIX "-hobo"
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID "a6ca3a92"
# define GIT_COMMIT_DATE "Tue Jan 07 18:52:00 2014"
#endif
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (C) 2006 by Tobias Koenig <tokoe@kde.org> *
* *
* This program 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 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 Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
#include "store.h"
#include "akonadi.h"
#include "akonadiconnection.h"
#include "handlerhelper.h"
#include "response.h"
#include "storage/datastore.h"
#include "storage/transaction.h"
#include "storage/itemqueryhelper.h"
#include "storage/selectquerybuilder.h"
#include "storage/parthelper.h"
#include "storage/dbconfig.h"
#include "storage/itemretriever.h"
#include "libs/imapparser_p.h"
#include "libs/protocol_p.h"
#include "imapstreamparser.h"
#include <QtCore/QStringList>
#include <QLocale>
#include <QDebug>
#include <QFile>
#include <boost/bind.hpp>
#include <algorithm>
using namespace Akonadi;
Store::Store( Scope::SelectionScope scope )
: Handler()
, mScope( scope )
, mPos( 0 )
, mPreviousRevision( -1 )
, mSize( 0 )
{
}
bool Store::replaceFlags( const PimItem &item, const QList<QByteArray> &flags )
{
Flag::List flagList = HandlerHelper::resolveFlags( flags );
DataStore *store = connection()->storageBackend();
Flag::List currentFlags = item.flags();
std::sort( flagList.begin(), flagList.end(), boost::bind( &Flag::id, _1 ) < boost::bind( &Flag::id, _2 ) );
std::sort( currentFlags.begin(), currentFlags.end(), boost::bind( &Flag::id, _1 ) < boost::bind( &Flag::id, _2 ) );
if ( flagList == currentFlags )
return false;
if ( !store->setItemFlags( item, flagList ) )
throw HandlerException( "Store::replaceFlags: Unable to set new item flags" );
return true;
}
bool Store::addFlags( const PimItem &item, const QList<QByteArray> &flags )
{
const Flag::List flagList = HandlerHelper::resolveFlags( flags );
DataStore *store = connection()->storageBackend();
if ( !store->appendItemFlags( item, flagList ) ) {
qDebug( "Store::addFlags: Unable to add new item flags" );
return false;
}
return true;
}
bool Store::deleteFlags( const PimItem &item, const QList<QByteArray> &flags )
{
DataStore *store = connection()->storageBackend();
QList<Flag> flagList;
for ( int i = 0; i < flags.count(); ++i ) {
Flag flag = Flag::retrieveByName( QString::fromUtf8( flags[ i ] ) );
if ( !flag.isValid() )
continue;
flagList.append( flag );
}
if ( !store->removeItemFlags( item, flagList ) ) {
qDebug( "Store::deleteFlags: Unable to remove item flags" );
return false;
}
return true;
}
bool Store::parseStream()
{
parseCommand();
DataStore *store = connection()->storageBackend();
Transaction transaction( store );
// Set the same modification time for each item.
const QDateTime modificationtime = QDateTime::currentDateTime().toUTC();
// retrieve selected items
SelectQueryBuilder<PimItem> qb;
ItemQueryHelper::scopeToQuery( mScope, connection(), qb );
if ( !qb.exec() )
return failureResponse( "Unable to retrieve items" );
PimItem::List pimItems = qb.result();
if ( pimItems.isEmpty() )
return failureResponse( "No items found" );
// check and update revisions
for ( int i = 0; i < pimItems.size(); ++i ) {
if ( mPreviousRevision >= 0 && pimItems.at( i ).rev() != (int)mPreviousRevision )
throw HandlerException( "Item was modified elsewhere, aborting STORE." );
pimItems[ i ].setRev( pimItems[ i ].rev() + 1 );
}
QSet<QByteArray> changes;
qint64 partSizes = 0;
bool invalidateCache = false;
// apply modifications
m_streamParser->beginList();
while ( !m_streamParser->atListEnd() ) {
// parse the command
QByteArray command = m_streamParser->readString();
if ( command.isEmpty() )
throw HandlerException( "Syntax error" );
Operation op = Replace;
bool silent = false;
if ( command.startsWith( '+' ) ) {
op = Add;
command = command.mid( 1 );
} else if ( command.startsWith( '-' ) ) {
op = Delete;
command = command.mid( 1 );
}
if ( command.endsWith( ".SILENT" ) ) {
command.chop( 7 );
silent = true;
}
// qDebug() << "STORE: handling command: " << command;
// handle commands that can be applied to more than one item
if ( command == AKONADI_PARAM_FLAGS ) {
bool flagsChanged = true;
const QList<QByteArray> flags = m_streamParser->readParenthesizedList();
// TODO move this iteration to an SQL query.
for ( int i = 0; i < pimItems.count(); ++i ) {
if ( op == Replace ) {
flagsChanged = replaceFlags( pimItems[ i ], flags );
} else if ( op == Add ) {
if ( !addFlags( pimItems[ i ], flags ) )
return failureResponse( "Unable to add item flags." );
} else if ( op == Delete ) {
if ( !deleteFlags( pimItems[ i ], flags ) )
return failureResponse( "Unable to remove item flags." );
}
// TODO what is this about?
if ( !silent ) {
sendPimItemResponse( pimItems[i] );
}
}
if ( flagsChanged )
changes << AKONADI_PARAM_FLAGS;
continue;
}
// handle commands that can only be applied to one item
if ( pimItems.size() > 1 )
throw HandlerException( "This Modification can only be applied to a single item" );
PimItem &item = pimItems.first();
if ( !item.isValid() )
throw HandlerException( "Invalid item in query result!?" );
if ( command == AKONADI_PARAM_REMOTEID ) {
const QString rid = m_streamParser->readUtf8String();
if ( item.remoteId() != rid ) {
if ( !connection()->isOwnerResource( item ) )
throw HandlerException( "Only resources can modify remote identifiers" );
item.setRemoteId( rid );
changes << AKONADI_PARAM_REMOTEID;
}
}
else if ( command == AKONADI_PARAM_REMOTEREVISION ) {
const QString remoteRevision = m_streamParser->readUtf8String();
if ( item.remoteRevision() != remoteRevision ) {
if ( !connection()->isOwnerResource( item ) )
throw HandlerException( "Only resources can modify remote revisions" );
item.setRemoteRevision( remoteRevision );
changes << AKONADI_PARAM_REMOTEREVISION;
}
}
else if ( command == AKONADI_PARAM_UNDIRTY ) {
m_streamParser->readString(); // read the 'false' string
item.setDirty( false );
}
else if ( command == AKONADI_PARAM_INVALIDATECACHE ) {
invalidateCache = true;
}
else if ( command == AKONADI_PARAM_SIZE ) {
mSize = m_streamParser->readNumber();
changes << AKONADI_PARAM_SIZE;
}
else if ( command == "PARTS" ) {
const QList<QByteArray> parts = m_streamParser->readParenthesizedList();
if ( op == Delete ) {
if ( !store->removeItemParts( item, parts ) )
return failureResponse( "Unable to remove item parts." );
changes += QSet<QByteArray>::fromList( parts );
}
}
else if ( command == "COLLECTION" ) {
throw HandlerException( "Item moving via STORE is deprecated, update your Akonadi client" );
}
// parts/attributes
else {
// obtain and configure the part object
int partVersion = 0;
QByteArray partName;
ImapParser::splitVersionedKey( command, partName, partVersion );
SelectQueryBuilder<Part> qb;
qb.addValueCondition( Part::pimItemIdColumn(), Query::Equals, item.id() );
qb.addValueCondition( Part::nameColumn(), Query::Equals, QString::fromUtf8( partName ) );
if ( !qb.exec() )
return failureResponse( "Unable to check item part existence" );
Part::List result = qb.result();
Part part;
if ( !result.isEmpty() )
part = result.first();
part.setName( QString::fromUtf8( partName ) );
part.setVersion( partVersion );
part.setPimItemId( item.id() );
QByteArray value;
if ( m_streamParser->hasLiteral() ) {
const qint64 dataSize = m_streamParser->remainingLiteralSize();
partSizes += dataSize;
const bool storeInFile = ( DbConfig::configuredDatabase()->useExternalPayloadFile() && dataSize > DbConfig::configuredDatabase()->sizeThreshold() );
//actual case when streaming storage is used: external payload is enabled, data is big enough in a literal
if ( storeInFile ) {
part.setExternal( true ); //the part WILL be external
value = m_streamParser->readLiteralPart(); // ### why?
if ( part.isValid() ) {
if ( !PartHelper::update( &part, value, dataSize ) )
return failureResponse( "Unable to update item part" );
} else {
// qDebug() << "insert from Store::handleLine";
part.setData( value );
part.setDatasize( value.size() ); // ### why not datasize?
if ( !PartHelper::insert( &part ) )
return failureResponse( "Unable to add item part" );
}
//the actual streaming code, reads from the parser, writes immediately to the file
// ### move this entire block to part helper? should be useful for append as well
const QString fileName = QString::fromUtf8( part.data() );
QFile file( fileName );
if ( file.open( QIODevice::WriteOnly | QIODevice::Append ) ) {
while ( !m_streamParser->atLiteralEnd() ) {
value = m_streamParser->readLiteralPart();
file.write( value ); // ### error handling?
}
file.close();
} else {
return failureResponse( "Unable to update item part" );
}
changes << partName;
continue;
} else { // not store in file
//don't write in streaming way as the data goes to the database
while (!m_streamParser->atLiteralEnd()) {
value += m_streamParser->readLiteralPart();
}
}
} else { //not a literal
value = m_streamParser->readString();
partSizes += value.size();
}
const QByteArray origData = PartHelper::translateData( part );
if ( origData != value ) {
if ( part.isValid() ) {
if ( !PartHelper::update( &part, value, value.size() ) )
return failureResponse( "Unable to update item part" );
} else {
// qDebug() << "insert from Store::handleLine: " << value.left(100);
part.setData( value );
part.setDatasize( value.size() );
if ( !PartHelper::insert( &part ) )
return failureResponse( "Unable to add item part" );
}
changes << partName;
}
} // parts/attribute modification
}
QString datetime;
if ( !changes.isEmpty() ) {
// update item size
if ( pimItems.size() == 1 && (mSize > 0 || partSizes > 0) )
pimItems.first().setSize( qMax( mSize, partSizes ) );
// run update query and prepare change notifications
for ( int i = 0; i < pimItems.count(); ++i ) {
PimItem &item = pimItems[ i ];
item.setDatetime( modificationtime );
item.setAtime( modificationtime );
if ( !connection()->isOwnerResource( item ) )
item.setDirty( true );
if ( !item.update() )
throw HandlerException( "Unable to write item changes into the database" );
if ( invalidateCache ) {
if ( !store->invalidateItemCache( item ) ) {
throw HandlerException( "Unable to invalidate item cache in the database" );
}
}
store->notificationCollector()->itemChanged( item, changes );
}
if ( !transaction.commit() )
return failureResponse( "Cannot commit transaction." );
datetime = QLocale::c().toString( modificationtime, QLatin1String( "dd-MMM-yyyy hh:mm:ss +0000" ) );
} else {
datetime = QLocale::c().toString( pimItems.first().datetime(), QLatin1String( "dd-MMM-yyyy hh:mm:ss +0000" ) );
}
Response response;
response.setTag( tag() );
response.setSuccess();
response.setString( "DATETIME " + ImapParser::quote( datetime.toUtf8() ) + " STORE completed" );
emit responseAvailable( response );
return true;
}
void Store::parseCommand()
{
mScope.parseScope( m_streamParser );
// parse the stuff before the modification list
while ( !m_streamParser->hasList() ) {
const QByteArray command = m_streamParser->readString();
if ( command.isEmpty() ) { // ie. we are at command end
throw HandlerException( "No modification list provided in STORE command" );
} else if ( command == AKONADI_PARAM_REVISION ) {
mPreviousRevision = m_streamParser->readNumber();
} else if ( command == AKONADI_PARAM_SIZE ) {
mSize = m_streamParser->readNumber();
}
}
}
void Store::sendPimItemResponse( const PimItem &pimItem )
{
QList<Flag> flags = pimItem.flags();
QStringList flagList;
for ( int j = 0; j < flags.count(); ++j )
flagList.append( flags[ j ].name() );
Response response;
response.setUntagged();
// IMAP protocol violation: should actually be the sequence number
response.setString( QByteArray::number( pimItem.id() ) + " FETCH (FLAGS (" + flagList.join( QLatin1String(" ") ).toUtf8() + "))" );
emit responseAvailable( response );
}
#include "store.moc"
<commit_msg>Add TODO for proper handling of no-op change jobs.<commit_after>/***************************************************************************
* Copyright (C) 2006 by Tobias Koenig <tokoe@kde.org> *
* *
* This program 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 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 Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
#include "store.h"
#include "akonadi.h"
#include "akonadiconnection.h"
#include "handlerhelper.h"
#include "response.h"
#include "storage/datastore.h"
#include "storage/transaction.h"
#include "storage/itemqueryhelper.h"
#include "storage/selectquerybuilder.h"
#include "storage/parthelper.h"
#include "storage/dbconfig.h"
#include "storage/itemretriever.h"
#include "libs/imapparser_p.h"
#include "libs/protocol_p.h"
#include "imapstreamparser.h"
#include <QtCore/QStringList>
#include <QLocale>
#include <QDebug>
#include <QFile>
#include <boost/bind.hpp>
#include <algorithm>
using namespace Akonadi;
Store::Store( Scope::SelectionScope scope )
: Handler()
, mScope( scope )
, mPos( 0 )
, mPreviousRevision( -1 )
, mSize( 0 )
{
}
bool Store::replaceFlags( const PimItem &item, const QList<QByteArray> &flags )
{
Flag::List flagList = HandlerHelper::resolveFlags( flags );
DataStore *store = connection()->storageBackend();
Flag::List currentFlags = item.flags();
std::sort( flagList.begin(), flagList.end(), boost::bind( &Flag::id, _1 ) < boost::bind( &Flag::id, _2 ) );
std::sort( currentFlags.begin(), currentFlags.end(), boost::bind( &Flag::id, _1 ) < boost::bind( &Flag::id, _2 ) );
if ( flagList == currentFlags )
return false;
if ( !store->setItemFlags( item, flagList ) )
throw HandlerException( "Store::replaceFlags: Unable to set new item flags" );
return true;
}
bool Store::addFlags( const PimItem &item, const QList<QByteArray> &flags )
{
const Flag::List flagList = HandlerHelper::resolveFlags( flags );
DataStore *store = connection()->storageBackend();
if ( !store->appendItemFlags( item, flagList ) ) {
qDebug( "Store::addFlags: Unable to add new item flags" );
return false;
}
return true;
}
bool Store::deleteFlags( const PimItem &item, const QList<QByteArray> &flags )
{
DataStore *store = connection()->storageBackend();
QList<Flag> flagList;
for ( int i = 0; i < flags.count(); ++i ) {
Flag flag = Flag::retrieveByName( QString::fromUtf8( flags[ i ] ) );
if ( !flag.isValid() )
continue;
flagList.append( flag );
}
if ( !store->removeItemFlags( item, flagList ) ) {
qDebug( "Store::deleteFlags: Unable to remove item flags" );
return false;
}
return true;
}
bool Store::parseStream()
{
parseCommand();
DataStore *store = connection()->storageBackend();
Transaction transaction( store );
// Set the same modification time for each item.
const QDateTime modificationtime = QDateTime::currentDateTime().toUTC();
// retrieve selected items
SelectQueryBuilder<PimItem> qb;
ItemQueryHelper::scopeToQuery( mScope, connection(), qb );
if ( !qb.exec() )
return failureResponse( "Unable to retrieve items" );
PimItem::List pimItems = qb.result();
if ( pimItems.isEmpty() )
return failureResponse( "No items found" );
// check and update revisions
for ( int i = 0; i < pimItems.size(); ++i ) {
if ( mPreviousRevision >= 0 && pimItems.at( i ).rev() != (int)mPreviousRevision )
throw HandlerException( "Item was modified elsewhere, aborting STORE." );
pimItems[ i ].setRev( pimItems[ i ].rev() + 1 );
}
QSet<QByteArray> changes;
qint64 partSizes = 0;
bool invalidateCache = false;
// apply modifications
m_streamParser->beginList();
while ( !m_streamParser->atListEnd() ) {
// parse the command
QByteArray command = m_streamParser->readString();
if ( command.isEmpty() )
throw HandlerException( "Syntax error" );
Operation op = Replace;
bool silent = false;
if ( command.startsWith( '+' ) ) {
op = Add;
command = command.mid( 1 );
} else if ( command.startsWith( '-' ) ) {
op = Delete;
command = command.mid( 1 );
}
if ( command.endsWith( ".SILENT" ) ) {
command.chop( 7 );
silent = true;
}
// qDebug() << "STORE: handling command: " << command;
// handle commands that can be applied to more than one item
if ( command == AKONADI_PARAM_FLAGS ) {
bool flagsChanged = true;
const QList<QByteArray> flags = m_streamParser->readParenthesizedList();
// TODO move this iteration to an SQL query.
for ( int i = 0; i < pimItems.count(); ++i ) {
if ( op == Replace ) {
flagsChanged = replaceFlags( pimItems[ i ], flags );
} else if ( op == Add ) {
if ( !addFlags( pimItems[ i ], flags ) )
return failureResponse( "Unable to add item flags." );
} else if ( op == Delete ) {
if ( !deleteFlags( pimItems[ i ], flags ) )
return failureResponse( "Unable to remove item flags." );
}
// TODO what is this about?
if ( !silent ) {
sendPimItemResponse( pimItems[i] );
}
}
if ( flagsChanged )
changes << AKONADI_PARAM_FLAGS;
continue;
}
// handle commands that can only be applied to one item
if ( pimItems.size() > 1 )
throw HandlerException( "This Modification can only be applied to a single item" );
PimItem &item = pimItems.first();
if ( !item.isValid() )
throw HandlerException( "Invalid item in query result!?" );
if ( command == AKONADI_PARAM_REMOTEID ) {
const QString rid = m_streamParser->readUtf8String();
if ( item.remoteId() != rid ) {
if ( !connection()->isOwnerResource( item ) )
throw HandlerException( "Only resources can modify remote identifiers" );
item.setRemoteId( rid );
changes << AKONADI_PARAM_REMOTEID;
}
}
else if ( command == AKONADI_PARAM_REMOTEREVISION ) {
const QString remoteRevision = m_streamParser->readUtf8String();
if ( item.remoteRevision() != remoteRevision ) {
if ( !connection()->isOwnerResource( item ) )
throw HandlerException( "Only resources can modify remote revisions" );
item.setRemoteRevision( remoteRevision );
changes << AKONADI_PARAM_REMOTEREVISION;
}
}
else if ( command == AKONADI_PARAM_UNDIRTY ) {
m_streamParser->readString(); // read the 'false' string
item.setDirty( false );
}
else if ( command == AKONADI_PARAM_INVALIDATECACHE ) {
invalidateCache = true;
}
else if ( command == AKONADI_PARAM_SIZE ) {
mSize = m_streamParser->readNumber();
changes << AKONADI_PARAM_SIZE;
}
else if ( command == "PARTS" ) {
const QList<QByteArray> parts = m_streamParser->readParenthesizedList();
if ( op == Delete ) {
if ( !store->removeItemParts( item, parts ) )
return failureResponse( "Unable to remove item parts." );
changes += QSet<QByteArray>::fromList( parts );
}
}
else if ( command == "COLLECTION" ) {
throw HandlerException( "Item moving via STORE is deprecated, update your Akonadi client" );
}
// parts/attributes
else {
// obtain and configure the part object
int partVersion = 0;
QByteArray partName;
ImapParser::splitVersionedKey( command, partName, partVersion );
SelectQueryBuilder<Part> qb;
qb.addValueCondition( Part::pimItemIdColumn(), Query::Equals, item.id() );
qb.addValueCondition( Part::nameColumn(), Query::Equals, QString::fromUtf8( partName ) );
if ( !qb.exec() )
return failureResponse( "Unable to check item part existence" );
Part::List result = qb.result();
Part part;
if ( !result.isEmpty() )
part = result.first();
part.setName( QString::fromUtf8( partName ) );
part.setVersion( partVersion );
part.setPimItemId( item.id() );
QByteArray value;
if ( m_streamParser->hasLiteral() ) {
const qint64 dataSize = m_streamParser->remainingLiteralSize();
partSizes += dataSize;
const bool storeInFile = ( DbConfig::configuredDatabase()->useExternalPayloadFile() && dataSize > DbConfig::configuredDatabase()->sizeThreshold() );
//actual case when streaming storage is used: external payload is enabled, data is big enough in a literal
if ( storeInFile ) {
part.setExternal( true ); //the part WILL be external
value = m_streamParser->readLiteralPart(); // ### why?
if ( part.isValid() ) {
if ( !PartHelper::update( &part, value, dataSize ) )
return failureResponse( "Unable to update item part" );
} else {
// qDebug() << "insert from Store::handleLine";
part.setData( value );
part.setDatasize( value.size() ); // ### why not datasize?
if ( !PartHelper::insert( &part ) )
return failureResponse( "Unable to add item part" );
}
//the actual streaming code, reads from the parser, writes immediately to the file
// ### move this entire block to part helper? should be useful for append as well
const QString fileName = QString::fromUtf8( part.data() );
QFile file( fileName );
if ( file.open( QIODevice::WriteOnly | QIODevice::Append ) ) {
while ( !m_streamParser->atLiteralEnd() ) {
value = m_streamParser->readLiteralPart();
file.write( value ); // ### error handling?
}
file.close();
} else {
return failureResponse( "Unable to update item part" );
}
changes << partName;
continue;
} else { // not store in file
//don't write in streaming way as the data goes to the database
while (!m_streamParser->atLiteralEnd()) {
value += m_streamParser->readLiteralPart();
}
}
} else { //not a literal
value = m_streamParser->readString();
partSizes += value.size();
}
const QByteArray origData = PartHelper::translateData( part );
if ( origData != value ) {
if ( part.isValid() ) {
if ( !PartHelper::update( &part, value, value.size() ) )
return failureResponse( "Unable to update item part" );
} else {
// qDebug() << "insert from Store::handleLine: " << value.left(100);
part.setData( value );
part.setDatasize( value.size() );
if ( !PartHelper::insert( &part ) )
return failureResponse( "Unable to add item part" );
}
changes << partName;
}
} // parts/attribute modification
}
QString datetime;
if ( !changes.isEmpty() ) {
// update item size
if ( pimItems.size() == 1 && (mSize > 0 || partSizes > 0) )
pimItems.first().setSize( qMax( mSize, partSizes ) );
// run update query and prepare change notifications
for ( int i = 0; i < pimItems.count(); ++i ) {
PimItem &item = pimItems[ i ];
item.setDatetime( modificationtime );
item.setAtime( modificationtime );
if ( !connection()->isOwnerResource( item ) )
item.setDirty( true );
if ( !item.update() )
throw HandlerException( "Unable to write item changes into the database" );
if ( invalidateCache ) {
if ( !store->invalidateItemCache( item ) ) {
throw HandlerException( "Unable to invalidate item cache in the database" );
}
}
store->notificationCollector()->itemChanged( item, changes );
}
if ( !transaction.commit() )
return failureResponse( "Cannot commit transaction." );
datetime = QLocale::c().toString( modificationtime, QLatin1String( "dd-MMM-yyyy hh:mm:ss +0000" ) );
} else {
datetime = QLocale::c().toString( pimItems.first().datetime(), QLatin1String( "dd-MMM-yyyy hh:mm:ss +0000" ) );
}
// TODO: When implementing support for modifying multiple items at once, the revisions of the items should be in the responses.
// or only modified items should appear in the repsponse.
Response response;
response.setTag( tag() );
response.setSuccess();
response.setString( "DATETIME " + ImapParser::quote( datetime.toUtf8() ) + " STORE completed" );
emit responseAvailable( response );
return true;
}
void Store::parseCommand()
{
mScope.parseScope( m_streamParser );
// parse the stuff before the modification list
while ( !m_streamParser->hasList() ) {
const QByteArray command = m_streamParser->readString();
if ( command.isEmpty() ) { // ie. we are at command end
throw HandlerException( "No modification list provided in STORE command" );
} else if ( command == AKONADI_PARAM_REVISION ) {
mPreviousRevision = m_streamParser->readNumber();
} else if ( command == AKONADI_PARAM_SIZE ) {
mSize = m_streamParser->readNumber();
}
}
}
void Store::sendPimItemResponse( const PimItem &pimItem )
{
QList<Flag> flags = pimItem.flags();
QStringList flagList;
for ( int j = 0; j < flags.count(); ++j )
flagList.append( flags[ j ].name() );
Response response;
response.setUntagged();
// IMAP protocol violation: should actually be the sequence number
response.setString( QByteArray::number( pimItem.id() ) + " FETCH (FLAGS (" + flagList.join( QLatin1String(" ") ).toUtf8() + "))" );
emit responseAvailable( response );
}
#include "store.moc"
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.