<commit_before>#include <cassert>
#include "samplers/stratified_sampler.h"
#include "material/bsdf.h"

BSDF::BSDF(const DifferentialGeometry &dg, float eta)
	: normal(dg.normal), geom_normal(dg.geom_normal), bitangent(dg.dp_du.normalized()),
	tangent(normal.cross(bitangent).normalized()), n_bxdfs(0), dg(dg), eta(eta)
{
	//Update the bitangent to get a proper coordinate system
	bitangent = tangent.cross(Vector{normal}).normalized();
}
void BSDF::add(BxDF *b){
	bxdfs[n_bxdfs++] = b;
}
int BSDF::num_bxdfs() const {
	return n_bxdfs;
}
int BSDF::num_bxdfs(BxDFTYPE flags) const {
	int n = 0;
	for (int i = 0; i < n_bxdfs; ++i){
		if (bxdfs[i]->matches(flags)){
			++n;
		}
	}
	return n;
}
Vector BSDF::to_shading(const Vector &v) const {
	return Vector{v.dot(bitangent), v.dot(tangent), v.dot(normal)};
}
Vector BSDF::from_shading(const Vector &v) const {
	return Vector{bitangent.x * v.x + tangent.x * v.y + normal.x * v.z,
		bitangent.y * v.x + tangent.y * v.y + normal.y * v.z,
		bitangent.z * v.x + tangent.z * v.y + normal.z * v.z};
}
Colorf BSDF::operator()(const Vector &wo_world, const Vector &wi_world, BxDFTYPE flags) const {
	Vector wo = to_shading(wo_world);
	Vector wi = to_shading(wi_world);
	//Determine if we should be evaluating reflection or transmission based on the geometry normal
	if (wo_world.dot(geom_normal) * wi_world.dot(geom_normal) > 0){
		flags = BxDFTYPE(flags & ~BxDFTYPE::TRANSMISSION);
	}
	else {
		flags = BxDFTYPE(flags & ~BxDFTYPE::REFLECTION);
	}
	Colorf color;
	for (int i = 0; i < n_bxdfs; ++i){
		if (bxdfs[i]->matches(flags)){
			color += (*bxdfs[i])(wo, wi);
		}
	}
	return color;
}
Colorf BSDF::sample(const Vector &wo_world, Vector &wi_world, const std::array<float, 2> &u, float comp,
	float &pdf_val, BxDFTYPE flags, BxDFTYPE *sampled_type) const
{
	//Select which component to sample that matches the desired flags
	int n_matching = num_bxdfs(flags);
	if (n_matching == 0){
		pdf_val = 0;
		if (sampled_type){
			*sampled_type = BxDFTYPE(0);
		}
		return Colorf{0};
	}
	int select = std::min(static_cast<int>(comp * n_matching), n_matching - 1);
	const BxDF *bxdf = matching_at(select, flags);
	assert(bxdf);

	Vector wo = to_shading(wo_world);
	Vector wi;
	pdf_val = 0;
	Colorf f = bxdf->sample(wo, wi, u, pdf_val);
	if (pdf_val == 0){
		if (sampled_type){
			*sampled_type = BxDFTYPE(0);
		}
		return Colorf{0};
	}
	if (sampled_type){
		*sampled_type = bxdf->type;
	}
	wi_world = from_shading(wi);

	//Compute the overall sampling PDF for the direction we sampled. This is skipped for specular BxDFs
	//since they contain a delta distribution which would make this incorrect
	if (!(bxdf->type & BxDFTYPE::SPECULAR) && n_matching > 1){
		pdf_val = pdf(wo_world, wi_world, flags);
		//Compute the total contribution from all BxDFs matching the flags along this direction
		f = (*this)(wo_world, wi_world, flags);
	}
	return f;
}
Colorf BSDF::rho_hd(const Vector &wo, Sampler &sampler, MemoryPool &pool, BxDFTYPE flags, int sqrt_samples) const {
	int n_samples = sqrt_samples * sqrt_samples;
	std::array<float, 2> *samples = pool.alloc_array<std::array<float, 2>>(n_samples);
	sampler.get_samples(samples, n_samples);
	Colorf color;
	for (int i = 0; i < n_bxdfs; ++i){
		if (bxdfs[i]->matches(flags)){
			color += bxdfs[i]->rho_hd(wo, samples, n_samples);
		}
	}
	return color;
}
Colorf BSDF::rho_hh(Sampler &sampler, MemoryPool &pool, BxDFTYPE flags, int sqrt_samples) const {
	int n_samples = sqrt_samples * sqrt_samples;
	std::array<float, 2> *samples_a = pool.alloc_array<std::array<float, 2>>(n_samples);
	std::array<float, 2> *samples_b = pool.alloc_array<std::array<float, 2>>(n_samples);
	sampler.get_samples(samples_a, n_samples);
	sampler.get_samples(samples_b, n_samples);
	Colorf color;
	for (int i = 0; i < n_bxdfs; ++i){
		if (bxdfs[i]->matches(flags)){
			color += bxdfs[i]->rho_hh(samples_a, samples_b, n_samples);
		}
	}
	return color;

}
float BSDF::pdf(const Vector &wo_world, const Vector &wi_world, BxDFTYPE flags) const {
	Vector wo = to_shading(wo_world);
	Vector wi = to_shading(wi_world);
	float pdf_val = 0;
	int n_comps = 0;
	for (int i = 0; i < n_bxdfs; ++i){
		if (bxdfs[i]->matches(flags)){
			++n_comps;
			pdf_val += bxdfs[i]->pdf(wo, wi);
		}
	}
	return n_comps > 0 ? pdf_val / n_comps : 0;
}
const BxDF* BSDF::matching_at(int n, BxDFTYPE flags) const {
	for (int i = 0; i < n_bxdfs; ++i){
		if (bxdfs[i]->matches(flags) && n-- == 0){
			return bxdfs[i];
		}
	}
	return nullptr;
}

<commit_msg>Add assert to cathc overflowing BxDFs<commit_after>#include <cassert>
#include "samplers/stratified_sampler.h"
#include "material/bsdf.h"

BSDF::BSDF(const DifferentialGeometry &dg, float eta)
	: normal(dg.normal), geom_normal(dg.geom_normal), bitangent(dg.dp_du.normalized()),
	tangent(normal.cross(bitangent).normalized()), n_bxdfs(0), dg(dg), eta(eta)
{
	//Update the bitangent to get a proper coordinate system
	bitangent = tangent.cross(Vector{normal}).normalized();
}
void BSDF::add(BxDF *b){
	assert(n_bxdfs < 8);
	bxdfs[n_bxdfs++] = b;
}
int BSDF::num_bxdfs() const {
	return n_bxdfs;
}
int BSDF::num_bxdfs(BxDFTYPE flags) const {
	int n = 0;
	for (int i = 0; i < n_bxdfs; ++i){
		if (bxdfs[i]->matches(flags)){
			++n;
		}
	}
	return n;
}
Vector BSDF::to_shading(const Vector &v) const {
	return Vector{v.dot(bitangent), v.dot(tangent), v.dot(normal)};
}
Vector BSDF::from_shading(const Vector &v) const {
	return Vector{bitangent.x * v.x + tangent.x * v.y + normal.x * v.z,
		bitangent.y * v.x + tangent.y * v.y + normal.y * v.z,
		bitangent.z * v.x + tangent.z * v.y + normal.z * v.z};
}
Colorf BSDF::operator()(const Vector &wo_world, const Vector &wi_world, BxDFTYPE flags) const {
	Vector wo = to_shading(wo_world);
	Vector wi = to_shading(wi_world);
	//Determine if we should be evaluating reflection or transmission based on the geometry normal
	if (wo_world.dot(geom_normal) * wi_world.dot(geom_normal) > 0){
		flags = BxDFTYPE(flags & ~BxDFTYPE::TRANSMISSION);
	}
	else {
		flags = BxDFTYPE(flags & ~BxDFTYPE::REFLECTION);
	}
	Colorf color;
	for (int i = 0; i < n_bxdfs; ++i){
		if (bxdfs[i]->matches(flags)){
			color += (*bxdfs[i])(wo, wi);
		}
	}
	return color;
}
Colorf BSDF::sample(const Vector &wo_world, Vector &wi_world, const std::array<float, 2> &u, float comp,
	float &pdf_val, BxDFTYPE flags, BxDFTYPE *sampled_type) const
{
	//Select which component to sample that matches the desired flags
	int n_matching = num_bxdfs(flags);
	if (n_matching == 0){
		pdf_val = 0;
		if (sampled_type){
			*sampled_type = BxDFTYPE(0);
		}
		return Colorf{0};
	}
	int select = std::min(static_cast<int>(comp * n_matching), n_matching - 1);
	const BxDF *bxdf = matching_at(select, flags);
	assert(bxdf);

	Vector wo = to_shading(wo_world);
	Vector wi;
	pdf_val = 0;
	Colorf f = bxdf->sample(wo, wi, u, pdf_val);
	if (pdf_val == 0){
		if (sampled_type){
			*sampled_type = BxDFTYPE(0);
		}
		return Colorf{0};
	}
	if (sampled_type){
		*sampled_type = bxdf->type;
	}
	wi_world = from_shading(wi);

	//Compute the overall sampling PDF for the direction we sampled. This is skipped for specular BxDFs
	//since they contain a delta distribution which would make this incorrect
	if (!(bxdf->type & BxDFTYPE::SPECULAR) && n_matching > 1){
		pdf_val = pdf(wo_world, wi_world, flags);
		//Compute the total contribution from all BxDFs matching the flags along this direction
		f = (*this)(wo_world, wi_world, flags);
	}
	return f;
}
Colorf BSDF::rho_hd(const Vector &wo, Sampler &sampler, MemoryPool &pool, BxDFTYPE flags, int sqrt_samples) const {
	int n_samples = sqrt_samples * sqrt_samples;
	std::array<float, 2> *samples = pool.alloc_array<std::array<float, 2>>(n_samples);
	sampler.get_samples(samples, n_samples);
	Colorf color;
	for (int i = 0; i < n_bxdfs; ++i){
		if (bxdfs[i]->matches(flags)){
			color += bxdfs[i]->rho_hd(wo, samples, n_samples);
		}
	}
	return color;
}
Colorf BSDF::rho_hh(Sampler &sampler, MemoryPool &pool, BxDFTYPE flags, int sqrt_samples) const {
	int n_samples = sqrt_samples * sqrt_samples;
	std::array<float, 2> *samples_a = pool.alloc_array<std::array<float, 2>>(n_samples);
	std::array<float, 2> *samples_b = pool.alloc_array<std::array<float, 2>>(n_samples);
	sampler.get_samples(samples_a, n_samples);
	sampler.get_samples(samples_b, n_samples);
	Colorf color;
	for (int i = 0; i < n_bxdfs; ++i){
		if (bxdfs[i]->matches(flags)){
			color += bxdfs[i]->rho_hh(samples_a, samples_b, n_samples);
		}
	}
	return color;

}
float BSDF::pdf(const Vector &wo_world, const Vector &wi_world, BxDFTYPE flags) const {
	Vector wo = to_shading(wo_world);
	Vector wi = to_shading(wi_world);
	float pdf_val = 0;
	int n_comps = 0;
	for (int i = 0; i < n_bxdfs; ++i){
		if (bxdfs[i]->matches(flags)){
			++n_comps;
			pdf_val += bxdfs[i]->pdf(wo, wi);
		}
	}
	return n_comps > 0 ? pdf_val / n_comps : 0;
}
const BxDF* BSDF::matching_at(int n, BxDFTYPE flags) const {
	for (int i = 0; i < n_bxdfs; ++i){
		if (bxdfs[i]->matches(flags) && n-- == 0){
			return bxdfs[i];
		}
	}
	return nullptr;
}

<|endoftext|>


<commit_before><commit_msg>KDE4: Drop Qt 4.9 support<commit_after><|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please
** contact Nokia at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qmessagestore.h"
#include "qmfhelpers_p.h"

#include <qmailstore.h>

using namespace QmfHelpers;

class QMessageStorePrivate
{
public:
    QMessageStorePrivate() : _store(QMailStore::instance()), _error(QMessageStore::NoError) {}

    QMailStore *_store;
    QMessageStore::ErrorCode _error;

    Q_SCOPED_STATIC_DECLARE(QMessageStore,storeInstance);
};

Q_SCOPED_STATIC_DEFINE(QMessageStore,QMessageStorePrivate,storeInstance);

QMessageStore::QMessageStore(QObject *parent)
    : QObject(parent),
      d_ptr(new QMessageStorePrivate)
{
    Q_ASSERT(instance() != 0);
}

QMessageStore::~QMessageStore()
{
    delete d_ptr;
}

QMessageStore::ErrorCode QMessageStore::lastError() const
{
    if (d_ptr->_error != QMessageStore::NoError) {
        return d_ptr->_error;
    }

    return convert(d_ptr->_store->lastError());
}

QMessageIdList QMessageStore::queryMessages(const QMessageFilterKey &key, const QMessageSortKey &sortKey, uint limit, uint offset) const
{
    if (key.options() != 0) {
        d_ptr->_error = QMessageStore::NotYetImplemented;
        return QMessageIdList();
    }

    d_ptr->_error = QMessageStore::NoError;
    return convert(d_ptr->_store->queryMessages(convert(key), convert(sortKey)));

    // TODO: Extend QMF to support limit/offset
    Q_UNUSED(limit)
    Q_UNUSED(offset)
}

#ifdef QMESSAGING_OPTIONAL_FOLDER
QMessageFolderIdList QMessageStore::queryFolders(const QMessageFolderFilterKey &key, const QMessageFolderSortKey &sortKey, uint limit, uint offset) const
{
    if (key.options() != 0) {
        d_ptr->_error = QMessageStore::NotYetImplemented;
        return QMessageFolderIdList();
    }

    d_ptr->_error = QMessageStore::NoError;
    return convert(d_ptr->_store->queryFolders(convert(key), convert(sortKey)));

    // TODO: Extend QMF to support limit/offset
    Q_UNUSED(limit)
    Q_UNUSED(offset)
}
#endif

QMessageAccountIdList QMessageStore::queryAccounts(const QMessageAccountFilterKey &key, const QMessageAccountSortKey &sortKey, uint limit, uint offset) const
{
    if (key.options() != 0) {
        d_ptr->_error = QMessageStore::NotYetImplemented;
        return QMessageAccountIdList();
    }

    d_ptr->_error = QMessageStore::NoError;
    return convert(d_ptr->_store->queryAccounts(convert(key), convert(sortKey)));

    // TODO: Extend QMF to support limit/offset
    Q_UNUSED(limit)
    Q_UNUSED(offset)
}

int QMessageStore::countMessages(const QMessageFilterKey& key) const
{
    if (key.options() != 0) {
        d_ptr->_error = QMessageStore::NotYetImplemented;
        return 0;
    }

    d_ptr->_error = QMessageStore::NoError;
    return d_ptr->_store->countMessages(convert(key));
}

#ifdef QMESSAGING_OPTIONAL_FOLDER
int QMessageStore::countFolders(const QMessageFolderFilterKey& key) const
{
    if (key.options() != 0) {
        d_ptr->_error = QMessageStore::NotYetImplemented;
        return 0;
    }

    d_ptr->_error = QMessageStore::NoError;
    return d_ptr->_store->countFolders(convert(key));
}
#endif

int QMessageStore::countAccounts(const QMessageAccountFilterKey& key) const
{
    if (key.options() != 0) {
        d_ptr->_error = QMessageStore::NotYetImplemented;
        return 0;
    }

    d_ptr->_error = QMessageStore::NoError;
    return d_ptr->_store->countAccounts(convert(key));
}

bool QMessageStore::removeMessage(const QMessageId& id, QMessageStore::RemovalOption option)
{
    d_ptr->_error = QMessageStore::NoError;
    return d_ptr->_store->removeMessage(convert(id), convert(option));
}

bool QMessageStore::removeMessages(const QMessageFilterKey& key, QMessageStore::RemovalOption option)
{
    d_ptr->_error = QMessageStore::NoError;
    return d_ptr->_store->removeMessages(convert(key), convert(option));
}

bool QMessageStore::addMessage(QMessage *m)
{
    QMailMessage msg(convert(*m));

    d_ptr->_error = QMessageStore::NoError;
    return d_ptr->_store->addMessage(&msg);
}

bool QMessageStore::updateMessage(QMessage *m)
{
    QMailMessage msg(convert(*m));

    d_ptr->_error = QMessageStore::NoError;
    return d_ptr->_store->updateMessage(&msg);
}

QMessage QMessageStore::message(const QMessageId& id) const
{
    d_ptr->_error = QMessageStore::NoError;
    return convert(d_ptr->_store->message(convert(id)));
}

#ifdef QMESSAGING_OPTIONAL_FOLDER
QMessageFolder QMessageStore::folder(const QMessageFolderId& id) const
{
    d_ptr->_error = QMessageStore::NoError;
    return convert(d_ptr->_store->folder(convert(id)));
}
#endif

QMessageAccount QMessageStore::account(const QMessageAccountId& id) const
{
    d_ptr->_error = QMessageStore::NoError;
    return convert(d_ptr->_store->account(convert(id)));
}

void QMessageStore::setMaximumWorkingMemory(uint maximumBytes)
{
    // TODO: implement memory constraints
    Q_UNUSED(maximumBytes)
}

uint QMessageStore::maximumWorkingMemory()
{
    // TODO: implement memory constraints
    return 0; // stub
}

QMessageStore* QMessageStore::instance()
{
    return QMessageStorePrivate::storeInstance();
}

void QMessageStore::startNotifications(const QMessageFilterKey &key)
{
    if (key.options() != 0) {
        d_ptr->_error = QMessageStore::NotYetImplemented;
        return;
    }

    // TODO: implement notifications
    Q_UNUSED(key)
}

void QMessageStore::stopNotifications()
{
    // TODO: implement notifications
}

<commit_msg>Dispatch limit/offset parameters to QMF queries.<commit_after>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please
** contact Nokia at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qmessagestore.h"
#include "qmfhelpers_p.h"

#include <qmailstore.h>

using namespace QmfHelpers;

class QMessageStorePrivate
{
public:
    QMessageStorePrivate() : _store(QMailStore::instance()), _error(QMessageStore::NoError) {}

    QMailStore *_store;
    QMessageStore::ErrorCode _error;

    Q_SCOPED_STATIC_DECLARE(QMessageStore,storeInstance);
};

Q_SCOPED_STATIC_DEFINE(QMessageStore,QMessageStorePrivate,storeInstance);

QMessageStore::QMessageStore(QObject *parent)
    : QObject(parent),
      d_ptr(new QMessageStorePrivate)
{
    Q_ASSERT(instance() != 0);
}

QMessageStore::~QMessageStore()
{
    delete d_ptr;
}

QMessageStore::ErrorCode QMessageStore::lastError() const
{
    if (d_ptr->_error != QMessageStore::NoError) {
        return d_ptr->_error;
    }

    return convert(d_ptr->_store->lastError());
}

QMessageIdList QMessageStore::queryMessages(const QMessageFilterKey &key, const QMessageSortKey &sortKey, uint limit, uint offset) const
{
    if (key.options() != 0) {
        d_ptr->_error = QMessageStore::NotYetImplemented;
        return QMessageIdList();
    }

    d_ptr->_error = QMessageStore::NoError;
    return convert(d_ptr->_store->queryMessages(convert(key), convert(sortKey), limit, offset));
}

#ifdef QMESSAGING_OPTIONAL_FOLDER
QMessageFolderIdList QMessageStore::queryFolders(const QMessageFolderFilterKey &key, const QMessageFolderSortKey &sortKey, uint limit, uint offset) const
{
    if (key.options() != 0) {
        d_ptr->_error = QMessageStore::NotYetImplemented;
        return QMessageFolderIdList();
    }

    d_ptr->_error = QMessageStore::NoError;
    return convert(d_ptr->_store->queryFolders(convert(key), convert(sortKey), limit, offset));
}
#endif

QMessageAccountIdList QMessageStore::queryAccounts(const QMessageAccountFilterKey &key, const QMessageAccountSortKey &sortKey, uint limit, uint offset) const
{
    if (key.options() != 0) {
        d_ptr->_error = QMessageStore::NotYetImplemented;
        return QMessageAccountIdList();
    }

    d_ptr->_error = QMessageStore::NoError;
    return convert(d_ptr->_store->queryAccounts(convert(key), convert(sortKey), limit, offset));
}

int QMessageStore::countMessages(const QMessageFilterKey& key) const
{
    if (key.options() != 0) {
        d_ptr->_error = QMessageStore::NotYetImplemented;
        return 0;
    }

    d_ptr->_error = QMessageStore::NoError;
    return d_ptr->_store->countMessages(convert(key));
}

#ifdef QMESSAGING_OPTIONAL_FOLDER
int QMessageStore::countFolders(const QMessageFolderFilterKey& key) const
{
    if (key.options() != 0) {
        d_ptr->_error = QMessageStore::NotYetImplemented;
        return 0;
    }

    d_ptr->_error = QMessageStore::NoError;
    return d_ptr->_store->countFolders(convert(key));
}
#endif

int QMessageStore::countAccounts(const QMessageAccountFilterKey& key) const
{
    if (key.options() != 0) {
        d_ptr->_error = QMessageStore::NotYetImplemented;
        return 0;
    }

    d_ptr->_error = QMessageStore::NoError;
    return d_ptr->_store->countAccounts(convert(key));
}

bool QMessageStore::removeMessage(const QMessageId& id, QMessageStore::RemovalOption option)
{
    d_ptr->_error = QMessageStore::NoError;
    return d_ptr->_store->removeMessage(convert(id), convert(option));
}

bool QMessageStore::removeMessages(const QMessageFilterKey& key, QMessageStore::RemovalOption option)
{
    d_ptr->_error = QMessageStore::NoError;
    return d_ptr->_store->removeMessages(convert(key), convert(option));
}

bool QMessageStore::addMessage(QMessage *m)
{
    QMailMessage msg(convert(*m));

    d_ptr->_error = QMessageStore::NoError;
    return d_ptr->_store->addMessage(&msg);
}

bool QMessageStore::updateMessage(QMessage *m)
{
    QMailMessage msg(convert(*m));

    d_ptr->_error = QMessageStore::NoError;
    return d_ptr->_store->updateMessage(&msg);
}

QMessage QMessageStore::message(const QMessageId& id) const
{
    d_ptr->_error = QMessageStore::NoError;
    return convert(d_ptr->_store->message(convert(id)));
}

#ifdef QMESSAGING_OPTIONAL_FOLDER
QMessageFolder QMessageStore::folder(const QMessageFolderId& id) const
{
    d_ptr->_error = QMessageStore::NoError;
    return convert(d_ptr->_store->folder(convert(id)));
}
#endif

QMessageAccount QMessageStore::account(const QMessageAccountId& id) const
{
    d_ptr->_error = QMessageStore::NoError;
    return convert(d_ptr->_store->account(convert(id)));
}

void QMessageStore::setMaximumWorkingMemory(uint maximumBytes)
{
    // TODO: implement memory constraints
    Q_UNUSED(maximumBytes)
}

uint QMessageStore::maximumWorkingMemory()
{
    // TODO: implement memory constraints
    return 0; // stub
}

QMessageStore* QMessageStore::instance()
{
    return QMessageStorePrivate::storeInstance();
}

void QMessageStore::startNotifications(const QMessageFilterKey &key)
{
    if (key.options() != 0) {
        d_ptr->_error = QMessageStore::NotYetImplemented;
        return;
    }

    // TODO: implement notifications
    Q_UNUSED(key)
}

void QMessageStore::stopNotifications()
{
    // TODO: implement notifications
}

<|endoftext|>


<commit_before>// This file was developed by Thomas Müller <thomas94@gmx.net>.
// It is published under the BSD 3-Clause License within the LICENSE file.

#include <tev/HelpWindow.h>

#include <nanogui/button.h>
#include <nanogui/icons.h>
#include <nanogui/label.h>
#include <nanogui/layout.h>
#include <nanogui/opengl.h>
#include <nanogui/tabwidget.h>
#include <nanogui/window.h>

using namespace nanogui;
using namespace std;

TEV_NAMESPACE_BEGIN

#ifdef __APPLE__
string HelpWindow::COMMAND = "Cmd";
#else
string HelpWindow::COMMAND = "Ctrl";
#endif

#ifdef __APPLE__
string HelpWindow::ALT = "Opt";
#else
string HelpWindow::ALT = "Alt";
#endif

HelpWindow::HelpWindow(Widget *parent, bool supportsHdr, function<void()> closeCallback)
    : Window{parent, "Help"}, mCloseCallback{closeCallback} {

    auto closeButton = new Button{button_panel(), "", FA_TIMES};
    closeButton->set_callback(mCloseCallback);

    set_layout(new GroupLayout{});
    set_fixed_width(600);

    TabWidget* tabWidget = new TabWidget{this};

    // Keybindings tab
    {
        Widget* shortcuts = new Widget(tabWidget);
        shortcuts->set_layout(new GroupLayout{});
        tabWidget->append_tab("Keybindings", shortcuts);

        auto addRow = [](Widget* current, string keys, string desc) {
            auto row = new Widget{current};
            row->set_layout(new BoxLayout{Orientation::Horizontal, Alignment::Fill, 0, 10});
            auto descWidget = new Label{row, desc, "sans"};
            descWidget->set_fixed_width(250);
            new Label{row, keys, "sans-bold"};
        };

        new Label{shortcuts, "Image Loading", "sans-bold", 18};
        auto imageLoading = new Widget{shortcuts};
        imageLoading->set_layout(new BoxLayout{Orientation::Vertical, Alignment::Fill, 0, 0});

        addRow(imageLoading, COMMAND + "+O",                             "Open Image");
        addRow(imageLoading, COMMAND + "+S",                             "Save View as Image");
        addRow(imageLoading, COMMAND + "+R or F5",                       "Reload Image");
        addRow(imageLoading, COMMAND + "+Shift+R or " + COMMAND + "+F5", "Reload All Images");
        addRow(imageLoading, COMMAND + "+W",                             "Close Image");
        addRow(imageLoading, COMMAND + "+Shift+W",                       "Close All Images");
        addRow(imageLoading, COMMAND + "+C",                             "Copy Image or Path to Clipboard");
        addRow(imageLoading, COMMAND + "+V",                             "Paste Image from Clipboard");

        new Label{shortcuts, "Image Options", "sans-bold", 18};
        auto imageSelection = new Widget{shortcuts};
        imageSelection->set_layout(new BoxLayout{Orientation::Vertical, Alignment::Fill, 0, 0});

        addRow(imageSelection, "Left Click",          "Select Hovered Image");
        addRow(imageSelection, "1…9",                 "Select N-th Image");
        addRow(imageSelection, "Down or S / Up or W", "Select Next / Previous Image");

        addRow(imageSelection, "Click & Drag (+Shift/" + COMMAND + ")", "Translate Image");
        addRow(imageSelection, "Plus / Minus / Scroll (+Shift/" + COMMAND + ")", "Zoom In / Out of Image");

        addRow(imageSelection, "F", "Fit Image to Screen");
        addRow(imageSelection, "N", "Normalize Image to [0, 1]");
        addRow(imageSelection, "R", "Reset Image Parameters");
        if (supportsHdr) {
            addRow(imageSelection, "L", "Display the image as if on an LDR screen");
        }

        addRow(imageSelection, "Shift+Right or Shift+D / Shift+Left or Shift+A", "Select Next / Previous Tonemap");

        addRow(imageSelection, "E / Shift+E", "Increase / Decrease Exposure by 0.5");
        addRow(imageSelection, "O / Shift+O", "Increase / Decrease Offset by 0.1");

        addRow(imageSelection, "Shift+Ctrl (hold)", "Display raw bytes on pixels when zoomed-in");

        new Label{shortcuts, "Reference Options", "sans-bold", 18};
        auto referenceSelection = new Widget{shortcuts};
        referenceSelection->set_layout(new BoxLayout{Orientation::Vertical, Alignment::Fill, 0, 0});

        addRow(referenceSelection, ALT + " (hold)",                               "View currently selected Reference");
        addRow(referenceSelection, "Shift+Left Click or Right Click",             "Select Hovered Image as Reference");
        addRow(referenceSelection, "Shift+1…9",                                   "Select N-th Image as Reference");
        addRow(referenceSelection, "Shift+Down or Shift+S / Shift+Up or Shift+W", "Select Next / Previous Image as Reference");

        addRow(referenceSelection, "Ctrl (hold)",                                "View selected Image if Reference is selected");
        addRow(referenceSelection, "Ctrl+Right or Ctrl+D / Ctrl+Left or Ctrl+A", "Select Next / Previous Error Metric");

        new Label{shortcuts, "Channel Group Options", "sans-bold", 18};
        auto groupSelection = new Widget{shortcuts};
        groupSelection->set_layout(new BoxLayout{Orientation::Vertical, Alignment::Fill, 0, 0});

        addRow(groupSelection, "Left Click",             "Select Hovered Channel Group");
        addRow(groupSelection, "Ctrl+1…9",               "Select N-th Channel Group");
        addRow(groupSelection, "Right or D / Left or A", "Select Next / Previous Channel Group");

        new Label{shortcuts, "Interface", "sans-bold", 18};
        auto ui = new Widget{shortcuts};
        ui->set_layout(new BoxLayout{Orientation::Vertical, Alignment::Fill, 0, 0});

        addRow(ui, ALT + "+Enter", "Maximize");
        addRow(ui, COMMAND + "+B", "Toggle GUI");
        addRow(ui, "H",            "Show Help (this Window)");
        addRow(ui, COMMAND + "+P", "Find Image or Channel Group");
        addRow(ui, COMMAND + "+Q", "Quit");
    }

    // About tab
    {
        Widget* about = new Widget(tabWidget);
        about->set_layout(new GroupLayout{});
        tabWidget->append_tab("About", about);

        auto addText = [](Widget* current, string text, string font = "sans", int fontSize = 18) {
            auto row = new Widget{current};
            row->set_layout(new BoxLayout{Orientation::Vertical, Alignment::Middle, 0, 10});
            new Label{row, text, font, fontSize };
        };

        auto addLibrary = [](Widget* current, string name, string license, string desc) {
            auto row = new Widget{current};
            row->set_layout(new BoxLayout{Orientation::Horizontal, Alignment::Fill, 3, 30});
            auto leftColumn = new Widget{row};
            leftColumn->set_layout(new BoxLayout{Orientation::Vertical, Alignment::Maximum});
            leftColumn->set_fixed_width(135);

            new Label{leftColumn, name, "sans-bold", 18};
            new Label{row, desc, "sans", 18};
        };

        auto addSpacer = [](Widget* current, int space) {
            auto row = new Widget{current};
            row->set_height(space);
        };

        addSpacer(about, 15);

        addText(about, "tev — The EXR Viewer", "sans-bold", 46);
        addText(about, "version " TEV_VERSION, "sans", 26);

        addSpacer(about, 50);

        addText(about, "tev was developed by Thomas Müller and is released under the BSD 3-Clause License.");
        addText(about, "It was built directly or indirectly upon the following amazing third-party libraries.");

        addSpacer(about, 30);

        addLibrary(about, "args",              "", "Single-Header Argument Parsing Library");
        addLibrary(about, "clip",              "", "Cross-Platform Clipboard Library");
        addLibrary(about, "{fmt}",             "", "Fast & Safe Formatting Library");
        addLibrary(about, "Glad",              "", "Multi-Language GL Loader-Generator");
        addLibrary(about, "GLFW",              "", "OpenGL Desktop Development Library");
        addLibrary(about, "NanoGUI",           "", "Small GUI Library");
        addLibrary(about, "NanoVG",            "", "Small Vector Graphics Library");
        addLibrary(about, "OpenEXR",           "", "High Dynamic-Range (HDR) Image File Format");
        addLibrary(about, "qoi",               "", "File Format for Fast, Lossless Image Compression");
        addLibrary(about, "stb_image(_write)", "", "Single-Header Library for Loading and Writing Images");
        addLibrary(about, "tinylogger",        "", "Minimal Pretty-Logging Library");
        addLibrary(about, "UTF8-CPP",          "", "Lightweight UTF-8 String Manipulation Library");
    }

    tabWidget->set_selected_id(0);
    tabWidget->set_callback([tabWidget] (int id) mutable {
        tabWidget->set_selected_id(id);
    });
}

bool HelpWindow::keyboard_event(int key, int scancode, int action, int modifiers) {
    if (Window::keyboard_event(key, scancode, action, modifiers)) {
        return true;
    }

    if (key == GLFW_KEY_ESCAPE) {
        mCloseCallback();
        return true;
    }

    return false;
}

TEV_NAMESPACE_END
<commit_msg>Several `HelpWindow` improvements<commit_after>// This file was developed by Thomas Müller <thomas94@gmx.net>.
// It is published under the BSD 3-Clause License within the LICENSE file.

#include <tev/HelpWindow.h>

#include <nanogui/button.h>
#include <nanogui/icons.h>
#include <nanogui/label.h>
#include <nanogui/layout.h>
#include <nanogui/opengl.h>
#include <nanogui/screen.h>
#include <nanogui/tabwidget.h>
#include <nanogui/vscrollpanel.h>
#include <nanogui/window.h>

using namespace nanogui;
using namespace std;

TEV_NAMESPACE_BEGIN

#ifdef __APPLE__
string HelpWindow::COMMAND = "Cmd";
#else
string HelpWindow::COMMAND = "Ctrl";
#endif

#ifdef __APPLE__
string HelpWindow::ALT = "Opt";
#else
string HelpWindow::ALT = "Alt";
#endif

HelpWindow::HelpWindow(Widget* parent, bool supportsHdr, function<void()> closeCallback)
    : Window{parent, "Help"}, mCloseCallback{closeCallback} {

    auto closeButton = new Button{button_panel(), "", FA_TIMES};
    closeButton->set_callback(mCloseCallback);

    set_layout(new GroupLayout{});
    set_fixed_width(600);

    TabWidget* tabWidget = new TabWidget{this};

    // Keybindings tab
    Widget* tmp = new Widget(tabWidget);
    // tmp->set_fixed_height(400);
    VScrollPanel* scrollPanel = new VScrollPanel{tmp};
    tabWidget->append_tab("Keybindings", tmp);

    Widget* shortcuts = new Widget(scrollPanel);
    shortcuts->set_layout(new GroupLayout{});

    auto addRow = [](Widget* current, string keys, string desc) {
        auto row = new Widget{current};
        row->set_layout(new BoxLayout{Orientation::Horizontal, Alignment::Fill, 0, 10});
        auto descWidget = new Label{row, desc, "sans"};
        descWidget->set_fixed_width(250);
        new Label{row, keys, "sans-bold"};
    };

    new Label{shortcuts, "Image loading", "sans-bold", 18};
    auto imageLoading = new Widget{shortcuts};
    imageLoading->set_layout(new BoxLayout{Orientation::Vertical, Alignment::Fill, 0, 0});

    addRow(imageLoading, COMMAND + "+O",                             "Open image");
    addRow(imageLoading, COMMAND + "+S",                             "Save view as image");
    addRow(imageLoading, COMMAND + "+R or F5",                       "Reload image");
    addRow(imageLoading, COMMAND + "+Shift+R or " + COMMAND + "+F5", "Reload all images");
    addRow(imageLoading, COMMAND + "+W",                             "Close image");
    addRow(imageLoading, COMMAND + "+Shift+W",                       "Close all images");
    addRow(imageLoading, COMMAND + "+C",                             "Copy image or path to clipboard");
    addRow(imageLoading, COMMAND + "+V",                             "Paste image from clipboard");

    new Label{shortcuts, "Image options", "sans-bold", 18};
    auto imageSelection = new Widget{shortcuts};
    imageSelection->set_layout(new BoxLayout{Orientation::Vertical, Alignment::Fill, 0, 0});

    addRow(imageSelection, "Left Click",          "Select hovered image");
    addRow(imageSelection, "1…9",                 "Select N-th image");
    addRow(imageSelection, "Down or S / Up or W", "Select next / previous image");
    addRow(imageSelection, "Home / End",          "Select first / last image");
    addRow(imageSelection, "Space",               "Toggle playback of images as video");

    addRow(imageSelection, "Click & Drag (+Shift/" + COMMAND + ")", "Translate image");
    addRow(imageSelection, "+ / - / Scroll (+Shift/" + COMMAND + ")", "Zoom in / out of image");

    addRow(imageSelection, "F", "Fit image to screen");
    addRow(imageSelection, "N", "Normalize image to [0, 1]");
    addRow(imageSelection, "R", "Reset image parameters");
    if (supportsHdr) {
        addRow(imageSelection, "L", "Display the image as if on an LDR screen");
    }

    addRow(imageSelection, "Shift+Right or Shift+D / Shift+Left or Shift+A", "Select next / previous tonemap");

    addRow(imageSelection, "E / Shift+E", "Increase / decrease exposure by 0.5");
    addRow(imageSelection, "O / Shift+O", "Increase / decrease offset by 0.1");

    addRow(imageSelection, "Shift+Ctrl (hold)", "Display raw bytes on pixels when zoomed-in");

    new Label{shortcuts, "Reference options", "sans-bold", 18};
    auto referenceSelection = new Widget{shortcuts};
    referenceSelection->set_layout(new BoxLayout{Orientation::Vertical, Alignment::Fill, 0, 0});

    addRow(referenceSelection, ALT + " (hold)",                               "View currently selected reference");
    addRow(referenceSelection, "Shift+Left Click or Right Click",             "Select hovered image as reference");
    addRow(referenceSelection, "Shift+1…9",                                   "Select N-th image as reference");
    addRow(referenceSelection, "Shift+Down or Shift+S / Shift+Up or Shift+W", "Select next / previous image as reference");

    addRow(referenceSelection, "Ctrl (hold)",                                "View selected image if reference is selected");
    addRow(referenceSelection, "Ctrl+Right or Ctrl+D / Ctrl+Left or Ctrl+A", "Select next / previous error metric");

    new Label{shortcuts, "Channel group options", "sans-bold", 18};
    auto groupSelection = new Widget{shortcuts};
    groupSelection->set_layout(new BoxLayout{Orientation::Vertical, Alignment::Fill, 0, 0});

    addRow(groupSelection, "Left Click",             "Select hovered channel group");
    addRow(groupSelection, "Ctrl+1…9",               "Select N-th channel group");
    addRow(groupSelection, "Right or D / Left or A", "Select next / previous channel group");

    new Label{shortcuts, "Interface", "sans-bold", 18};
    auto ui = new Widget{shortcuts};
    ui->set_layout(new BoxLayout{Orientation::Vertical, Alignment::Fill, 0, 0});

    addRow(ui, ALT + "+Enter", "Maximize");
    addRow(ui, COMMAND + "+B", "Toggle GUI");
    addRow(ui, "H",            "Show help (this window)");
    addRow(ui, COMMAND + "+P", "Find image or channel group");
    addRow(ui, COMMAND + "+Q", "Quit");

    // About tab
    Widget* about = new Widget(tabWidget);
    about->set_layout(new GroupLayout{});
    tabWidget->append_tab("About", about);

    auto addText = [](Widget* current, string text, string font = "sans", int fontSize = 18) {
        auto row = new Widget{current};
        row->set_layout(new BoxLayout{Orientation::Vertical, Alignment::Middle, 0, 10});
        new Label{row, text, font, fontSize };
    };

    auto addLibrary = [](Widget* current, string name, string license, string desc) {
        auto row = new Widget{current};
        row->set_layout(new BoxLayout{Orientation::Horizontal, Alignment::Fill, 3, 30});
        auto leftColumn = new Widget{row};
        leftColumn->set_layout(new BoxLayout{Orientation::Vertical, Alignment::Maximum});
        leftColumn->set_fixed_width(135);

        new Label{leftColumn, name, "sans-bold", 18};
        new Label{row, desc, "sans", 18};
    };

    auto addSpacer = [](Widget* current, int space) {
        auto row = new Widget{current};
        row->set_height(space);
    };

    addSpacer(about, 15);

    addText(about, "tev — The EXR Viewer", "sans-bold", 46);
    addText(about, "version " TEV_VERSION, "sans", 26);

    addSpacer(about, 50);

    addText(about, "tev was developed by Thomas Müller and is released under the BSD 3-Clause License.");
    addText(about, "It was built directly or indirectly upon the following amazing third-party libraries.");

    addSpacer(about, 30);

    addLibrary(about, "args",              "", "Single-Header Argument Parsing Library");
    addLibrary(about, "clip",              "", "Cross-Platform Clipboard Library");
    addLibrary(about, "{fmt}",             "", "Fast & Safe Formatting Library");
    addLibrary(about, "Glad",              "", "Multi-Language GL Loader-Generator");
    addLibrary(about, "GLFW",              "", "OpenGL Desktop Development Library");
    addLibrary(about, "NanoGUI",           "", "Small GUI Library");
    addLibrary(about, "NanoVG",            "", "Small Vector Graphics Library");
    addLibrary(about, "OpenEXR",           "", "High Dynamic-Range (HDR) Image File Format");
    addLibrary(about, "qoi",               "", "File Format for Fast, Lossless Image Compression");
    addLibrary(about, "stb_image(_write)", "", "Single-Header Library for Loading and Writing Images");
    addLibrary(about, "tinylogger",        "", "Minimal Pretty-Logging Library");
    addLibrary(about, "UTF8-CPP",          "", "Lightweight UTF-8 String Manipulation Library");

    // Make the keybindings page as big as is needed to fit the about tab
    perform_layout(screen()->nvg_context());
    scrollPanel->set_fixed_height(about->height() + 12);

    tabWidget->set_selected_id(0);
    tabWidget->set_callback([tabWidget] (int id) mutable {
        tabWidget->set_selected_id(id);
    });
}

bool HelpWindow::keyboard_event(int key, int scancode, int action, int modifiers) {
    if (Window::keyboard_event(key, scancode, action, modifiers)) {
        return true;
    }

    if (key == GLFW_KEY_ESCAPE) {
        mCloseCallback();
        return true;
    }

    return false;
}

TEV_NAMESPACE_END
<|endoftext|>


<commit_before>
/*
 * MIT License
 *
 * Copyright (c) 2017 Susanow
 * Copyright (c) 2017 Hiroki SHIROKURA
 *
 * 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 <ssn_common.h>
#include <ssn_ma_ring.h>

int main(int argc, char** argv)
{
  constexpr size_t n_que = 8;
  constexpr size_t n_enq_acc = 4;
  constexpr size_t n_deq_acc = 2;
  ssn_init(argc, argv);

  ssn_ma_ring ring0;
  ring0.configure_que(n_que);
  ring0.configure_acc(n_enq_acc, n_deq_acc);
  ring0.debug_dump(stdout);

  size_t n_enq;
  size_t n_deq;
  size_t* send_buf[1] = { nullptr };
  size_t* recv_buf[32];

  slankdev::waitmsg("phase 1");
  n_enq = ring0.enqueue_burst(0, (void**)send_buf, 1);
  printf("n_enq: %zd \n", n_enq);
  ring0.debug_dump(stdout);

  slankdev::waitmsg("phase 2");
  n_enq = ring0.enqueue_burst(0, (void**)send_buf, 1);
  printf("n_enq: %zd \n", n_enq);
  ring0.debug_dump(stdout);

  slankdev::waitmsg("phase 3");
  n_enq = ring0.enqueue_burst(1, (void**)send_buf, 1);
  printf("n_enq: %zd \n", n_enq);
  ring0.debug_dump(stdout);

  slankdev::waitmsg("phase 4");
  n_deq = ring0.dequeue_burst(0, (void**)recv_buf, 32);
  printf("n_deq: %zd \n", n_deq);
  ring0.debug_dump(stdout);

  slankdev::waitmsg("phase 4");
  n_deq = ring0.dequeue_burst(0, (void**)recv_buf, 32);
  printf("n_deq: %zd \n", n_deq);
  ring0.debug_dump(stdout);

  slankdev::waitmsg("phase 4");
  n_deq = ring0.dequeue_burst(0, (void**)recv_buf, 32);
  printf("n_deq: %zd \n", n_deq);
  ring0.debug_dump(stdout);

  slankdev::waitmsg("phase 5");
  n_enq = ring0.enqueue_burst(0, (void**)send_buf, 1);
  printf("n_enq: %zd \n", n_enq);
  ring0.debug_dump(stdout);
}

<commit_msg>hotfix bug test_ssn_ma_ring<commit_after>
/*
 * MIT License
 *
 * Copyright (c) 2017 Susanow
 * Copyright (c) 2017 Hiroki SHIROKURA
 *
 * 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 <ssn_common.h>
#include <ssn_ma_ring.h>

int main(int argc, char** argv)
{
  constexpr size_t n_que = 8;
  constexpr size_t n_enq_acc = 4;
  constexpr size_t n_deq_acc = 2;
  ssn_init(argc, argv);

  ssn_ma_ring ring0("test_ring");
  ring0.configure_que(n_que);
  ring0.configure_acc(n_enq_acc, n_deq_acc);
  ring0.debug_dump(stdout);

  size_t n_enq;
  size_t n_deq;
  size_t* send_buf[1] = { nullptr };
  size_t* recv_buf[32];

  slankdev::waitmsg("phase 1");
  n_enq = ring0.enqueue_burst(0, (void**)send_buf, 1);
  printf("n_enq: %zd \n", n_enq);
  ring0.debug_dump(stdout);

  slankdev::waitmsg("phase 2");
  n_enq = ring0.enqueue_burst(0, (void**)send_buf, 1);
  printf("n_enq: %zd \n", n_enq);
  ring0.debug_dump(stdout);

  slankdev::waitmsg("phase 3");
  n_enq = ring0.enqueue_burst(1, (void**)send_buf, 1);
  printf("n_enq: %zd \n", n_enq);
  ring0.debug_dump(stdout);

  slankdev::waitmsg("phase 4");
  n_deq = ring0.dequeue_burst(0, (void**)recv_buf, 32);
  printf("n_deq: %zd \n", n_deq);
  ring0.debug_dump(stdout);

  slankdev::waitmsg("phase 4");
  n_deq = ring0.dequeue_burst(0, (void**)recv_buf, 32);
  printf("n_deq: %zd \n", n_deq);
  ring0.debug_dump(stdout);

  slankdev::waitmsg("phase 4");
  n_deq = ring0.dequeue_burst(0, (void**)recv_buf, 32);
  printf("n_deq: %zd \n", n_deq);
  ring0.debug_dump(stdout);

  slankdev::waitmsg("phase 5");
  n_enq = ring0.enqueue_burst(0, (void**)send_buf, 1);
  printf("n_enq: %zd \n", n_enq);
  ring0.debug_dump(stdout);
}

<|endoftext|>


<commit_before>
// Bindings
#include "PyROOTWrapper.h"

// Cppyy
#include "CPyCppyy.h"
#include "ProxyWrappers.h"

// ROOT
#include "TROOT.h"
#include "TSystem.h"
#include "TClass.h"
#include "TDataMember.h"
#include "TClassEdit.h"
#include "TEnum.h"
#include "TEnumConstant.h"
#include "TInterpreter.h"
#include "TGlobal.h"
#include "DllImport.h"

namespace PyROOT {
R__EXTERN PyObject *gRootModule;
}

using namespace PyROOT;

namespace {

inline void AddToGlobalScope(const char *label, const char * /* hdr */, TObject *obj, Cppyy::TCppType_t klass)
{
   // Bind the given object with the given class in the global scope with the
   // given label for its reference.
   PyModule_AddObject(gRootModule, const_cast<char *>(label), CPyCppyy::BindCppObjectNoCast(obj, klass));
}

} // unnamed namespace

void PyROOT::InitPyROOT()
{
   // Initialize and acquire the GIL to allow for threading in ROOT
   PyEval_InitThreads();

   // Bind ROOT globals that will be needed in ROOT.py
   AddToGlobalScope("gROOT", "TROOT.h", gROOT, Cppyy::GetScope(gROOT->IsA()->GetName()));
   AddToGlobalScope("gSystem", "TSystem.h", gSystem, Cppyy::GetScope(gSystem->IsA()->GetName()));
   AddToGlobalScope("gInterpreter", "TInterpreter.h", gInterpreter, Cppyy::GetScope(gInterpreter->IsA()->GetName()));
}
<commit_msg>Make AddToGlobalScope static but not inline<commit_after>
// Bindings
#include "PyROOTWrapper.h"

// Cppyy
#include "CPyCppyy.h"
#include "ProxyWrappers.h"

// ROOT
#include "TROOT.h"
#include "TSystem.h"
#include "TClass.h"
#include "TDataMember.h"
#include "TClassEdit.h"
#include "TEnum.h"
#include "TEnumConstant.h"
#include "TInterpreter.h"
#include "TGlobal.h"
#include "DllImport.h"

namespace PyROOT {
R__EXTERN PyObject *gRootModule;
}

using namespace PyROOT;

namespace {

static void AddToGlobalScope(const char *label, const char * /* hdr */, TObject *obj, Cppyy::TCppType_t klass)
{
   // Bind the given object with the given class in the global scope with the
   // given label for its reference.
   PyModule_AddObject(gRootModule, const_cast<char *>(label), CPyCppyy::BindCppObjectNoCast(obj, klass));
}

} // unnamed namespace

void PyROOT::InitPyROOT()
{
   // Initialize and acquire the GIL to allow for threading in ROOT
   PyEval_InitThreads();

   // Bind ROOT globals that will be needed in ROOT.py
   AddToGlobalScope("gROOT", "TROOT.h", gROOT, Cppyy::GetScope(gROOT->IsA()->GetName()));
   AddToGlobalScope("gSystem", "TSystem.h", gSystem, Cppyy::GetScope(gSystem->IsA()->GetName()));
   AddToGlobalScope("gInterpreter", "TInterpreter.h", gInterpreter, Cppyy::GetScope(gInterpreter->IsA()->GetName()));
}
<|endoftext|>


<commit_before>/* -*- mode: c++; fill-column: 132; c-basic-offset: 4; indent-tabs-mode: nil -*- */

// =-=-=-=-=-=-=-
#include "irods_file_object.hpp"
#include "irods_resource_manager.hpp"
#include "irods_hierarchy_parser.hpp"
#include "irods_log.hpp"
#include "irods_stacktrace.hpp"
#include "irods_hierarchy_parser.hpp"
#include "irods_resource_backport.hpp"

// =-=-=-=-=-=-=-
// irods includes
#include "miscServerFunct.hpp"
#include "dataObjOpr.hpp"
#include "objDesc.hpp"

// =-=-=-=-=-=-=-
// boost includes
#include <boost/asio/ip/host_name.hpp>

namespace irods {
// =-=-=-=-=-=-=-
// public - ctor
    file_object::file_object() :
        data_object(),
        file_descriptor_( -1 ),
        size_( 0 ),
        repl_requested_( -1 ) {
    } // file_object

// =-=-=-=-=-=-=-
// public - cctor
    file_object::file_object(
        const file_object& _rhs ) :
        data_object( _rhs ) {
        // =-=-=-=-=-=-=-
        // explicit initialization
        comm_           = _rhs.comm_;
        logical_path_   = _rhs.logical_path_;
        data_type_      = _rhs.data_type_;
        file_descriptor_ = _rhs.file_descriptor_;
        l1_desc_idx_    = _rhs.l1_desc_idx_;
        size_           = _rhs.size_;
        repl_requested_ = _rhs.repl_requested_;
        replicas_       = _rhs.replicas_;
        in_pdmo_        = _rhs.in_pdmo_;

    } // cctor

// =-=-=-=-=-=-=-
// public - ctor
    file_object::file_object(
        rsComm_t* _c,
        const std::string& _logical_path,
        const std::string& _fn,
        const std::string& _resc_hier,
        int _fd,
        int _m,
        int _f ) :
        data_object(
            _fn,
            _resc_hier,
            _m,
            _f ),
        comm_( _c ),
        logical_path_( _logical_path ),
        data_type_( "" ),
        file_descriptor_( _fd ),
        l1_desc_idx_( -1 ),
        size_( -1 ),
        repl_requested_( -1 ) {
        // =-=-=-=-=-=-=-
        // explicit initialization
        replicas_.empty();
    } // file_object

// from dataObjInfo
    file_object::file_object(
        rsComm_t*            _rsComm,
        const dataObjInfo_t* _dataObjInfo ) {
        logical_path( _dataObjInfo->objPath );

        comm_           = _rsComm;
        physical_path_  = _dataObjInfo->filePath;
        resc_hier_      = _dataObjInfo->rescHier;
        flags_          = _dataObjInfo->flags;
        repl_requested_ = _dataObjInfo->replNum;
        replicas_.empty();
        // should mode be set here? - hcj
        replKeyVal( &_dataObjInfo->condInput, &cond_input_ );
        int l1descInx = getL1descIndexByDataObjInfo( _dataObjInfo );
        if( l1descInx != -1 )
        {
            int l3descInx = L1desc[ l1descInx ].l3descInx;
            file_descriptor_ = FileDesc[ l3descInx ].fd;
        }
        else
        {
            file_descriptor_ = -1;
        }
    }

// =-=-=-=-=-=-=-
// public - dtor
    file_object::~file_object() {
        clearKeyVal( &cond_input_ );
    } // dtor

// =-=-=-=-=-=-=-
// public - assignment operator
    file_object& file_object::operator=(
        const file_object& _rhs ) {
        // =-=-=-=-=-=-=-
        // call base class assignment first
        data_object::operator=( _rhs );

        comm_           = _rhs.comm_;
        logical_path_   = _rhs.logical_path_;
        data_type_      = _rhs.data_type_;
        file_descriptor_ = _rhs.file_descriptor_;
        l1_desc_idx_    = _rhs.l1_desc_idx_;
        size_           = _rhs.size_;
        repl_requested_ = _rhs.repl_requested_;
        replicas_       = _rhs.replicas_;
        in_pdmo_        = _rhs.in_pdmo_;
        replKeyVal( &_rhs.cond_input_, &cond_input_ );

        return *this;

    }  // operator=

// public comparison operator
    bool file_object::operator==(
        const file_object& _rhs ) const {
        bool result = true;
        if ( this->repl_requested() != _rhs.repl_requested() ||
                this->logical_path() != _rhs.logical_path() ) {
            result = false;
        }
        return result;
    }

// =-=-=-=-=-=-=-
// plugin - resolve resource plugin for this object
    error file_object::resolve(
        const std::string& _interface,
        plugin_ptr&        _ptr ) {
        // =-=-=-=-=-=-=-
        // check to see if this is for a resource plugin
        // resolution, otherwise it is an error
        if ( RESOURCE_INTERFACE != _interface ) {
            std::stringstream msg;
            msg << "file_object does not support a [";
            msg << _interface;
            msg << "] for plugin resolution";
            return ERROR( SYS_INVALID_INPUT_PARAM, msg.str() );
        }

        error result = SUCCESS();
        error ret;

        hierarchy_parser hparse;
        ret = hparse.set_string( resc_hier() );

        if ( !ret.ok() ) {
            std::stringstream msg;
            msg << "error parsing resource hierarchy \"" << resc_hier() << "\"";
            result = PASSMSG( msg.str(), ret );
        }
        else {
            std::string resc;

            ret = hparse.first_resc( resc );
            if ( !ret.ok() ) {
                std::stringstream msg;
                msg << __FUNCTION__ << " - ERROR getting first resource from hierarchy.";
                result = PASSMSG( msg.str(), ret );
            }
            else {

                if ( resc.empty() && resc_hier().empty() ) {
                    //std::stringstream msg;
                    //msg << __FUNCTION__
                    //    << " - there is no resource specified in the resource hierarchy.";
                    //log(LOG_NOTICE, msg.str());
                }
                else if ( resc.empty() ) {
                    return ERROR( HIERARCHY_ERROR, "Hierarchy string is not empty but first resource is!" );
                }

                resource_ptr resc_ptr;
                ret = resc_mgr.resolve( resc, resc_ptr );
                if ( !ret.ok() ) {
                    std::stringstream msg;
                    msg << __FUNCTION__ << " - ERROR resolving resource \"" << resc << "\"";
                    result = PASSMSG( msg.str(), ret );
                }

                _ptr = boost::dynamic_pointer_cast< resource >( resc_ptr );
            }
        }

        return result;

    } // resolve

// =-=-=-=-=-=-=-
// public - get vars from object for rule engine
    error file_object::get_re_vars(
        keyValPair_t& _kvp ) {
        data_object::get_re_vars( _kvp );

        copyKeyVal( &cond_input_, &_kvp );

        addKeyVal( &_kvp, LOGICAL_PATH_KW, logical_path_.c_str() );
        addKeyVal( &_kvp, DATA_TYPE_KW,    data_type_.c_str() );

        std::stringstream fd;
        fd << file_descriptor_;
        addKeyVal( &_kvp, FILE_DESCRIPTOR_KW, fd.str().c_str() );

        std::stringstream idx;
        idx << l1_desc_idx_;
        addKeyVal( &_kvp, L1_DESC_IDX_KW, idx.str().c_str() );

        std::stringstream sz;
        sz << size_;
        addKeyVal( &_kvp, SIZE_KW, sz.str().c_str() );

        std::stringstream repl;
        repl << repl_requested_;
        addKeyVal( &_kvp, REPL_REQUESTED_KW, repl.str().c_str() );

        std::stringstream pdmo;
        pdmo << in_pdmo_;
        addKeyVal( &_kvp, IN_PDMO_KW, pdmo.str().c_str() );

        return SUCCESS();

    } // get_re_vars

// =-=-=-=-=-=-=-
// static factory to create file_object from dataobjinfo linked list
    error file_object_factory( rsComm_t*        _comm,
                               dataObjInp_t*    _data_obj_inp,
                               file_object_ptr  _file_obj ) {
        // =-=-=-=-=-=-=-
        // if a repl is requested, cache that fact
        char* repl_num_ptr = getValByKey( &_data_obj_inp->condInput, REPL_NUM_KW );
        std::string repl_num;
        if ( repl_num_ptr ) {
            repl_num = repl_num_ptr;
            rmKeyVal( &_data_obj_inp->condInput, REPL_NUM_KW );
        }

        // =-=-=-=-=-=-=-
        // make a call to build the linked list
        dataObjInfo_t* head_ptr = 0;

        int status = getDataObjInfoIncSpecColl( _comm, _data_obj_inp, &head_ptr );
        if ( status < 0 ) {
            status = getDataObjInfo( _comm, _data_obj_inp, &head_ptr, 0, 0 );
        }
        if ( 0 == head_ptr || status < 0 ) {
            if ( head_ptr ) {
                freeAllDataObjInfo( head_ptr );
            }

            char* sys_error;
            char* rods_error = rodsErrorName( status, &sys_error );
            std::stringstream msg;
            msg << "failed in call to getDataObjInfoIncSpecColl";
            msg << " for [";
            msg << _data_obj_inp->objPath;
            msg << "] ";
            msg << rods_error << " " << sys_error;
            return ERROR( status, msg.str() );
        }

        // =-=-=-=-=-=-=-
        // replace the keyword
        if ( !repl_num.empty() ) {
            addKeyVal(
                &_data_obj_inp->condInput,
                REPL_NUM_KW,
                repl_num.c_str() );
        }

        // =-=-=-=-=-=-=-
        // start populating file_object
        _file_obj->comm( _comm );
        _file_obj->logical_path( _data_obj_inp->objPath );
        _file_obj->resc_hier( head_ptr->rescHier );
        _file_obj->cond_input( _data_obj_inp->condInput );

        // =-=-=-=-=-=-=-
        // handle requested repl number
        if ( !repl_num.empty() ) {
            _file_obj->repl_requested( atoi( repl_num.c_str() ) );
        }

        // handle the case where we are being called as part of a pdmo
        char* in_pdmo = getValByKey( &_data_obj_inp->condInput, IN_PDMO_KW );
        if ( in_pdmo ) {
            _file_obj->in_pdmo( in_pdmo );
        }

        // =-=-=-=-=-=-=-
        // iterate over the linked list and populate
        // the physical_object vector in the file_object
        dataObjInfo_t* info_ptr = head_ptr;
        std::vector< physical_object > objects;
        while ( info_ptr ) {
            physical_object obj;

            obj.is_dirty( info_ptr->replStatus );
            obj.repl_num( info_ptr->replNum );
            obj.map_id( info_ptr->dataMapId );
            obj.size( info_ptr->dataSize );
            obj.id( info_ptr->dataId );
            obj.coll_id( info_ptr->collId );
            obj.name( info_ptr->objPath );
            obj.version( info_ptr->version );
            obj.type_name( info_ptr->dataType );
            obj.resc_group_name( info_ptr->rescGroupName );
            obj.resc_name( info_ptr->rescName );
            obj.path( info_ptr->filePath );
            obj.owner_name( info_ptr->dataOwnerName );
            obj.owner_zone( info_ptr->dataOwnerZone );
            obj.status( info_ptr->statusString );
            obj.checksum( info_ptr->chksum );
            obj.expiry_ts( info_ptr->dataExpiry );
            obj.mode( info_ptr->dataMode );
            obj.r_comment( info_ptr->dataComments );
            obj.create_ts( info_ptr->dataCreate );
            obj.modify_ts( info_ptr->dataModify );
            obj.resc_hier( info_ptr->rescHier );

            objects.push_back( obj );
            info_ptr = info_ptr->next;

        } // while

        _file_obj->replicas( objects );

        //delete head_ptr->rescInfo;
        //free( head_ptr );
        freeAllDataObjInfo( head_ptr );
        return SUCCESS();

    } // file_object_factory

}; // namespace irods

<commit_msg>[#1376] fixed initialisation problems<commit_after>/* -*- mode: c++; fill-column: 132; c-basic-offset: 4; indent-tabs-mode: nil -*- */

// =-=-=-=-=-=-=-
#include "irods_file_object.hpp"
#include "irods_resource_manager.hpp"
#include "irods_hierarchy_parser.hpp"
#include "irods_log.hpp"
#include "irods_stacktrace.hpp"
#include "irods_hierarchy_parser.hpp"
#include "irods_resource_backport.hpp"

// =-=-=-=-=-=-=-
// irods includes
#include "miscServerFunct.hpp"
#include "dataObjOpr.hpp"
#include "objDesc.hpp"

// =-=-=-=-=-=-=-
// boost includes
#include <boost/asio/ip/host_name.hpp>

namespace irods {
// =-=-=-=-=-=-=-
// public - ctor
    file_object::file_object() :
        data_object(),
        file_descriptor_( -1 ),
        l1_desc_idx_( -1 ),
        size_( 0 ),
        repl_requested_( -1 ) {
    } // file_object

// =-=-=-=-=-=-=-
// public - cctor
    file_object::file_object(
        const file_object& _rhs ) :
        data_object( _rhs ) {
        // =-=-=-=-=-=-=-
        // explicit initialization
        comm_           = _rhs.comm_;
        logical_path_   = _rhs.logical_path_;
        data_type_      = _rhs.data_type_;
        file_descriptor_ = _rhs.file_descriptor_;
        l1_desc_idx_    = _rhs.l1_desc_idx_;
        size_           = _rhs.size_;
        repl_requested_ = _rhs.repl_requested_;
        replicas_       = _rhs.replicas_;
        in_pdmo_        = _rhs.in_pdmo_;

    } // cctor

// =-=-=-=-=-=-=-
// public - ctor
    file_object::file_object(
        rsComm_t* _c,
        const std::string& _logical_path,
        const std::string& _fn,
        const std::string& _resc_hier,
        int _fd,
        int _m,
        int _f ) :
        data_object(
            _fn,
            _resc_hier,
            _m,
            _f ),
        comm_( _c ),
        logical_path_( _logical_path ),
        data_type_( "" ),
        file_descriptor_( _fd ),
        l1_desc_idx_( -1 ),
        size_( 0 ),
        repl_requested_( -1 ) {
        // =-=-=-=-=-=-=-
        // explicit initialization
        replicas_.empty();
    } // file_object

// from dataObjInfo
    file_object::file_object(
        rsComm_t*            _rsComm,
        const dataObjInfo_t* _dataObjInfo ) {

        data_type_      = _dataObjInfo->dataType;
        comm_           = _rsComm;
        logical_path_   = _dataObjInfo->objPath;
        physical_path_  = _dataObjInfo->filePath;
        resc_hier_      = _dataObjInfo->rescHier;
        flags_          = _dataObjInfo->flags;
        repl_requested_ = _dataObjInfo->replNum;
        replicas_.empty();
        replKeyVal( &_dataObjInfo->condInput, &cond_input_ );
        l1_desc_idx_ = getL1descIndexByDataObjInfo( _dataObjInfo );
        size_ = _dataObjInfo->dataSize;
        if( l1_desc_idx_ != -1 )
        {
            int l3descInx = L1desc[ l1_desc_idx_ ].l3descInx;
            file_descriptor_ = FileDesc[ l3descInx ].fd;
        }
        else
        {
            file_descriptor_ = -1;
        }
    }

// =-=-=-=-=-=-=-
// public - dtor
    file_object::~file_object() {
        clearKeyVal( &cond_input_ );
    } // dtor

// =-=-=-=-=-=-=-
// public - assignment operator
    file_object& file_object::operator=(
        const file_object& _rhs ) {
        // =-=-=-=-=-=-=-
        // call base class assignment first
        data_object::operator=( _rhs );

        comm_           = _rhs.comm_;
        logical_path_   = _rhs.logical_path_;
        data_type_      = _rhs.data_type_;
        file_descriptor_ = _rhs.file_descriptor_;
        l1_desc_idx_    = _rhs.l1_desc_idx_;
        size_           = _rhs.size_;
        repl_requested_ = _rhs.repl_requested_;
        replicas_       = _rhs.replicas_;
        in_pdmo_        = _rhs.in_pdmo_;
        replKeyVal( &_rhs.cond_input_, &cond_input_ );

        return *this;

    }  // operator=

// public comparison operator
    bool file_object::operator==(
        const file_object& _rhs ) const {
        bool result = true;
        if ( this->repl_requested() != _rhs.repl_requested() ||
                this->logical_path() != _rhs.logical_path() ) {
            result = false;
        }
        return result;
    }

// =-=-=-=-=-=-=-
// plugin - resolve resource plugin for this object
    error file_object::resolve(
        const std::string& _interface,
        plugin_ptr&        _ptr ) {
        // =-=-=-=-=-=-=-
        // check to see if this is for a resource plugin
        // resolution, otherwise it is an error
        if ( RESOURCE_INTERFACE != _interface ) {
            std::stringstream msg;
            msg << "file_object does not support a [";
            msg << _interface;
            msg << "] for plugin resolution";
            return ERROR( SYS_INVALID_INPUT_PARAM, msg.str() );
        }

        error result = SUCCESS();
        error ret;

        hierarchy_parser hparse;
        ret = hparse.set_string( resc_hier() );

        if ( !ret.ok() ) {
            std::stringstream msg;
            msg << "error parsing resource hierarchy \"" << resc_hier() << "\"";
            result = PASSMSG( msg.str(), ret );
        }
        else {
            std::string resc;

            ret = hparse.first_resc( resc );
            if ( !ret.ok() ) {
                std::stringstream msg;
                msg << __FUNCTION__ << " - ERROR getting first resource from hierarchy.";
                result = PASSMSG( msg.str(), ret );
            }
            else {

                if ( resc.empty() && resc_hier().empty() ) {
                    //std::stringstream msg;
                    //msg << __FUNCTION__
                    //    << " - there is no resource specified in the resource hierarchy.";
                    //log(LOG_NOTICE, msg.str());
                }
                else if ( resc.empty() ) {
                    return ERROR( HIERARCHY_ERROR, "Hierarchy string is not empty but first resource is!" );
                }

                resource_ptr resc_ptr;
                ret = resc_mgr.resolve( resc, resc_ptr );
                if ( !ret.ok() ) {
                    std::stringstream msg;
                    msg << __FUNCTION__ << " - ERROR resolving resource \"" << resc << "\"";
                    result = PASSMSG( msg.str(), ret );
                }

                _ptr = boost::dynamic_pointer_cast< resource >( resc_ptr );
            }
        }

        return result;

    } // resolve

// =-=-=-=-=-=-=-
// public - get vars from object for rule engine
    error file_object::get_re_vars(
        keyValPair_t& _kvp ) {
        data_object::get_re_vars( _kvp );

        copyKeyVal( &cond_input_, &_kvp );

        addKeyVal( &_kvp, LOGICAL_PATH_KW, logical_path_.c_str() );
        addKeyVal( &_kvp, DATA_TYPE_KW,    data_type_.c_str() );

        std::stringstream fd;
        fd << file_descriptor_;
        addKeyVal( &_kvp, FILE_DESCRIPTOR_KW, fd.str().c_str() );

        std::stringstream idx;
        idx << l1_desc_idx_;
        addKeyVal( &_kvp, L1_DESC_IDX_KW, idx.str().c_str() );

        std::stringstream sz;
        sz << size_;
        addKeyVal( &_kvp, SIZE_KW, sz.str().c_str() );

        std::stringstream repl;
        repl << repl_requested_;
        addKeyVal( &_kvp, REPL_REQUESTED_KW, repl.str().c_str() );

        std::stringstream pdmo;
        pdmo << in_pdmo_;
        addKeyVal( &_kvp, IN_PDMO_KW, pdmo.str().c_str() );

        return SUCCESS();

    } // get_re_vars

// =-=-=-=-=-=-=-
// static factory to create file_object from dataobjinfo linked list
    error file_object_factory( rsComm_t*        _comm,
                               dataObjInp_t*    _data_obj_inp,
                               file_object_ptr  _file_obj ) {
        // =-=-=-=-=-=-=-
        // if a repl is requested, cache that fact
        char* repl_num_ptr = getValByKey( &_data_obj_inp->condInput, REPL_NUM_KW );
        std::string repl_num;
        if ( repl_num_ptr ) {
            repl_num = repl_num_ptr;
            rmKeyVal( &_data_obj_inp->condInput, REPL_NUM_KW );
        }

        // =-=-=-=-=-=-=-
        // make a call to build the linked list
        dataObjInfo_t* head_ptr = 0;

        int status = getDataObjInfoIncSpecColl( _comm, _data_obj_inp, &head_ptr );
        if ( status < 0 ) {
            status = getDataObjInfo( _comm, _data_obj_inp, &head_ptr, 0, 0 );
        }
        if ( 0 == head_ptr || status < 0 ) {
            if ( head_ptr ) {
                freeAllDataObjInfo( head_ptr );
            }

            char* sys_error;
            char* rods_error = rodsErrorName( status, &sys_error );
            std::stringstream msg;
            msg << "failed in call to getDataObjInfoIncSpecColl";
            msg << " for [";
            msg << _data_obj_inp->objPath;
            msg << "] ";
            msg << rods_error << " " << sys_error;
            return ERROR( status, msg.str() );
        }

        // =-=-=-=-=-=-=-
        // replace the keyword
        if ( !repl_num.empty() ) {
            addKeyVal(
                &_data_obj_inp->condInput,
                REPL_NUM_KW,
                repl_num.c_str() );
        }

        // =-=-=-=-=-=-=-
        // start populating file_object
        _file_obj->comm( _comm );
        _file_obj->logical_path( _data_obj_inp->objPath );
        _file_obj->resc_hier( head_ptr->rescHier );
        _file_obj->cond_input( _data_obj_inp->condInput );

        // =-=-=-=-=-=-=-
        // handle requested repl number
        if ( !repl_num.empty() ) {
            _file_obj->repl_requested( atoi( repl_num.c_str() ) );
        }

        // handle the case where we are being called as part of a pdmo
        char* in_pdmo = getValByKey( &_data_obj_inp->condInput, IN_PDMO_KW );
        if ( in_pdmo ) {
            _file_obj->in_pdmo( in_pdmo );
        }

        // =-=-=-=-=-=-=-
        // iterate over the linked list and populate
        // the physical_object vector in the file_object
        dataObjInfo_t* info_ptr = head_ptr;
        std::vector< physical_object > objects;
        while ( info_ptr ) {
            physical_object obj;

            obj.is_dirty( info_ptr->replStatus );
            obj.repl_num( info_ptr->replNum );
            obj.map_id( info_ptr->dataMapId );
            obj.size( info_ptr->dataSize );
            obj.id( info_ptr->dataId );
            obj.coll_id( info_ptr->collId );
            obj.name( info_ptr->objPath );
            obj.version( info_ptr->version );
            obj.type_name( info_ptr->dataType );
            obj.resc_group_name( info_ptr->rescGroupName );
            obj.resc_name( info_ptr->rescName );
            obj.path( info_ptr->filePath );
            obj.owner_name( info_ptr->dataOwnerName );
            obj.owner_zone( info_ptr->dataOwnerZone );
            obj.status( info_ptr->statusString );
            obj.checksum( info_ptr->chksum );
            obj.expiry_ts( info_ptr->dataExpiry );
            obj.mode( info_ptr->dataMode );
            obj.r_comment( info_ptr->dataComments );
            obj.create_ts( info_ptr->dataCreate );
            obj.modify_ts( info_ptr->dataModify );
            obj.resc_hier( info_ptr->rescHier );

            objects.push_back( obj );
            info_ptr = info_ptr->next;

        } // while

        _file_obj->replicas( objects );

        //delete head_ptr->rescInfo;
        //free( head_ptr );
        freeAllDataObjInfo( head_ptr );
        return SUCCESS();

    } // file_object_factory

}; // namespace irods

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2006-2016  Music Technology Group - Universitat Pompeu Fabra
 *
 * This file is part of Essentia
 *
 * Essentia 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 (FSF), 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 General Public License for more
 * details.
 *
 * You should have received a copy of the Affero GNU General Public License
 * version 3 along with this program.  If not, see http://www.gnu.org/licenses/
 */

#include "gaiatransform.h"
#include "essentia.h"
#include <gaia2/point.h>
#include <gaia2/convert.h>

using namespace std;
using namespace essentia;
using namespace standard;

const char* GaiaTransform::name = "GaiaTransform";
const char* GaiaTransform::category = "Transformations";
const char* GaiaTransform::description = DOC(
"Applies a given Gaia2 transformation history to a given pool. It first converts the pool into a gaia2::Point suitable for the history, applies the history, and converts back the resulting point into an essentia Pool. In particular, it allows classification.\n"
"\n"
"Note that in order to enable this algorithm it is necessary to install Gaia2 library before building Essentia.\n"
"\n"
"References:\n"
"  [1] Gaia - A library for similarity in high-dimensional spaces,\n"
"  http://github.com/MTG/gaia");

void GaiaTransform::configure() {
  string filename;
  try {
    filename = parameter("history").toString();
  }
  catch (...) {}

  if (filename.empty()) {
    _configured = false;
    return;
  }

  _history.load(QString::fromStdString(filename));

  _configured = true;
}

/**
 * Create a new point with the given layout and copy those values it needs from the
 * given pool.
 */
gaia2::Point* poolToPoint(const Pool& pool, const gaia2::PointLayout& layout) {
  gaia2::Point* result = new gaia2::Point(layout);

  foreach (const QString& d, layout.descriptorNames(gaia2::RealType)) {

    string dname = d.mid(1).toStdString();
    if (pool.contains<Real>(dname)) {
      // descriptor is a single value
      Real value = pool.value<Real>(dname);
      result->setValue(d, gaia2::RealDescriptor(value));
    }
    else if (pool.contains<vector<Real> >(dname)) {
      // descriptor is a vector of reals
      const vector<Real>& value = pool.value<vector<Real> >(dname);
      result->setValue(d, gaia2::RealDescriptor(value));
    }
    else if (pool.contains<vector<vector<Real> > >(dname)) {
      // descriptor is a matrix
      const vector<vector<Real> >& value = pool.value<vector<vector<Real> > >(d.mid(1).toStdString());

      // copy it in a single vector (flatten), such as what gaia uses
      int rows = value.size();
      int cols = value[0].size();

      gaia2::RealDescriptor vecmat(2 + rows*cols, 0.0);
      vecmat[0] = rows;
      vecmat[1] = cols;
      for (int i=0; i<rows; i++) {
        for (int j=0; j<cols; j++) {
          vecmat[2+i*cols+j] = value[i][j];
        }
      }
      result->setValue(d, vecmat);
    }
    else {
      throw EssentiaException("Descriptor ", dname, " could not be found in pool");
    }

  }

  // for string descs, we need to be looking at both the string and enum types in the layout
  QStringList stringDescs = layout.descriptorNames(gaia2::StringType) +
                            layout.descriptorNames(gaia2::EnumType);

  foreach (const QString& d, stringDescs) {
    // NB: we should only have single strings here
    // ignore those descriptors which are added by the YamlOutput before giving them to Gaia
    if (d.startsWith(".metadata.version")) continue;

    string dname = d.mid(1).toStdString();
    if (pool.contains<string>(dname)) {
      // descriptor is a single string
      string label = pool.value<string>(dname);
      result->setLabel(d, gaia2::StringDescriptor(QString::fromStdString(label)));
    }
    else if (pool.contains<vector<string> >(dname)) {
      // descriptor is a list of strings
      vector<string> label = pool.value<vector<string> >(dname);
      result->setLabel(d, gaia2::convert::VectorString_to_StringDescriptor(label));
    }
    else {
      throw EssentiaException("Descriptor ", dname, " could not be found in pool");
    }
  }

  return result;
}

void checkNotIn(const string& desc, const set<string>& alldescs) {
  if (alldescs.find(desc) != alldescs.end()) {
    throw EssentiaException("GaiaTransform is trying to overwrite the ", desc, " value, which is already present in the pool. You can't do that.");
  }
}

/**
 * Copy all the values from the point inside the pool.
 */
void pointToPool(const gaia2::Point* p, Pool& pool, const Pool& origPool) {
  const gaia2::PointLayout& layout = p->layout();
  vector<string> alldescsv = pool.descriptorNames();
  set<string> alldescs(alldescsv.begin(), alldescsv.end());

  foreach (const QString& d, layout.descriptorNames(gaia2::RealType)) {
    string pooldesc = d.mid(1).toStdString();
    checkNotIn(pooldesc, alldescs);

    gaia2::RealDescriptor desc = p->value(d);

    if (desc.size() == 1)    pool.set(pooldesc, desc[0]);
    else if (desc.isEmpty()) pool.set(pooldesc, vector<Real>());
    else                     pool.set(pooldesc, vector<Real>(&desc[0],
                                                             &desc[0]+desc.size()));

    // in fact, if desc.size == 1 and we're not in the single pool, we'd better
    // put back the value as a list of size 1
    const std::map<std::string, Real>& srpool = origPool.getSingleRealPool();

    if ((desc.size() == 1) && (srpool.find(pooldesc) == srpool.end())) {
      pool.remove(pooldesc);
      for (int i=0; i<desc.size(); i++) pool.add(pooldesc, desc[i]);
    }

    // if desc was a vector<vector<Real> >, it will have been converted to a single
    // vector<Real>, where the first 2 values are the dimensions. Construct this matrix back.
    const PoolOf(std::vector<Real>)& vrpool = origPool.getVectorRealPool();

    if (vrpool.find(pooldesc) != vrpool.end()) {
      int rows = int(desc[0]);
      int cols = int(desc[1]);

      // assert we're not doing something potentially stupid
      if ((rows*cols + 2) != desc.size()) {
        E_WARNING("Oops, internal error in GaiaTransform::pointToPool, ignoring...");
        continue;
      }
      pool.remove(pooldesc);

      for (int i=0; i<rows; i++) {
        pool.add(pooldesc, vector<Real>(&desc[2+ i*cols],
                                        &desc[2+ i*cols] + cols));
      }
    }
  }

  // for string descs, we need to be looking at both the string and enum types in the layout
  QStringList stringDescs = layout.descriptorNames(gaia2::StringType) +
                            layout.descriptorNames(gaia2::EnumType);

  foreach (const QString& d, stringDescs) {
    string pooldesc = d.mid(1).toStdString();
    checkNotIn(pooldesc, alldescs);

    gaia2::StringDescriptor desc = p->label(d);

    // little check: see if we haven't removed the version before
    if (pooldesc == "metadata.version.essentia") {
      pool.set(pooldesc, essentia::version);
      continue;
    }

    if (desc.size() == 1) pool.set(pooldesc, desc[0].toStdString());
    else {
      for (int i=0; i<desc.size(); i++) {
        pool.add(pooldesc, desc[i].toStdString());
      }
    }
  }
}

void GaiaTransform::compute() {
  if (!_configured) {
    throw EssentiaException("GaiaTransform: Algorithm is not properly configured");
  }

  const Pool& inputPool = _inputPool.get();
  Pool& outputPool = _outputPool.get();

  gaia2::Point* p = poolToPoint(inputPool, _history.at(0).layout);
  gaia2::Point* result = _history.mapPoint(p, true); // p has been deleted by mapPoint

  // FIXME: should raise an exception if we overwrite a value which was previously in the pool
  pointToPool(result, outputPool, inputPool);

  // small hack: if we got an SVM transfo with associated probabilities, put them in
  // a nicer shape than the vector of anonymous reals it is.
  bool doesSVM = false;
  gaia2::ParameterMap params;
  for (int i=0; i<_history.size(); i++) {
    if (_history[i].analyzerName == "svmtrain") {
      params = _history[i].params;
      doesSVM = true;
      break;
    }
  }

  if (doesSVM && params.value("probability").toBool()) {
    // we need to remove the class and the probability vector and replace them with:
    // class:
    //   value: X
    //   probability: X
    //   all:
    //     cls1: X
    //     cls2: X
    //     ...
    QStringList classList = params.value("classMapping").toStringList();
    string className = params.value("className").toString().toStdString();
    string cls = outputPool.value<string>(className);
    vector<Real> probs = outputPool.value<vector<Real> >(className + "Probability");
    Q_ASSERT(classList.size() == (int)probs.size());

    outputPool.remove(className);
    outputPool.remove(className + "Probability");

    outputPool.set(className + ".value", cls);
    outputPool.set(className + ".probability", probs[classList.indexOf(QString::fromStdString(cls))]);
    for (int i=0; i<classList.size(); i++) {
      outputPool.set(className + ".all." + classList[i].toStdString(), probs[i]);
    }
  }

  delete result;
}

GaiaTransform::~GaiaTransform() {}
<commit_msg>Throw nicer exception on gaia history load problem<commit_after>/*
 * Copyright (C) 2006-2016  Music Technology Group - Universitat Pompeu Fabra
 *
 * This file is part of Essentia
 *
 * Essentia 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 (FSF), 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 General Public License for more
 * details.
 *
 * You should have received a copy of the Affero GNU General Public License
 * version 3 along with this program.  If not, see http://www.gnu.org/licenses/
 */

#include "gaiatransform.h"
#include "essentia.h"
#include <gaia2/point.h>
#include <gaia2/convert.h>

using namespace std;
using namespace essentia;
using namespace standard;

const char* GaiaTransform::name = "GaiaTransform";
const char* GaiaTransform::category = "Transformations";
const char* GaiaTransform::description = DOC(
"Applies a given Gaia2 transformation history to a given pool. It first converts the pool into a gaia2::Point suitable for the history, applies the history, and converts back the resulting point into an essentia Pool. In particular, it allows classification.\n"
"\n"
"Note that in order to enable this algorithm it is necessary to install Gaia2 library before building Essentia.\n"
"\n"
"References:\n"
"  [1] Gaia - A library for similarity in high-dimensional spaces,\n"
"  http://github.com/MTG/gaia");

void GaiaTransform::configure() {
  string filename;
  try {
    filename = parameter("history").toString();
  }
  catch (...) {}

  if (filename.empty()) {
    _configured = false;
    return;
  }

  try {
  _history.load(QString::fromStdString(filename));
  }
  catch (gaia2::GaiaException& e) {
    throw EssentiaException("GaiaTransform: error loading gaia history: ", e.what());
  }

  _configured = true;
}

/**
 * Create a new point with the given layout and copy those values it needs from the
 * given pool.
 */
gaia2::Point* poolToPoint(const Pool& pool, const gaia2::PointLayout& layout) {
  gaia2::Point* result = new gaia2::Point(layout);

  foreach (const QString& d, layout.descriptorNames(gaia2::RealType)) {

    string dname = d.mid(1).toStdString();
    if (pool.contains<Real>(dname)) {
      // descriptor is a single value
      Real value = pool.value<Real>(dname);
      result->setValue(d, gaia2::RealDescriptor(value));
    }
    else if (pool.contains<vector<Real> >(dname)) {
      // descriptor is a vector of reals
      const vector<Real>& value = pool.value<vector<Real> >(dname);
      result->setValue(d, gaia2::RealDescriptor(value));
    }
    else if (pool.contains<vector<vector<Real> > >(dname)) {
      // descriptor is a matrix
      const vector<vector<Real> >& value = pool.value<vector<vector<Real> > >(d.mid(1).toStdString());

      // copy it in a single vector (flatten), such as what gaia uses
      int rows = value.size();
      int cols = value[0].size();

      gaia2::RealDescriptor vecmat(2 + rows*cols, 0.0);
      vecmat[0] = rows;
      vecmat[1] = cols;
      for (int i=0; i<rows; i++) {
        for (int j=0; j<cols; j++) {
          vecmat[2+i*cols+j] = value[i][j];
        }
      }
      result->setValue(d, vecmat);
    }
    else {
      throw EssentiaException("Descriptor ", dname, " could not be found in pool");
    }

  }

  // for string descs, we need to be looking at both the string and enum types in the layout
  QStringList stringDescs = layout.descriptorNames(gaia2::StringType) +
                            layout.descriptorNames(gaia2::EnumType);

  foreach (const QString& d, stringDescs) {
    // NB: we should only have single strings here
    // ignore those descriptors which are added by the YamlOutput before giving them to Gaia
    if (d.startsWith(".metadata.version")) continue;

    string dname = d.mid(1).toStdString();
    if (pool.contains<string>(dname)) {
      // descriptor is a single string
      string label = pool.value<string>(dname);
      result->setLabel(d, gaia2::StringDescriptor(QString::fromStdString(label)));
    }
    else if (pool.contains<vector<string> >(dname)) {
      // descriptor is a list of strings
      vector<string> label = pool.value<vector<string> >(dname);
      result->setLabel(d, gaia2::convert::VectorString_to_StringDescriptor(label));
    }
    else {
      throw EssentiaException("Descriptor ", dname, " could not be found in pool");
    }
  }

  return result;
}

void checkNotIn(const string& desc, const set<string>& alldescs) {
  if (alldescs.find(desc) != alldescs.end()) {
    throw EssentiaException("GaiaTransform is trying to overwrite the ", desc, " value, which is already present in the pool. You can't do that.");
  }
}

/**
 * Copy all the values from the point inside the pool.
 */
void pointToPool(const gaia2::Point* p, Pool& pool, const Pool& origPool) {
  const gaia2::PointLayout& layout = p->layout();
  vector<string> alldescsv = pool.descriptorNames();
  set<string> alldescs(alldescsv.begin(), alldescsv.end());

  foreach (const QString& d, layout.descriptorNames(gaia2::RealType)) {
    string pooldesc = d.mid(1).toStdString();
    checkNotIn(pooldesc, alldescs);

    gaia2::RealDescriptor desc = p->value(d);

    if (desc.size() == 1)    pool.set(pooldesc, desc[0]);
    else if (desc.isEmpty()) pool.set(pooldesc, vector<Real>());
    else                     pool.set(pooldesc, vector<Real>(&desc[0],
                                                             &desc[0]+desc.size()));

    // in fact, if desc.size == 1 and we're not in the single pool, we'd better
    // put back the value as a list of size 1
    const std::map<std::string, Real>& srpool = origPool.getSingleRealPool();

    if ((desc.size() == 1) && (srpool.find(pooldesc) == srpool.end())) {
      pool.remove(pooldesc);
      for (int i=0; i<desc.size(); i++) pool.add(pooldesc, desc[i]);
    }

    // if desc was a vector<vector<Real> >, it will have been converted to a single
    // vector<Real>, where the first 2 values are the dimensions. Construct this matrix back.
    const PoolOf(std::vector<Real>)& vrpool = origPool.getVectorRealPool();

    if (vrpool.find(pooldesc) != vrpool.end()) {
      int rows = int(desc[0]);
      int cols = int(desc[1]);

      // assert we're not doing something potentially stupid
      if ((rows*cols + 2) != desc.size()) {
        E_WARNING("Oops, internal error in GaiaTransform::pointToPool, ignoring...");
        continue;
      }
      pool.remove(pooldesc);

      for (int i=0; i<rows; i++) {
        pool.add(pooldesc, vector<Real>(&desc[2+ i*cols],
                                        &desc[2+ i*cols] + cols));
      }
    }
  }

  // for string descs, we need to be looking at both the string and enum types in the layout
  QStringList stringDescs = layout.descriptorNames(gaia2::StringType) +
                            layout.descriptorNames(gaia2::EnumType);

  foreach (const QString& d, stringDescs) {
    string pooldesc = d.mid(1).toStdString();
    checkNotIn(pooldesc, alldescs);

    gaia2::StringDescriptor desc = p->label(d);

    // little check: see if we haven't removed the version before
    if (pooldesc == "metadata.version.essentia") {
      pool.set(pooldesc, essentia::version);
      continue;
    }

    if (desc.size() == 1) pool.set(pooldesc, desc[0].toStdString());
    else {
      for (int i=0; i<desc.size(); i++) {
        pool.add(pooldesc, desc[i].toStdString());
      }
    }
  }
}

void GaiaTransform::compute() {
  if (!_configured) {
    throw EssentiaException("GaiaTransform: Algorithm is not properly configured");
  }

  const Pool& inputPool = _inputPool.get();
  Pool& outputPool = _outputPool.get();

  gaia2::Point* p = poolToPoint(inputPool, _history.at(0).layout);
  gaia2::Point* result = _history.mapPoint(p, true); // p has been deleted by mapPoint

  // FIXME: should raise an exception if we overwrite a value which was previously in the pool
  pointToPool(result, outputPool, inputPool);

  // small hack: if we got an SVM transfo with associated probabilities, put them in
  // a nicer shape than the vector of anonymous reals it is.
  bool doesSVM = false;
  gaia2::ParameterMap params;
  for (int i=0; i<_history.size(); i++) {
    if (_history[i].analyzerName == "svmtrain") {
      params = _history[i].params;
      doesSVM = true;
      break;
    }
  }

  if (doesSVM && params.value("probability").toBool()) {
    // we need to remove the class and the probability vector and replace them with:
    // class:
    //   value: X
    //   probability: X
    //   all:
    //     cls1: X
    //     cls2: X
    //     ...
    QStringList classList = params.value("classMapping").toStringList();
    string className = params.value("className").toString().toStdString();
    string cls = outputPool.value<string>(className);
    vector<Real> probs = outputPool.value<vector<Real> >(className + "Probability");
    Q_ASSERT(classList.size() == (int)probs.size());

    outputPool.remove(className);
    outputPool.remove(className + "Probability");

    outputPool.set(className + ".value", cls);
    outputPool.set(className + ".probability", probs[classList.indexOf(QString::fromStdString(cls))]);
    for (int i=0; i<classList.size(); i++) {
      outputPool.set(className + ".all." + classList[i].toStdString(), probs[i]);
    }
  }

  delete result;
}

GaiaTransform::~GaiaTransform() {}
<|endoftext|>


<commit_before>#include <iostream>
#include <time.h>
#include <stdint.h>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>

#include "KinectWrapper.h"
#include "Connection.h"
#include "Logger.h"

#define LOG_LEVEL DEBUG

using namespace std;

volatile bool running = true;
void signalHandler(int signal)
{
	if (signal == SIGINT
	 || signal == SIGTERM
	 || signal == SIGQUIT)
	{
		running = false;
	}
}

IplImage* handleVideoFrame(Connection con, int len){
	VideoFrame vf = {};
	char* data = 0;

	IplImage* ret = cvCreateImageHeader(cvSize(640, 480), 8, 3);

	con.recvData((void *) &vf, sizeof(VideoFrame));
	LOG_DEBUG << "VideoFrame h=" << vf.h << " sizeof=" << sizeof(VideoFrame) << endl;

	if (vf.h != VIDEO_FRAME){
		LOG_WARNING << "expected to receive video frame, got " << vf.h << endl;
		return NULL;
	}

	data = (char*) malloc(len);
	memcpy(data, vf.data, len);

	cvSetData(ret, data, 640*3);
	cvCvtColor(ret, ret, CV_RGB2BGR);

	return ret;
}

IplImage* handleDepthFrame(Connection con, int len){
	DepthFrame df = {};
	char* data = 0;

	IplImage* ret = cvCreateImageHeader(cvSize(640, 480), IPL_DEPTH_16U, 1);

	con.recvData((void *) &df, sizeof(DepthFrame));

	if (df.h != DEPTH_FRAME){
		LOG_WARNING << "expected to receive depth frame, got " << df.h << endl;
		return NULL;
	}

	data = (char*) malloc(len);
	memcpy(data, df.data, len);

	cvSetData(ret, data, 640);

	return ret;
}

int main(void){
	int client_socket = 0;
	Header h = UNKNOWN;
	IplImage* frame = 0;
	//Connection clients[MAX_CLIENTS] = {0};

	signal(SIGINT, signalHandler);
	signal(SIGTERM, signalHandler);
	signal(SIGQUIT, signalHandler);

	Connection con(CONNECTION_PORT, "127.0.0.1");
	con.createConnection(SERVER);

	con.acceptConnection(&client_socket);
	Connection client(client_socket);

	/*
	for (int i = 0; i < MAX_CLIENTS; i++){
		con.acceptConnection(&client_socket);
		client[i] = Connection(client_socket);
	}
	*/

	//while(running){
	for (int i = 0; i<10; i++){
		//if ((h = client.peekHeader()) == FRAME_MESSAGE){
			FrameMessage fm = {};

			client.recvData((void*) &fm, sizeof(FrameMessage));

			LOG_DEBUG << "FrameMessage h=" << fm.h << " info="<<fm.info <<" length="<<fm.length << " sizeof=" << sizeof(FrameMessage) << endl;

			if(fm.info == VIDEO){
				frame = handleVideoFrame(client, fm.length);
			} else if(fm.info == DEPTH) {
				frame = handleDepthFrame(client, fm.length);
			} else {
				LOG_WARNING << "received unknown frame_info " << fm.info << endl;
				continue;
			}
		/*} else {
			LOG_WARNING << "received wrong header " << h << endl;
			continue;
		}*/

		LOG_DEBUG << "try to show frame" << endl;
		cvShowImage("Frame", frame);
		cvFree(&frame);
	}

	con.closeConnection();
	client.closeConnection();

	return 0;
}
<commit_msg>switch to c++ implementation of opencv<commit_after>#include <iostream>
#include <time.h>
#include <stdint.h>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>

#include "KinectWrapper.h"
#include "Connection.h"
#include "Logger.h"

#define LOG_LEVEL DEBUG

using namespace std;
using namespace cv;

volatile bool running = true;
void signalHandler(int signal)
{
	if (signal == SIGINT
	 || signal == SIGTERM
	 || signal == SIGQUIT)
	{
		running = false;
	}
}

char* handleVideoFrame(Connection con, int len, Mat* ret){
	VideoFrame vf = {};
	char* data = 0;

	con.recvData((void *) &vf, sizeof(VideoFrame));

	if (vf.h != VIDEO_FRAME){
		LOG_WARNING << "expected to receive video frame, got " << vf.h << endl;
		return NULL;
	}

	data = (char*) malloc(len);
	memcpy(data, vf.data, len);

	ret = new Mat(Size(640, 480), CV_8UC3, data);
	cvtColor(*ret, *ret, CV_RGB2BGR);

	return data;
}

char* handleDepthFrame(Connection con, int len, Mat* ret){
	DepthFrame df = {};
	char* data = 0;

	con.recvData((void *) &df, sizeof(DepthFrame));

	if (df.h != DEPTH_FRAME){
		LOG_WARNING << "expected to receive depth frame, got " << df.h << endl;
		return NULL;
	}

	data = (char*) malloc(len);
	memcpy(data, df.data, len);

	ret = new Mat(Size(640, 480), CV_16UC1, data);

	return data;
}

int main(void){
	int client_socket = 0;
	Header h = UNKNOWN;
	Mat* frame = 0;
	char* data = 0;
	//Connection clients[MAX_CLIENTS] = {0};

	signal(SIGINT, signalHandler);
	signal(SIGTERM, signalHandler);
	signal(SIGQUIT, signalHandler);

	Connection con(CONNECTION_PORT, "127.0.0.1");
	con.createConnection(SERVER);

	con.acceptConnection(&client_socket);
	Connection client(client_socket);

	/*
	for (int i = 0; i < MAX_CLIENTS; i++){
		con.acceptConnection(&client_socket);
		client[i] = Connection(client_socket);
	}
	*/

	//while(running){
	for (int i = 0; i<10; i++){
		//if ((h = client.peekHeader()) == FRAME_MESSAGE){
			FrameMessage fm = {};

			client.recvData((void*) &fm, sizeof(FrameMessage));

			LOG_DEBUG << "FrameMessage h=" << fm.h << " info="<<fm.info <<" length="<<fm.length << " sizeof=" << sizeof(FrameMessage) << endl;

			if(fm.info == VIDEO){
				data = handleVideoFrame(client, fm.length, frame);
			} else if(fm.info == DEPTH) {
				data = handleDepthFrame(client, fm.length, frame);
			} else {
				LOG_WARNING << "received unknown frame_info " << fm.info << endl;
				continue;
			}
		/*} else {
			LOG_WARNING << "received wrong header " << h << endl;
			continue;
		}*/

		LOG_DEBUG << "try to show frame" << endl;
		imshow("Frame", *frame);

		free(data);
		delete(frame);
	}

	con.closeConnection();
	client.closeConnection();

	return 0;
}
<|endoftext|>


<commit_before>#include "MainWindow.hpp"
#include "ui_MainWindow.h"
#include <QMessageBox>
#include <QCloseEvent>

MainWindow::MainWindow(QWidget *parent) :
  QMainWindow(parent),
  ui(new Ui::MainWindow)
{
  ui->setupUi(this);
}

MainWindow::~MainWindow()
{
  delete ui;
}

void MainWindow::closeEvent(QCloseEvent *event)
{
  if(QMessageBox::question(this, QString::fromUtf8("ipAddress"),
    QString::fromUtf8("Do you want to quit?"), QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes)
  {
    event->accept();
  }
  else
  {
    event->ignore();
  }
}
<commit_msg>Prepared validators<commit_after>#include "MainWindow.hpp"
#include "ui_MainWindow.h"
#include <QMessageBox>
#include <QCloseEvent>
#include <QRegExp>
#include <QRegExpValidator>
#include <QIntValidator>

MainWindow::MainWindow(QWidget *parent) :
  QMainWindow(parent),
  ui(new Ui::MainWindow)
{
  ui->setupUi(this);

  // QRegExpValidator *validator = new QRegExpValidator(QRegExp("\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b"));

  // QIntValidator *validator = new QIntValidator(0, 4294967295);

  // QRegExpValidator *validator = new QRegExpValidator(QRegExp("[0-9a-fA-F]+"));

  // QRegExpValidator *validator = new QRegExpValidator(QRegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$"));

  // ui->lineEdit->setValidator(validator);
}

MainWindow::~MainWindow()
{
  delete ui;
}

void MainWindow::closeEvent(QCloseEvent *event)
{
  if(QMessageBox::question(this, QString::fromUtf8("ipAddress"),
    QString::fromUtf8("Do you want to quit?"), QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes)
  {
    event->accept();
  }
  else
  {
    event->ignore();
  }
}
<|endoftext|>