<commit_before>/*

  Copyright (C) 2003-2008  Grame
  Grame Research Laboratory, 9 rue du Garet, 69001 Lyon - France
  research@grame.fr

  This file is provided as an example of the MusicXML Library use.
*/

#ifdef VC6
# pragma warning (disable : 4786)
#endif

#include <string>

#include <stdlib.h>
#include <string.h>
#ifndef WIN32
#include <signal.h>
#endif

#include "libmusicxml.h"

using namespace std;
using namespace MusicXML2;

static void usage() {
	cerr << "usage: xml2guido [options]  <musicxml file>" << endl;
	cerr << "       reads stdin when <musicxml file> is '-'" << endl;
	cerr << "       option: --autobars don't generates barlines" << endl;
	cerr << "       option: --version print version and exit" << endl;
	exit(1);
}

#ifndef WIN32

static void _sigaction(int signal, siginfo_t *si, void *arg)
{
    cerr << "Signal #" << signal << " catched!" << endl;
    exit(-2);
}

static void catchsigs()
{
	struct sigaction sa;

    memset(&sa, 0, sizeof(struct sigaction));
    sigemptyset(&sa.sa_mask);
    sa.sa_sigaction = _sigaction;
    sa.sa_flags   = SA_SIGINFO;
    sigaction(SIGSEGV, &sa, NULL);
    sigaction(SIGILL, &sa, NULL);
    sigaction(SIGFPE, &sa, NULL);
}

#else
static void catchsigs()	{}
#endif

//_______________________________________________________________________________
static bool checkOpt(int argc, char *argv[], const string& option)
{
	for (int i=1; i<argc;i++) {
		if (option == argv[i]) return true;
	}
	return false;
}

//_______________________________________________________________________________
static void versionInfo()
{
	cout << "xml2guido version " << musicxml2guidoVersionStr() << endl;
	cout << "Using libmusicxml version " << musicxmllibVersionStr() << endl;
	exit (0);
}

//_______________________________________________________________________________
int main(int argc, char *argv[])
{
	catchsigs();

	bool version = checkOpt (argc, argv, "--version");
	if (version) versionInfo();

	if (argc < 2) usage();

	bool generateBars = checkOpt (argc, argv, "--autobars");
	char * file = argv[argc-1];

	xmlErr err = kNoErr;
	if (!strcmp(file, "-"))
		err = musicxmlfd2guido(stdin, generateBars, cout);
	else
		err = musicxmlfile2guido(file, generateBars, cout);
	if (err == kUnsupported)
		cerr << "unsupported xml format" << endl;
	else if (err == kUnsupported) {
		cerr << "conversion failed" << endl;
		return -1;
	}
	return 0;
}
<commit_msg>-v option added<commit_after>/*

  Copyright (C) 2003-2008  Grame
  Grame Research Laboratory, 9 rue du Garet, 69001 Lyon - France
  research@grame.fr

  This file is provided as an example of the MusicXML Library use.
*/

#ifdef VC6
# pragma warning (disable : 4786)
#endif

#include <string>

#include <stdlib.h>
#include <string.h>
#ifndef WIN32
#include <signal.h>
#endif

#include "libmusicxml.h"

using namespace std;
using namespace MusicXML2;

static void usage() {
	cerr << "usage: xml2guido [options]  <musicxml file>" << endl;
	cerr << "       reads stdin when <musicxml file> is '-'" << endl;
	cerr << "       option: --autobars don't generates barlines" << endl;
	cerr << "       option: --version print version and exit" << endl;
	exit(1);
}

#ifndef WIN32

static void _sigaction(int signal, siginfo_t *si, void *arg)
{
    cerr << "Signal #" << signal << " catched!" << endl;
    exit(-2);
}

static void catchsigs()
{
	struct sigaction sa;

    memset(&sa, 0, sizeof(struct sigaction));
    sigemptyset(&sa.sa_mask);
    sa.sa_sigaction = _sigaction;
    sa.sa_flags   = SA_SIGINFO;
    sigaction(SIGSEGV, &sa, NULL);
    sigaction(SIGILL, &sa, NULL);
    sigaction(SIGFPE, &sa, NULL);
}

#else
static void catchsigs()	{}
#endif

//_______________________________________________________________________________
static bool checkOpt(int argc, char *argv[], const string& option)
{
	for (int i=1; i<argc;i++) {
		if (option == argv[i]) return true;
	}
	return false;
}

//_______________________________________________________________________________
static void versionInfo()
{
	cout << "xml2guido version " << musicxml2guidoVersionStr() << endl;
	cout << "Using libmusicxml version " << musicxmllibVersionStr() << endl;
	exit (0);
}

//_______________________________________________________________________________
int main(int argc, char *argv[])
{
	catchsigs();

	bool version = checkOpt (argc, argv, "--version") || checkOpt (argc, argv, "-v");
	if (version) versionInfo();

	if (argc < 2) usage();

	bool generateBars = checkOpt (argc, argv, "--autobars");
	char * file = argv[argc-1];

	xmlErr err = kNoErr;
	if (!strcmp(file, "-"))
		err = musicxmlfd2guido(stdin, generateBars, cout);
	else
		err = musicxmlfile2guido(file, generateBars, cout);
	if (err == kUnsupported)
		cerr << "unsupported xml format" << endl;
	else if (err == kUnsupported) {
		cerr << "conversion failed" << endl;
		return -1;
	}
	return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2008, 2009 Nokia Corporation.
 *
 * Contact: Marius Vollmer <marius.vollmer@nokia.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * version 2.1 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

#include <QtTest/QtTest>
#include <QtCore>
#include "fileutils.h"
#include "infocdbbackend.h"
#include "cdbwriter.h"

class InfoCdbBackendUnitTest : public QObject
{
    Q_OBJECT
    InfoCdbBackend *backend;

private:
    void createBaseDatabase(QString path);
    void createAlternateDatabase(QString path);

private slots:
    void initTestCase();
    void databaseExists();
    void databaseDirectory();
    void listKeys();
    void typeForKey();
    void docForKey();
    void keyDeclared();
    void keyProvided();
    void listProviders();
    void dynamics();
    void removed();
    void cleanupTestCase();
};

void InfoCdbBackendUnitTest::createBaseDatabase(QString path)
{
    CDBWriter writer(path);

    if (! writer.isWritable())
        qFatal("Failed to open %s for reading!", path.toLocal8Bit().data());

    writer.add("KEYS", "Battery.Charging");
    writer.add("KEYS", "Internet.BytesOut");
    writer.add("PLUGINS", "contextkit-dbus");
    writer.add("contextkit-dbus:KEYS", "Battery.Charging");
    writer.add("contextkit-dbus:KEYS", "Internet.BytesOut");
    writer.add("Battery.Charging:KEYTYPE", "TRUTH");
    writer.add("Internet.BytesOut:KEYTYPE", "INTEGER");
    writer.add("Battery.Charging:KEYDOC", "doc1");
    writer.add("Internet.BytesOut:KEYPLUGIN", "contextkit-dbus");
    writer.add("Battery.Charging:KEYPLUGIN", "contextkit-dbus");
    writer.add("Battery.Charging:KEYCONSTRUCTIONSTRING", "system:org.freedesktop.ContextKit.contextd1");
    writer.add("Internet.BytesOut:KEYCONSTRUCTIONSTRING", "session:org.freedesktop.ContextKit.contextd2");

    QVariantList providers1;
    QHash <QString, QVariant> provider1;
    provider1.insert("plugin", "contextkit-dbus");
    provider1.insert("constructionString", "system:org.freedesktop.ContextKit.contextd1");
    providers1 << QVariant(provider1);
    writer.add("Battery.Charging:PROVIDERS", QVariant(providers1));

    QVariantList providers2;
    QHash <QString, QVariant> provider2;
    provider2.insert("plugin", "contextkit-dbus");
    provider2.insert("constructionString", "session:org.freedesktop.ContextKit.contextd2");
    providers2 << QVariant(provider2);
    writer.add("Internet.BytesOut:PROVIDERS", QVariant(providers2));

    writer.close();
}

void InfoCdbBackendUnitTest::createAlternateDatabase(QString path)
{
    CDBWriter writer(path);

    if (! writer.isWritable())
        qFatal("Failed to open %s for reading!", path.toLocal8Bit().data());

    writer.add("KEYS", "Battery.Charging");
    writer.add("KEYS", "Battery.Capacity");
    writer.add("PLUGINS", "contextkit-dbus");
    writer.add("contextkit-dbus:KEYS", "Battery.Charging");
    writer.add("contextkit-dbus:KEYS", "Battery.Capacity");
    writer.add("Battery.Charging:KEYTYPE", "INTEGER");
    writer.add("Battery.Charging:KEYDOC", "doc1");
    writer.add("Battery.Charging:KEYPLUGIN", "contextkit-dbus");
    writer.add("Battery.Charging:KEYCONSTRUCTIONSTRING", "system:org.freedesktop.ContextKit.contextd1");
    writer.add("Battery.Capacity:KEYTYPE", "INTEGER");
    writer.add("Battery.Capacity:KEYDOC", "doc3");
    writer.add("Battery.Capacity:KEYPLUGIN", "contextkit-dbus");
    writer.add("Battery.Capacity:KEYCONSTRUCTIONSTRING", "system:org.freedesktop.ContextKit.contextd1");

    QVariantList providers1;
    QHash <QString, QVariant> provider1;
    provider1.insert("plugin", "contextkit-dbus");
    provider1.insert("constructionString", "system:org.freedesktop.ContextKit.contextd1");
    providers1 << QVariant(provider1);
    writer.add("Battery.Charging:PROVIDERS", QVariant(providers1));

    QVariantList providers2;
    QHash <QString, QVariant> provider2;
    provider2.insert("plugin", "contextkit-dbus");
    provider2.insert("constructionString", "system:org.freedesktop.ContextKit.contextd1");
    providers2 << QVariant(provider2);
    writer.add("Battery.Capacity:PROVIDERS", providers2);

    writer.close();
}

void InfoCdbBackendUnitTest::initTestCase()
{
    createBaseDatabase("cache.cdb");

    utilSetEnv("CONTEXT_PROVIDERS", "./");
    utilSetEnv("CONTEXT_CORE_DECLARATIONS", "/dev/null");
    backend = new InfoCdbBackend();
}

void InfoCdbBackendUnitTest::databaseDirectory()
{
    QCOMPARE(backend->databaseDirectory(), QString("./"));
}

void InfoCdbBackendUnitTest::databaseExists()
{
    QCOMPARE(backend->databaseExists(), true);
}

void InfoCdbBackendUnitTest::listKeys()
{
    QStringList keys = backend->listKeys();
    QCOMPARE(keys.count(), 2);
    QVERIFY(keys.contains("Battery.Charging"));
    QVERIFY(keys.contains("Internet.BytesOut"));
}

void InfoCdbBackendUnitTest::typeForKey()
{
    QCOMPARE(backend->typeForKey("Internet.BytesOut"), QString("INTEGER"));
    QCOMPARE(backend->typeForKey("Battery.Charging"), QString("TRUTH"));
    QCOMPARE(backend->typeForKey("Does.Not.Exist"), QString());
}

void InfoCdbBackendUnitTest::docForKey()
{
    QCOMPARE(backend->docForKey("Internet.BytesOut"), QString());
    QCOMPARE(backend->docForKey("Battery.Charging"), QString("doc1"));
    QCOMPARE(backend->docForKey("Does.Not.Exist"), QString());
}

void InfoCdbBackendUnitTest::keyDeclared()
{
    foreach (QString key, backend->listKeys())
        QCOMPARE(backend->keyDeclared(key), true);

    QCOMPARE(backend->keyDeclared("Does.Not.Exist"), false);
    QCOMPARE(backend->keyDeclared("Battery.Charging"), true);
}

void InfoCdbBackendUnitTest::keyProvided()
{
    foreach (QString key, backend->listKeys())
        QVERIFY(backend->keyProvided(key) == true);

    QCOMPARE(backend->keyProvided("Does.Not.Exist"), false);
}

void InfoCdbBackendUnitTest::listProviders()
{
    QList <ContextProviderInfo> list1 = backend->listProviders("Battery.Charging");
    QCOMPARE(list1.count(), 1);
    QCOMPARE(list1.at(0).plugin, QString("contextkit-dbus"));
    QCOMPARE(list1.at(0).constructionString, QString("system:org.freedesktop.ContextKit.contextd1"));

    QList <ContextProviderInfo> list2 = backend->listProviders("Does.Not.Exist");
    QCOMPARE(list2.count(), 0);
}

void InfoCdbBackendUnitTest::dynamics()
{
    backend->connectNotify("-"); // Fake it. Spy does something fishy here.

    // Setup the spy observers
    QSignalSpy spy1(backend, SIGNAL(keysRemoved(QStringList)));
    QSignalSpy spy2(backend, SIGNAL(keysChanged(QStringList)));
    QSignalSpy spy3(backend, SIGNAL(keyChanged(QString)));
    QSignalSpy spy4(backend, SIGNAL(keysAdded(QStringList)));

    createAlternateDatabase("cache-next.cdb");
    QFile::remove("cache.cdb");
    QFile::copy("cache-next.cdb", "cache.cdb");
    QTest::qWait(DEFAULT_WAIT_PERIOD);

    // Test the new values
    QCOMPARE(backend->databaseExists(), true);
    QCOMPARE(backend->listKeys().count(), 2);
    QVERIFY(backend->listKeys().contains("Battery.Charging"));
    QVERIFY(backend->listKeys().contains("Battery.Capacity"));
    QCOMPARE(backend->typeForKey("Battery.Charging"), QString("INTEGER"));
    QCOMPARE(backend->docForKey("Battery.Charging"), QString("doc1"));
    QVERIFY(backend->keyProvided("Battery.Charging") == true);
    QVERIFY(backend->keyProvided("Internet.BytesOut") == false);

    // Test emissions
    QCOMPARE(spy1.count(), 1);
    QList<QVariant> args1 = spy1.takeFirst();
    QCOMPARE(args1.at(0).toList().size(), 1);
    QCOMPARE(args1.at(0).toStringList().at(0), QString("Internet.BytesOut"));

    QCOMPARE(spy2.count(), 1);
    QList<QVariant> args2 = spy2.takeFirst();
    QCOMPARE(args2.at(0).toList().size(), 2);
    QCOMPARE(args2.at(0).toStringList().at(0), QString("Battery.Charging"));
    QCOMPARE(args2.at(0).toStringList().at(1), QString("Battery.Capacity"));

    QCOMPARE(spy3.count(), 3);

    QCOMPARE(spy4.count(), 1);
    QList<QVariant> args4 = spy4.takeFirst();
    QCOMPARE(args4.at(0).toList().size(), 1);
    QCOMPARE(args4.at(0).toStringList().at(0), QString("Battery.Capacity"));

    backend->disconnectNotify("-"); // Fake it. Spy does something fishy here.
}

void InfoCdbBackendUnitTest::removed()
{
    backend->connectNotify("-"); // Fake it. Spy does something fishy here.
    QSignalSpy spy(backend, SIGNAL(keysRemoved(QStringList)));

    QFile::remove("cache.cdb");

    QTest::qWait(DEFAULT_WAIT_PERIOD);

    //QCOMPARE(spy.count(), 1);
    //QList<QVariant> args = spy.takeFirst();
    //QCOMPARE(args.at(0).toList().size(), 2);

    backend->disconnectNotify("-"); // Fake it. Spy does something fishy here.
}

void InfoCdbBackendUnitTest::cleanupTestCase()
{
    QFile::remove("cache.cdb");
    QFile::remove("cache-next.cdb");
}

#include "infocdbbackendunittest.moc"
QTEST_MAIN(InfoCdbBackendUnitTest);
<commit_msg>Removing redundant stuff now.<commit_after>/*
 * Copyright (C) 2008, 2009 Nokia Corporation.
 *
 * Contact: Marius Vollmer <marius.vollmer@nokia.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * version 2.1 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

#include <QtTest/QtTest>
#include <QtCore>
#include "fileutils.h"
#include "infocdbbackend.h"
#include "cdbwriter.h"

class InfoCdbBackendUnitTest : public QObject
{
    Q_OBJECT
    InfoCdbBackend *backend;

private:
    void createBaseDatabase(QString path);
    void createAlternateDatabase(QString path);

private slots:
    void initTestCase();
    void databaseExists();
    void databaseDirectory();
    void listKeys();
    void typeForKey();
    void docForKey();
    void keyDeclared();
    void keyProvided();
    void listProviders();
    void dynamics();
    void removed();
    void cleanupTestCase();
};

void InfoCdbBackendUnitTest::createBaseDatabase(QString path)
{
    CDBWriter writer(path);

    if (! writer.isWritable())
        qFatal("Failed to open %s for reading!", path.toLocal8Bit().data());

    writer.add("KEYS", "Battery.Charging");
    writer.add("KEYS", "Internet.BytesOut");
    writer.add("Battery.Charging:KEYTYPE", "TRUTH");
    writer.add("Internet.BytesOut:KEYTYPE", "INTEGER");
    writer.add("Battery.Charging:KEYDOC", "doc1");

    QVariantList providers1;
    QHash <QString, QVariant> provider1;
    provider1.insert("plugin", "contextkit-dbus");
    provider1.insert("constructionString", "system:org.freedesktop.ContextKit.contextd1");
    providers1 << QVariant(provider1);
    writer.add("Battery.Charging:PROVIDERS", QVariant(providers1));

    QVariantList providers2;
    QHash <QString, QVariant> provider2;
    provider2.insert("plugin", "contextkit-dbus");
    provider2.insert("constructionString", "session:org.freedesktop.ContextKit.contextd2");
    providers2 << QVariant(provider2);
    writer.add("Internet.BytesOut:PROVIDERS", QVariant(providers2));

    writer.close();
}

void InfoCdbBackendUnitTest::createAlternateDatabase(QString path)
{
    CDBWriter writer(path);

    if (! writer.isWritable())
        qFatal("Failed to open %s for reading!", path.toLocal8Bit().data());

    writer.add("KEYS", "Battery.Charging");
    writer.add("KEYS", "Battery.Capacity");
    writer.add("Battery.Charging:KEYTYPE", "INTEGER");
    writer.add("Battery.Charging:KEYDOC", "doc1");
    writer.add("Battery.Capacity:KEYTYPE", "INTEGER");
    writer.add("Battery.Capacity:KEYDOC", "doc3");

    QVariantList providers1;
    QHash <QString, QVariant> provider1;
    provider1.insert("plugin", "contextkit-dbus");
    provider1.insert("constructionString", "system:org.freedesktop.ContextKit.contextd1");
    providers1 << QVariant(provider1);
    writer.add("Battery.Charging:PROVIDERS", QVariant(providers1));

    QVariantList providers2;
    QHash <QString, QVariant> provider2;
    provider2.insert("plugin", "contextkit-dbus");
    provider2.insert("constructionString", "system:org.freedesktop.ContextKit.contextd1");
    providers2 << QVariant(provider2);
    writer.add("Battery.Capacity:PROVIDERS", providers2);

    writer.close();
}

void InfoCdbBackendUnitTest::initTestCase()
{
    createBaseDatabase("cache.cdb");

    utilSetEnv("CONTEXT_PROVIDERS", "./");
    utilSetEnv("CONTEXT_CORE_DECLARATIONS", "/dev/null");
    backend = new InfoCdbBackend();
}

void InfoCdbBackendUnitTest::databaseDirectory()
{
    QCOMPARE(backend->databaseDirectory(), QString("./"));
}

void InfoCdbBackendUnitTest::databaseExists()
{
    QCOMPARE(backend->databaseExists(), true);
}

void InfoCdbBackendUnitTest::listKeys()
{
    QStringList keys = backend->listKeys();
    QCOMPARE(keys.count(), 2);
    QVERIFY(keys.contains("Battery.Charging"));
    QVERIFY(keys.contains("Internet.BytesOut"));
}

void InfoCdbBackendUnitTest::typeForKey()
{
    QCOMPARE(backend->typeForKey("Internet.BytesOut"), QString("INTEGER"));
    QCOMPARE(backend->typeForKey("Battery.Charging"), QString("TRUTH"));
    QCOMPARE(backend->typeForKey("Does.Not.Exist"), QString());
}

void InfoCdbBackendUnitTest::docForKey()
{
    QCOMPARE(backend->docForKey("Internet.BytesOut"), QString());
    QCOMPARE(backend->docForKey("Battery.Charging"), QString("doc1"));
    QCOMPARE(backend->docForKey("Does.Not.Exist"), QString());
}

void InfoCdbBackendUnitTest::keyDeclared()
{
    foreach (QString key, backend->listKeys())
        QCOMPARE(backend->keyDeclared(key), true);

    QCOMPARE(backend->keyDeclared("Does.Not.Exist"), false);
    QCOMPARE(backend->keyDeclared("Battery.Charging"), true);
}

void InfoCdbBackendUnitTest::keyProvided()
{
    foreach (QString key, backend->listKeys())
        QVERIFY(backend->keyProvided(key) == true);

    QCOMPARE(backend->keyProvided("Does.Not.Exist"), false);
}

void InfoCdbBackendUnitTest::listProviders()
{
    QList <ContextProviderInfo> list1 = backend->listProviders("Battery.Charging");
    QCOMPARE(list1.count(), 1);
    QCOMPARE(list1.at(0).plugin, QString("contextkit-dbus"));
    QCOMPARE(list1.at(0).constructionString, QString("system:org.freedesktop.ContextKit.contextd1"));

    QList <ContextProviderInfo> list2 = backend->listProviders("Does.Not.Exist");
    QCOMPARE(list2.count(), 0);
}

void InfoCdbBackendUnitTest::dynamics()
{
    backend->connectNotify("-"); // Fake it. Spy does something fishy here.

    // Setup the spy observers
    QSignalSpy spy1(backend, SIGNAL(keysRemoved(QStringList)));
    QSignalSpy spy2(backend, SIGNAL(keysChanged(QStringList)));
    QSignalSpy spy3(backend, SIGNAL(keyChanged(QString)));
    QSignalSpy spy4(backend, SIGNAL(keysAdded(QStringList)));

    createAlternateDatabase("cache-next.cdb");
    QFile::remove("cache.cdb");
    QFile::copy("cache-next.cdb", "cache.cdb");
    QTest::qWait(DEFAULT_WAIT_PERIOD);

    // Test the new values
    QCOMPARE(backend->databaseExists(), true);
    QCOMPARE(backend->listKeys().count(), 2);
    QVERIFY(backend->listKeys().contains("Battery.Charging"));
    QVERIFY(backend->listKeys().contains("Battery.Capacity"));
    QCOMPARE(backend->typeForKey("Battery.Charging"), QString("INTEGER"));
    QCOMPARE(backend->docForKey("Battery.Charging"), QString("doc1"));
    QVERIFY(backend->keyProvided("Battery.Charging") == true);
    QVERIFY(backend->keyProvided("Internet.BytesOut") == false);

    // Test emissions
    QCOMPARE(spy1.count(), 1);
    QList<QVariant> args1 = spy1.takeFirst();
    QCOMPARE(args1.at(0).toList().size(), 1);
    QCOMPARE(args1.at(0).toStringList().at(0), QString("Internet.BytesOut"));

    QCOMPARE(spy2.count(), 1);
    QList<QVariant> args2 = spy2.takeFirst();
    QCOMPARE(args2.at(0).toList().size(), 2);
    QCOMPARE(args2.at(0).toStringList().at(0), QString("Battery.Charging"));
    QCOMPARE(args2.at(0).toStringList().at(1), QString("Battery.Capacity"));

    QCOMPARE(spy3.count(), 3);

    QCOMPARE(spy4.count(), 1);
    QList<QVariant> args4 = spy4.takeFirst();
    QCOMPARE(args4.at(0).toList().size(), 1);
    QCOMPARE(args4.at(0).toStringList().at(0), QString("Battery.Capacity"));

    backend->disconnectNotify("-"); // Fake it. Spy does something fishy here.
}

void InfoCdbBackendUnitTest::removed()
{
    backend->connectNotify("-"); // Fake it. Spy does something fishy here.
    QSignalSpy spy(backend, SIGNAL(keysRemoved(QStringList)));

    QFile::remove("cache.cdb");

    QTest::qWait(DEFAULT_WAIT_PERIOD);

    //QCOMPARE(spy.count(), 1);
    //QList<QVariant> args = spy.takeFirst();
    //QCOMPARE(args.at(0).toList().size(), 2);

    backend->disconnectNotify("-"); // Fake it. Spy does something fishy here.
}

void InfoCdbBackendUnitTest::cleanupTestCase()
{
    QFile::remove("cache.cdb");
    QFile::remove("cache-next.cdb");
}

#include "infocdbbackendunittest.moc"
QTEST_MAIN(InfoCdbBackendUnitTest);
<|endoftext|>


<commit_before>/*
 *
 * Copyright 2015, Google Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <thread>

#include "test/core/util/port.h"
#include "test/core/util/test_config.h"
#include "test/cpp/util/echo_duplicate.grpc.pb.h"
#include "test/cpp/util/echo.grpc.pb.h"
#include "src/cpp/server/thread_pool.h"
#include <grpc++/channel_arguments.h>
#include <grpc++/channel_interface.h>
#include <grpc++/client_context.h>
#include <grpc++/create_channel.h>
#include <grpc++/credentials.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <grpc++/server_context.h>
#include <grpc++/server_credentials.h>
#include <grpc++/status.h>
#include <grpc++/stream.h>
#include <grpc++/time.h>
#include <gtest/gtest.h>

#include <grpc/grpc.h>
#include <grpc/support/thd.h>
#include <grpc/support/time.h>

#include "test/cpp/util/subprocess.h"

using grpc::cpp::test::util::EchoRequest;
using grpc::cpp::test::util::EchoResponse;
using std::chrono::system_clock;

static std::string g_root;

namespace grpc {
namespace testing {

namespace {

class CrashTest : public ::testing::Test {
 protected:
  CrashTest() {}

  std::unique_ptr<grpc::cpp::test::util::TestService::Stub> CreateServerAndStub() {
    auto port = grpc_pick_unused_port_or_die();
    auto addr = (std::ostringstream() << "localhost:" << port).str();
    server_.reset(new SubProcess({
      (std::ostringstream() << g_root << "/crash_test_server").str(),
      (std::ostringstream() << "--address=" << addr).str(),
    }));
    GPR_ASSERT(server_);
    return grpc::cpp::test::util::TestService::NewStub(CreateChannel(addr, InsecureCredentials(), ChannelArguments()));
  }

  void KillServer() {
    server_.reset();
  }

 private:
  std::unique_ptr<SubProcess> server_;
};

TEST_F(CrashTest, KillAfterWrite) {
  auto stub = CreateServerAndStub();

  EchoRequest request;
  EchoResponse response;
  ClientContext context;

  auto stream = stub->BidiStream(&context);

  request.set_message("Hello");
  EXPECT_TRUE(stream->Write(request));
  EXPECT_TRUE(stream->Read(&response));
  EXPECT_EQ(response.message(), request.message());

  request.set_message("I'm going to kill you");
  EXPECT_TRUE(stream->Write(request));

  KillServer();

  EXPECT_FALSE(stream->Read(&response));

  EXPECT_FALSE(stream->Finish().IsOk());
}

TEST_F(CrashTest, KillBeforeWrite) {
  auto stub = CreateServerAndStub();

  EchoRequest request;
  EchoResponse response;
  ClientContext context;

  auto stream = stub->BidiStream(&context);

  request.set_message("Hello");
  EXPECT_TRUE(stream->Write(request));
  EXPECT_TRUE(stream->Read(&response));
  EXPECT_EQ(response.message(), request.message());

  KillServer();

  request.set_message("You should be dead");
  EXPECT_FALSE(stream->Write(request));
  EXPECT_FALSE(stream->Read(&response));

  EXPECT_FALSE(stream->Finish().IsOk());
}

}  // namespace

}  // namespace testing
}  // namespace grpc

int main(int argc, char** argv) {
  std::string me = argv[0];
  auto lslash = me.rfind('/');
  if (lslash != std::string::npos) {
    g_root = me.substr(0, lslash);
  } else {
    g_root = ".";
  }

  grpc_test_init(argc, argv);
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<commit_msg>Sleep a little after server death to allow TCP time to catch up<commit_after>/*
 *
 * Copyright 2015, Google Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <thread>

#include "test/core/util/port.h"
#include "test/core/util/test_config.h"
#include "test/cpp/util/echo_duplicate.grpc.pb.h"
#include "test/cpp/util/echo.grpc.pb.h"
#include "src/cpp/server/thread_pool.h"
#include <grpc++/channel_arguments.h>
#include <grpc++/channel_interface.h>
#include <grpc++/client_context.h>
#include <grpc++/create_channel.h>
#include <grpc++/credentials.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <grpc++/server_context.h>
#include <grpc++/server_credentials.h>
#include <grpc++/status.h>
#include <grpc++/stream.h>
#include <grpc++/time.h>
#include <gtest/gtest.h>

#include <grpc/grpc.h>
#include <grpc/support/thd.h>
#include <grpc/support/time.h>

#include "test/cpp/util/subprocess.h"

using grpc::cpp::test::util::EchoRequest;
using grpc::cpp::test::util::EchoResponse;
using std::chrono::system_clock;

static std::string g_root;

namespace grpc {
namespace testing {

namespace {

class CrashTest : public ::testing::Test {
 protected:
  CrashTest() {}

  std::unique_ptr<grpc::cpp::test::util::TestService::Stub> CreateServerAndStub() {
    auto port = grpc_pick_unused_port_or_die();
    auto addr = (std::ostringstream() << "localhost:" << port).str();
    server_.reset(new SubProcess({
      (std::ostringstream() << g_root << "/crash_test_server").str(),
      (std::ostringstream() << "--address=" << addr).str(),
    }));
    GPR_ASSERT(server_);
    return grpc::cpp::test::util::TestService::NewStub(CreateChannel(addr, InsecureCredentials(), ChannelArguments()));
  }

  void KillServer() {
    server_.reset();
    // give some time for the TCP connection to drop
    gpr_sleep_until(gpr_time_add(gpr_now(), gpr_time_from_seconds(1)));
  }

 private:
  std::unique_ptr<SubProcess> server_;
};

TEST_F(CrashTest, KillAfterWrite) {
  auto stub = CreateServerAndStub();

  EchoRequest request;
  EchoResponse response;
  ClientContext context;

  auto stream = stub->BidiStream(&context);

  request.set_message("Hello");
  EXPECT_TRUE(stream->Write(request));
  EXPECT_TRUE(stream->Read(&response));
  EXPECT_EQ(response.message(), request.message());

  request.set_message("I'm going to kill you");
  EXPECT_TRUE(stream->Write(request));

  KillServer();

  EXPECT_FALSE(stream->Read(&response));

  EXPECT_FALSE(stream->Finish().IsOk());
}

TEST_F(CrashTest, KillBeforeWrite) {
  auto stub = CreateServerAndStub();

  EchoRequest request;
  EchoResponse response;
  ClientContext context;

  auto stream = stub->BidiStream(&context);

  request.set_message("Hello");
  EXPECT_TRUE(stream->Write(request));
  EXPECT_TRUE(stream->Read(&response));
  EXPECT_EQ(response.message(), request.message());

  KillServer();

  request.set_message("You should be dead");
  EXPECT_FALSE(stream->Write(request));
  EXPECT_FALSE(stream->Read(&response));

  EXPECT_FALSE(stream->Finish().IsOk());
}

}  // namespace

}  // namespace testing
}  // namespace grpc

int main(int argc, char** argv) {
  std::string me = argv[0];
  auto lslash = me.rfind('/');
  if (lslash != std::string::npos) {
    g_root = me.substr(0, lslash);
  } else {
    g_root = ".";
  }

  grpc_test_init(argc, argv);
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>#include <cap/version.h>
#include <pycap/property_tree_wrappers.h>
#include <pycap/energy_storage_device_wrappers.h>
#include <boost/python.hpp>
#include <string>
#include <memory>
#include <map>

BOOST_PYTHON_MODULE(_pycap)
{
    // Deprecated stuff
    boost::python::class_<pycap::ElectrochemicalImpedanceSpectroscopyData, std::shared_ptr<pycap::ElectrochemicalImpedanceSpectroscopyData>>("ElectrochemicalImpedanceSpectroscopyData")
        .def("impedance_spectroscopy", &pycap::ElectrochemicalImpedanceSpectroscopyData::impedance_spectroscopy)
        .def("measure_impedance", &pycap::ElectrochemicalImpedanceSpectroscopyData::measure_impedance)
        .def("get_frequency", &pycap::ElectrochemicalImpedanceSpectroscopyData::get_frequency)
        .def("get_complex_impedance", &pycap::ElectrochemicalImpedanceSpectroscopyData::get_complex_impedance)
        .def("clear", &pycap::ElectrochemicalImpedanceSpectroscopyData::clear)
        ;

    boost::python::docstring_options doc_options;
    doc_options.enable_user_defined();
    doc_options.disable_py_signatures();
    doc_options.disable_cpp_signatures();

    boost::python::class_<pycap::EnergyStorageDeviceWrap, std::shared_ptr<pycap::EnergyStorageDeviceWrap>, boost::noncopyable>("EnergyStorageDevice", "Wrappers for Cap.EnergyStorageDevice", boost::python::no_init)
        .def("__init__", boost::python::make_constructor(&pycap::build_energy_storage_device) )
        .def("get_voltage", (&pycap::get_voltage), boost::python::args("self") )
        .def("get_current", (&pycap::get_current), boost::python::args("self") )
        .def("evolve_one_time_step_constant_current", boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_constant_current), boost::python::args("self", "time_step", "current") )
        .def("evolve_one_time_step_constant_voltage", boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_constant_voltage), boost::python::args("self", "time_step", "voltage") )
        .def("evolve_one_time_step_constant_power"  , boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_constant_power  ), boost::python::args("self", "time_step", "load"   ) )
        .def("evolve_one_time_step_constant_load"   , boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_constant_load   ), boost::python::args("self", "time_step", "power"  ) )
        .def("evolve_one_time_step_changing_current", boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_changing_current), boost::python::args("self", "time_step", "current") )
        .def("evolve_one_time_step_changing_voltage", boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_changing_voltage), boost::python::args("self", "time_step", "voltage") )
        .def("evolve_one_time_step_changing_power"  , boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_changing_power  ), boost::python::args("self", "time_step", "power"  ) )
        .def("evolve_one_time_step_changing_load"   , boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_changing_load   ), boost::python::args("self", "time_step", "load"   ) )
        .def("compute_equivalent_circuit", &pycap::compute_equivalent_circuit, "Return the PropertyTree to build an equivalent circuit model", boost::python::args("ptree") )
        .staticmethod("compute_equivalent_circuit")
//        .def_pickle(pycap::serializable_class_pickle_support<cap::EnergyStorageDevice>())
        ;
    boost::python::register_ptr_to_python<std::shared_ptr<cap::EnergyStorageDevice>>();

    boost::python::scope().attr("__version__"        ) = cap::version()        ;
    boost::python::scope().attr("__git_branch__"     ) = cap::git_branch()     ;
    boost::python::scope().attr("__git_commit_hash__") = cap::git_commit_hash();

    boost::python::class_<boost::property_tree::ptree,std::shared_ptr<boost::property_tree::ptree>>("PropertyTree", "Wrappers for Boost.PropertyTree")
        .def("get_double"                   , &pycap::get_double                   , "Get the double at the given path."                                , boost::python::args("self", "path") )
        .def("get_string"                   , &pycap::get_string                   , "Get the string at the given path."                                , boost::python::args("self", "path") )
        .def("get_int"                      , &pycap::get_int                      , "Get the integer at the given path."                               , boost::python::args("self", "path") )
        .def("get_bool"                     , &pycap::get_bool                     , "Get the boolean at the given path."                               , boost::python::args("self", "path") )
        .def("get_double_with_default_value", &pycap::get_double_with_default_value, "Get the double at the given path or return default_value."        , boost::python::args("self", "path", "default_value") )
        .def("get_string_with_default_value", &pycap::get_string_with_default_value, "Get the string at the given path or return default_value."        , boost::python::args("self", "path", "default_value") )
        .def("get_int_with_default_value"   , &pycap::get_int_with_default_value   , "Get the integer at the given path or return default_value."       , boost::python::args("self", "path", "default_value") )
        .def("get_bool_with_default_value"  , &pycap::get_bool_with_default_value  , "Get the boolean at the given path or return default_value."       , boost::python::args("self", "path", "default_value") )
        .def("put_double"                   , &pycap::put_double                   , "Set the node at the given path to the supplied value."            , boost::python::args("self", "path", "value") )
        .def("put_string"                   , &pycap::put_string                   , "Set the node at the given path to the supplied value."            , boost::python::args("self", "path", "value") )
        .def("put_int"                      , &pycap::put_int                      , "Set the node at the given path to the supplied value."            , boost::python::args("self", "path", "value") )
        .def("put_bool"                     , &pycap::put_bool                     , "Set the node at the given path to the supplied value."            , boost::python::args("self", "path", "value") )
        .def("get_array_double"             , &pycap::get_array_double             , "Get comma separated array of double."                             , boost::python::args("self", "path") )
        .def("get_array_string"             , &pycap::get_array_string             , "Get comma separated array of string."                             , boost::python::args("self", "path") )
        .def("get_array_int"                , &pycap::get_array_int                , "Get comma separated array of integer."                            , boost::python::args("self", "path") )
        .def("get_array_bool"               , &pycap::get_array_bool               , "Get comma separated array of boolean."                            , boost::python::args("self", "path") )
        .def("parse_xml"                    , &pycap::parse_xml                    , "Read the input file at XML format and populate the PropertyTree." , boost::python::args("self", "filename") )
        .def("parse_json"                   , &pycap::parse_json                   , "Read the input file at JSON format and populate the PropertyTree.", boost::python::args("self", "filename") )
        .def("parse_info"                   , &pycap::parse_info                   , "Read the input file at INFO format and populate the PropertyTree.", boost::python::args("self", "filename") )
        .def("get_child"                    , &pycap::get_child                    , "Get the child at the given path, or throw ptree_bad_path."        , boost::python::args("self", "path") )
        .def_pickle(pycap::serializable_class_pickle_support<boost::property_tree::ptree>())
        ;
}
<commit_msg>enable py signature in docstring<commit_after>#include <cap/version.h>
#include <pycap/property_tree_wrappers.h>
#include <pycap/energy_storage_device_wrappers.h>
#include <boost/python.hpp>
#include <string>
#include <memory>
#include <map>

BOOST_PYTHON_MODULE(_pycap)
{
    // Deprecated stuff
    boost::python::class_<pycap::ElectrochemicalImpedanceSpectroscopyData, std::shared_ptr<pycap::ElectrochemicalImpedanceSpectroscopyData>>("ElectrochemicalImpedanceSpectroscopyData")
        .def("impedance_spectroscopy", &pycap::ElectrochemicalImpedanceSpectroscopyData::impedance_spectroscopy)
        .def("measure_impedance", &pycap::ElectrochemicalImpedanceSpectroscopyData::measure_impedance)
        .def("get_frequency", &pycap::ElectrochemicalImpedanceSpectroscopyData::get_frequency)
        .def("get_complex_impedance", &pycap::ElectrochemicalImpedanceSpectroscopyData::get_complex_impedance)
        .def("clear", &pycap::ElectrochemicalImpedanceSpectroscopyData::clear)
        ;

    boost::python::docstring_options doc_options;
    doc_options.enable_user_defined();
    doc_options.enable_py_signatures();
    doc_options.disable_cpp_signatures();

    boost::python::class_<pycap::EnergyStorageDeviceWrap, std::shared_ptr<pycap::EnergyStorageDeviceWrap>, boost::noncopyable>("EnergyStorageDevice", "Wrappers for Cap.EnergyStorageDevice", boost::python::no_init)
        .def("__init__", boost::python::make_constructor(&pycap::build_energy_storage_device) )
        .def("get_voltage", (&pycap::get_voltage), boost::python::args("self") )
        .def("get_current", (&pycap::get_current), boost::python::args("self") )
        .def("evolve_one_time_step_constant_current", boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_constant_current), boost::python::args("self", "time_step", "current") )
        .def("evolve_one_time_step_constant_voltage", boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_constant_voltage), boost::python::args("self", "time_step", "voltage") )
        .def("evolve_one_time_step_constant_power"  , boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_constant_power  ), boost::python::args("self", "time_step", "load"   ) )
        .def("evolve_one_time_step_constant_load"   , boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_constant_load   ), boost::python::args("self", "time_step", "power"  ) )
        .def("evolve_one_time_step_changing_current", boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_changing_current), boost::python::args("self", "time_step", "current") )
        .def("evolve_one_time_step_changing_voltage", boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_changing_voltage), boost::python::args("self", "time_step", "voltage") )
        .def("evolve_one_time_step_changing_power"  , boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_changing_power  ), boost::python::args("self", "time_step", "power"  ) )
        .def("evolve_one_time_step_changing_load"   , boost::python::pure_virtual(&cap::EnergyStorageDevice::evolve_one_time_step_changing_load   ), boost::python::args("self", "time_step", "load"   ) )
        .def("compute_equivalent_circuit", &pycap::compute_equivalent_circuit, "Return the PropertyTree to build an equivalent circuit model", boost::python::args("ptree") )
        .staticmethod("compute_equivalent_circuit")
//        .def_pickle(pycap::serializable_class_pickle_support<cap::EnergyStorageDevice>())
        ;
    boost::python::register_ptr_to_python<std::shared_ptr<cap::EnergyStorageDevice>>();

    boost::python::scope().attr("__version__"        ) = cap::version()        ;
    boost::python::scope().attr("__git_branch__"     ) = cap::git_branch()     ;
    boost::python::scope().attr("__git_commit_hash__") = cap::git_commit_hash();

    boost::python::class_<boost::property_tree::ptree,std::shared_ptr<boost::property_tree::ptree>>("PropertyTree", "Wrappers for Boost.PropertyTree")
        .def("get_double"                   , &pycap::get_double                   , "Get the double at the given path."                                , boost::python::args("self", "path") )
        .def("get_string"                   , &pycap::get_string                   , "Get the string at the given path."                                , boost::python::args("self", "path") )
        .def("get_int"                      , &pycap::get_int                      , "Get the integer at the given path."                               , boost::python::args("self", "path") )
        .def("get_bool"                     , &pycap::get_bool                     , "Get the boolean at the given path."                               , boost::python::args("self", "path") )
        .def("get_double_with_default_value", &pycap::get_double_with_default_value, "Get the double at the given path or return default_value."        , boost::python::args("self", "path", "default_value") )
        .def("get_string_with_default_value", &pycap::get_string_with_default_value, "Get the string at the given path or return default_value."        , boost::python::args("self", "path", "default_value") )
        .def("get_int_with_default_value"   , &pycap::get_int_with_default_value   , "Get the integer at the given path or return default_value."       , boost::python::args("self", "path", "default_value") )
        .def("get_bool_with_default_value"  , &pycap::get_bool_with_default_value  , "Get the boolean at the given path or return default_value."       , boost::python::args("self", "path", "default_value") )
        .def("put_double"                   , &pycap::put_double                   , "Set the node at the given path to the supplied value."            , boost::python::args("self", "path", "value") )
        .def("put_string"                   , &pycap::put_string                   , "Set the node at the given path to the supplied value."            , boost::python::args("self", "path", "value") )
        .def("put_int"                      , &pycap::put_int                      , "Set the node at the given path to the supplied value."            , boost::python::args("self", "path", "value") )
        .def("put_bool"                     , &pycap::put_bool                     , "Set the node at the given path to the supplied value."            , boost::python::args("self", "path", "value") )
        .def("get_array_double"             , &pycap::get_array_double             , "Get comma separated array of double."                             , boost::python::args("self", "path") )
        .def("get_array_string"             , &pycap::get_array_string             , "Get comma separated array of string."                             , boost::python::args("self", "path") )
        .def("get_array_int"                , &pycap::get_array_int                , "Get comma separated array of integer."                            , boost::python::args("self", "path") )
        .def("get_array_bool"               , &pycap::get_array_bool               , "Get comma separated array of boolean."                            , boost::python::args("self", "path") )
        .def("parse_xml"                    , &pycap::parse_xml                    , "Read the input file at XML format and populate the PropertyTree." , boost::python::args("self", "filename") )
        .def("parse_json"                   , &pycap::parse_json                   , "Read the input file at JSON format and populate the PropertyTree.", boost::python::args("self", "filename") )
        .def("parse_info"                   , &pycap::parse_info                   , "Read the input file at INFO format and populate the PropertyTree.", boost::python::args("self", "filename") )
        .def("get_child"                    , &pycap::get_child                    , "Get the child at the given path, or throw ptree_bad_path."        , boost::python::args("self", "path") )
        .def_pickle(pycap::serializable_class_pickle_support<boost::property_tree::ptree>())
        ;
}
<|endoftext|>


<commit_before>/*
*  Copyright 2011 Matthias Fuchs
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/

#include <stromx/core/Primitive.h>

#include <boost/python.hpp>

using namespace boost::python;
using namespace stromx::core;

void exportPrimitive()
{
    class_<Bool, bases<Data> >("Bool")
        .def(init<>())
        .def(init<bool>())
        .def("get", &Bool::get)
        .def("data_cast", &data_cast<Bool &>, return_internal_reference<1>())
        .staticmethod("data_cast")
    ;

    class_<Int8, bases<Data> >("Int8")
        .def(init<>())
        .def(init<int>())
        .def("get", &Int8::get)
        .def("data_cast", &data_cast<Int8 &>, return_internal_reference<1>())
        .staticmethod("data_cast")
    ;

    class_<UInt32, bases<Data> >("UInt32")
        .def(init<>())
        .def(init<unsigned int>())
        .def("get", &UInt32::get)
        .def("data_cast", &data_cast<UInt32 &>, return_internal_reference<1>())
        .staticmethod("data_cast")
    ;
}
<commit_msg>Python wrapper for all primitives<commit_after>/*
*  Copyright 2011 Matthias Fuchs
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/

#include <stromx/core/Primitive.h>

#include <boost/python.hpp>

using namespace boost::python;
using namespace stromx::core;

namespace
{
    template <class repr_t, class val_t>
    void primitive(const char* name)
    {
        class_<val_t, bases<Data> >(name)
            .def(init<>())
            .def(init<repr_t>())
            .def("get", &val_t::get)
            .def("data_cast", &data_cast<val_t &>, return_internal_reference<1>())
            .staticmethod("data_cast")
        ;
    }
}

void exportPrimitive()
{
    primitive<bool, Bool>("Bool");
    primitive<int, Int8>("Int8");
    primitive<unsigned int, UInt8>("UInt8");
    primitive<int, Int16>("Int16");
    primitive<unsigned int, UInt16>("UInt16");
    primitive<int, Int32>("Int32");
    primitive<unsigned int, UInt32>("UInt32");
    primitive<double, Float>("Float");
    primitive<float, Double>("Double");
}
<|endoftext|>


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

#include "net/third_party/quiche/src/quic/qbone/qbone_session_base.h"

#include <netinet/icmp6.h>
#include <netinet/ip6.h>

#include <utility>

#include "net/third_party/quiche/src/quic/core/quic_buffer_allocator.h"
#include "net/third_party/quiche/src/quic/core/quic_data_reader.h"
#include "net/third_party/quiche/src/quic/core/quic_types.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_exported_stats.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
#include "net/third_party/quiche/src/quic/qbone/platform/icmp_packet.h"
#include "net/third_party/quiche/src/quic/qbone/qbone_constants.h"
#include "net/third_party/quiche/src/common/platform/api/quiche_string_piece.h"

namespace quic {

#define ENDPOINT \
  (perspective() == Perspective::IS_SERVER ? "Server: " : "Client: ")

QboneSessionBase::QboneSessionBase(
    QuicConnection* connection,
    Visitor* owner,
    const QuicConfig& config,
    const ParsedQuicVersionVector& supported_versions,
    QbonePacketWriter* writer)
    : QuicSession(connection,
                  owner,
                  config,
                  supported_versions,
                  /*num_expected_unidirectional_static_streams = */ 0) {
  set_writer(writer);
  const uint32_t max_streams =
      (std::numeric_limits<uint32_t>::max() / kMaxAvailableStreamsMultiplier) -
      1;
  this->config()->SetMaxBidirectionalStreamsToSend(max_streams);
  if (VersionHasIetfQuicFrames(transport_version())) {
    ConfigureMaxDynamicStreamsToSend(max_streams);
  }
}

QboneSessionBase::~QboneSessionBase() {
  // Clear out the streams before leaving this destructor to avoid calling
  // QuicSession::UnregisterStreamPriority
  stream_map().clear();
  closed_streams()->clear();
}

void QboneSessionBase::Initialize() {
  crypto_stream_ = CreateCryptoStream();
  QuicSession::Initialize();
}

const QuicCryptoStream* QboneSessionBase::GetCryptoStream() const {
  return crypto_stream_.get();
}

QuicCryptoStream* QboneSessionBase::GetMutableCryptoStream() {
  return crypto_stream_.get();
}

QuicStream* QboneSessionBase::CreateOutgoingStream() {
  return ActivateDataStream(
      CreateDataStream(GetNextOutgoingUnidirectionalStreamId()));
}

void QboneSessionBase::CloseStream(QuicStreamId stream_id) {
  if (IsClosedStream(stream_id)) {
    // When CloseStream has been called recursively (via
    // QuicStream::OnClose), the stream is already closed so return.
    return;
  }
  QuicSession::CloseStream(stream_id);
}

void QboneSessionBase::OnStreamFrame(const QuicStreamFrame& frame) {
  if (frame.offset == 0 && frame.fin && frame.data_length > 0) {
    ++num_ephemeral_packets_;
    ProcessPacketFromPeer(
        quiche::QuicheStringPiece(frame.data_buffer, frame.data_length));
    flow_controller()->AddBytesConsumed(frame.data_length);
    return;
  }
  QuicSession::OnStreamFrame(frame);
}

void QboneSessionBase::OnMessageReceived(quiche::QuicheStringPiece message) {
  ++num_message_packets_;
  ProcessPacketFromPeer(message);
}

QuicStream* QboneSessionBase::CreateIncomingStream(QuicStreamId id) {
  return ActivateDataStream(CreateDataStream(id));
}

QuicStream* QboneSessionBase::CreateIncomingStream(PendingStream* /*pending*/) {
  QUIC_NOTREACHED();
  return nullptr;
}

bool QboneSessionBase::ShouldKeepConnectionAlive() const {
  // QBONE connections stay alive until they're explicitly closed.
  return true;
}

std::unique_ptr<QuicStream> QboneSessionBase::CreateDataStream(
    QuicStreamId id) {
  if (crypto_stream_ == nullptr || !crypto_stream_->encryption_established()) {
    // Encryption not active so no stream created
    return nullptr;
  }

  if (IsIncomingStream(id)) {
    ++num_streamed_packets_;
    return std::make_unique<QboneReadOnlyStream>(id, this);
  }

  return std::make_unique<QboneWriteOnlyStream>(id, this);
}

QuicStream* QboneSessionBase::ActivateDataStream(
    std::unique_ptr<QuicStream> stream) {
  // Transfer ownership of the data stream to the session via ActivateStream().
  QuicStream* raw = stream.get();
  if (stream) {
    // Make QuicSession take ownership of the stream.
    ActivateStream(std::move(stream));
  }
  return raw;
}

void QboneSessionBase::SendPacketToPeer(quiche::QuicheStringPiece packet) {
  if (crypto_stream_ == nullptr) {
    QUIC_BUG << "Attempting to send packet before encryption established";
    return;
  }

  if (send_packets_as_messages_) {
    QuicUniqueBufferPtr buffer = MakeUniqueBuffer(
        connection()->helper()->GetStreamSendBufferAllocator(), packet.size());
    memcpy(buffer.get(), packet.data(), packet.size());
    QuicMemSlice slice(std::move(buffer), packet.size());
    switch (SendMessage(QuicMemSliceSpan(&slice), /*flush=*/true).status) {
      case MESSAGE_STATUS_SUCCESS:
        break;
      case MESSAGE_STATUS_TOO_LARGE: {
        if (packet.size() < sizeof(ip6_hdr)) {
          QUIC_BUG << "Dropped malformed packet: IPv6 header too short";
          break;
        }
        auto* header = reinterpret_cast<const ip6_hdr*>(packet.begin());
        icmp6_hdr icmp_header{};
        icmp_header.icmp6_type = ICMP6_PACKET_TOO_BIG;
        icmp_header.icmp6_mtu =
            connection()->GetGuaranteedLargestMessagePayload();

        CreateIcmpPacket(header->ip6_dst, header->ip6_src, icmp_header, packet,
                         [this](quiche::QuicheStringPiece icmp_packet) {
                           writer_->WritePacketToNetwork(icmp_packet.data(),
                                                         icmp_packet.size());
                         });
        break;
      }
      case MESSAGE_STATUS_ENCRYPTION_NOT_ESTABLISHED:
        QUIC_BUG << "MESSAGE_STATUS_ENCRYPTION_NOT_ESTABLISHED";
        break;
      case MESSAGE_STATUS_UNSUPPORTED:
        QUIC_BUG << "MESSAGE_STATUS_UNSUPPORTED";
        break;
      case MESSAGE_STATUS_BLOCKED:
        QUIC_BUG << "MESSAGE_STATUS_BLOCKED";
        break;
      case MESSAGE_STATUS_INTERNAL_ERROR:
        QUIC_BUG << "MESSAGE_STATUS_INTERNAL_ERROR";
        break;
    }
    return;
  }

  // QBONE streams are ephemeral.
  QuicStream* stream = CreateOutgoingStream();
  if (!stream) {
    QUIC_BUG << "Failed to create an outgoing QBONE stream.";
    return;
  }

  QboneWriteOnlyStream* qbone_stream =
      static_cast<QboneWriteOnlyStream*>(stream);
  qbone_stream->WritePacketToQuicStream(packet);
}

uint64_t QboneSessionBase::GetNumEphemeralPackets() const {
  return num_ephemeral_packets_;
}

uint64_t QboneSessionBase::GetNumStreamedPackets() const {
  return num_streamed_packets_;
}

uint64_t QboneSessionBase::GetNumMessagePackets() const {
  return num_message_packets_;
}

uint64_t QboneSessionBase::GetNumFallbackToStream() const {
  return num_fallback_to_stream_;
}

void QboneSessionBase::set_writer(QbonePacketWriter* writer) {
  writer_ = writer;
  testing::testvalue::Adjust("quic_QbonePacketWriter", &writer_);
}

}  // namespace quic
<commit_msg>Close any existing stream when processing an ephemeral packet.<commit_after>// Copyright (c) 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/third_party/quiche/src/quic/qbone/qbone_session_base.h"

#include <netinet/icmp6.h>
#include <netinet/ip6.h>

#include <utility>

#include "net/third_party/quiche/src/quic/core/quic_buffer_allocator.h"
#include "net/third_party/quiche/src/quic/core/quic_data_reader.h"
#include "net/third_party/quiche/src/quic/core/quic_types.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_exported_stats.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
#include "net/third_party/quiche/src/quic/qbone/platform/icmp_packet.h"
#include "net/third_party/quiche/src/quic/qbone/qbone_constants.h"
#include "net/third_party/quiche/src/common/platform/api/quiche_string_piece.h"

ABSL_FLAG(
    bool,
    qbone_close_ephemeral_frames,
    true,
    "If true, we'll call CloseStream even when we receive ephemeral frames.");

namespace quic {

#define ENDPOINT \
  (perspective() == Perspective::IS_SERVER ? "Server: " : "Client: ")

QboneSessionBase::QboneSessionBase(
    QuicConnection* connection,
    Visitor* owner,
    const QuicConfig& config,
    const ParsedQuicVersionVector& supported_versions,
    QbonePacketWriter* writer)
    : QuicSession(connection,
                  owner,
                  config,
                  supported_versions,
                  /*num_expected_unidirectional_static_streams = */ 0) {
  set_writer(writer);
  const uint32_t max_streams =
      (std::numeric_limits<uint32_t>::max() / kMaxAvailableStreamsMultiplier) -
      1;
  this->config()->SetMaxBidirectionalStreamsToSend(max_streams);
  if (VersionHasIetfQuicFrames(transport_version())) {
    ConfigureMaxDynamicStreamsToSend(max_streams);
  }
}

QboneSessionBase::~QboneSessionBase() {
  // Clear out the streams before leaving this destructor to avoid calling
  // QuicSession::UnregisterStreamPriority
  stream_map().clear();
  closed_streams()->clear();
}

void QboneSessionBase::Initialize() {
  crypto_stream_ = CreateCryptoStream();
  QuicSession::Initialize();
}

const QuicCryptoStream* QboneSessionBase::GetCryptoStream() const {
  return crypto_stream_.get();
}

QuicCryptoStream* QboneSessionBase::GetMutableCryptoStream() {
  return crypto_stream_.get();
}

QuicStream* QboneSessionBase::CreateOutgoingStream() {
  return ActivateDataStream(
      CreateDataStream(GetNextOutgoingUnidirectionalStreamId()));
}

void QboneSessionBase::CloseStream(QuicStreamId stream_id) {
  if (IsClosedStream(stream_id)) {
    // When CloseStream has been called recursively (via
    // QuicStream::OnClose), the stream is already closed so return.
    return;
  }
  QuicSession::CloseStream(stream_id);
}

void QboneSessionBase::OnStreamFrame(const QuicStreamFrame& frame) {
  if (frame.offset == 0 && frame.fin && frame.data_length > 0) {
    ++num_ephemeral_packets_;
    ProcessPacketFromPeer(
        quiche::QuicheStringPiece(frame.data_buffer, frame.data_length));
    flow_controller()->AddBytesConsumed(frame.data_length);
    // TODO(b/147817422): Add a counter for how many streams were actually
    // closed here.
    if (GetQuicFlag(FLAGS_qbone_close_ephemeral_frames)) {
      CloseStream(frame.stream_id);
    }
    return;
  }
  QuicSession::OnStreamFrame(frame);
}

void QboneSessionBase::OnMessageReceived(quiche::QuicheStringPiece message) {
  ++num_message_packets_;
  ProcessPacketFromPeer(message);
}

QuicStream* QboneSessionBase::CreateIncomingStream(QuicStreamId id) {
  return ActivateDataStream(CreateDataStream(id));
}

QuicStream* QboneSessionBase::CreateIncomingStream(PendingStream* /*pending*/) {
  QUIC_NOTREACHED();
  return nullptr;
}

bool QboneSessionBase::ShouldKeepConnectionAlive() const {
  // QBONE connections stay alive until they're explicitly closed.
  return true;
}

std::unique_ptr<QuicStream> QboneSessionBase::CreateDataStream(
    QuicStreamId id) {
  if (crypto_stream_ == nullptr || !crypto_stream_->encryption_established()) {
    // Encryption not active so no stream created
    return nullptr;
  }

  if (IsIncomingStream(id)) {
    ++num_streamed_packets_;
    return std::make_unique<QboneReadOnlyStream>(id, this);
  }

  return std::make_unique<QboneWriteOnlyStream>(id, this);
}

QuicStream* QboneSessionBase::ActivateDataStream(
    std::unique_ptr<QuicStream> stream) {
  // Transfer ownership of the data stream to the session via ActivateStream().
  QuicStream* raw = stream.get();
  if (stream) {
    // Make QuicSession take ownership of the stream.
    ActivateStream(std::move(stream));
  }
  return raw;
}

void QboneSessionBase::SendPacketToPeer(quiche::QuicheStringPiece packet) {
  if (crypto_stream_ == nullptr) {
    QUIC_BUG << "Attempting to send packet before encryption established";
    return;
  }

  if (send_packets_as_messages_) {
    QuicUniqueBufferPtr buffer = MakeUniqueBuffer(
        connection()->helper()->GetStreamSendBufferAllocator(), packet.size());
    memcpy(buffer.get(), packet.data(), packet.size());
    QuicMemSlice slice(std::move(buffer), packet.size());
    switch (SendMessage(QuicMemSliceSpan(&slice), /*flush=*/true).status) {
      case MESSAGE_STATUS_SUCCESS:
        break;
      case MESSAGE_STATUS_TOO_LARGE: {
        if (packet.size() < sizeof(ip6_hdr)) {
          QUIC_BUG << "Dropped malformed packet: IPv6 header too short";
          break;
        }
        auto* header = reinterpret_cast<const ip6_hdr*>(packet.begin());
        icmp6_hdr icmp_header{};
        icmp_header.icmp6_type = ICMP6_PACKET_TOO_BIG;
        icmp_header.icmp6_mtu =
            connection()->GetGuaranteedLargestMessagePayload();

        CreateIcmpPacket(header->ip6_dst, header->ip6_src, icmp_header, packet,
                         [this](quiche::QuicheStringPiece icmp_packet) {
                           writer_->WritePacketToNetwork(icmp_packet.data(),
                                                         icmp_packet.size());
                         });
        break;
      }
      case MESSAGE_STATUS_ENCRYPTION_NOT_ESTABLISHED:
        QUIC_BUG << "MESSAGE_STATUS_ENCRYPTION_NOT_ESTABLISHED";
        break;
      case MESSAGE_STATUS_UNSUPPORTED:
        QUIC_BUG << "MESSAGE_STATUS_UNSUPPORTED";
        break;
      case MESSAGE_STATUS_BLOCKED:
        QUIC_BUG << "MESSAGE_STATUS_BLOCKED";
        break;
      case MESSAGE_STATUS_INTERNAL_ERROR:
        QUIC_BUG << "MESSAGE_STATUS_INTERNAL_ERROR";
        break;
    }
    return;
  }

  // QBONE streams are ephemeral.
  QuicStream* stream = CreateOutgoingStream();
  if (!stream) {
    QUIC_BUG << "Failed to create an outgoing QBONE stream.";
    return;
  }

  QboneWriteOnlyStream* qbone_stream =
      static_cast<QboneWriteOnlyStream*>(stream);
  qbone_stream->WritePacketToQuicStream(packet);
}

uint64_t QboneSessionBase::GetNumEphemeralPackets() const {
  return num_ephemeral_packets_;
}

uint64_t QboneSessionBase::GetNumStreamedPackets() const {
  return num_streamed_packets_;
}

uint64_t QboneSessionBase::GetNumMessagePackets() const {
  return num_message_packets_;
}

uint64_t QboneSessionBase::GetNumFallbackToStream() const {
  return num_fallback_to_stream_;
}

void QboneSessionBase::set_writer(QbonePacketWriter* writer) {
  writer_ = writer;
  testing::testvalue::Adjust("quic_QbonePacketWriter", &writer_);
}

}  // namespace quic
<|endoftext|>


<commit_before>/***********************************************************************
    filename:   CEGUIOgreTexture.cpp
    created:    Tue Feb 17 2009
    author:     Paul D Turner
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
 *
 *   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 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 "CEGUIOgreTexture.h"
#include "CEGUIExceptions.h"
#include "CEGUISystem.h"
#include "CEGUIImageCodec.h"
#include <OgreTextureManager.h>

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
// Internal function that reverses all bytes in a buffer
void _byteSwap(unsigned char* b, int n)
{
    register int i = 0;
    register int j = n-1;
    while (i < j)
        std::swap(b[i++], b[j--]);
}
#define byteSwap(x) _byteSwap((unsigned char*) &x,sizeof(x))

//----------------------------------------------------------------------------//
uint32 OgreTexture::d_textureNumber = 0;

//----------------------------------------------------------------------------//
const Size& OgreTexture::getSize() const
{
    return d_size;
}

//----------------------------------------------------------------------------//
const Size& OgreTexture::getOriginalDataSize() const
{
    return d_dataSize;
}

//----------------------------------------------------------------------------//
const Vector2& OgreTexture::getTexelScaling() const
{
    return d_texelScaling;
}

//----------------------------------------------------------------------------//
void OgreTexture::loadFromFile(const String& filename,
                               const String& resourceGroup)
{
    // get and check existence of CEGUI::System object
    System* sys = System::getSingletonPtr();
    if (!sys)
        throw RendererException("OgreTexture::loadFromFile: "
                                "CEGUI::System object has not been created!");

    // load file to memory via resource provider
    RawDataContainer texFile;
    sys->getResourceProvider()->loadRawDataContainer(filename, texFile,
                                                     resourceGroup);

    Texture* res = sys->getImageCodec().load(texFile, this);

    // unload file data buffer
    sys->getResourceProvider()->unloadRawDataContainer(texFile);

    // throw exception if data was load loaded to texture.
    if (!res)
        throw RendererException("OgreTexture::loadFromFile: " +
                                sys->getImageCodec().getIdentifierString()+
                                " failed to load image '" + filename + "'.");
}

//----------------------------------------------------------------------------//
void OgreTexture::loadFromMemory(const void* buffer, const Size& buffer_size,
                                 PixelFormat pixel_format)
{
    using namespace Ogre;

    // get rid of old texture
    freeOgreTexture();

    // wrap input buffer with an Ogre data stream
    const size_t pixel_size = pixel_format == PF_RGBA ? 4 : 3;
    const size_t byte_size = buffer_size.d_width * buffer_size.d_height *
                                pixel_size;

#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
    // FIXME: I think this leaks memory, though need to check!
    unsigned char* swapped_buffer = new unsigned char[byte_size];
    memcpy(swapped_buffer, buffer, byte_size);

    for (size_t i = 0; i < byte_size; i += pixel_size)
        _byteSwap(&swapped_buffer[i], pixel_size);

    DataStreamPtr odc(new MemoryDataStream(static_cast<void*>(swapped_buffer),
                                           byte_size, false));
#else
    DataStreamPtr odc(new MemoryDataStream(const_cast<void*>(buffer),
                                           byte_size, false));
#endif

    // get pixel type for the target texture.
    Ogre::PixelFormat target_fmt =
        (pixel_format == PF_RGBA) ? Ogre::PF_A8B8G8R8 : Ogre::PF_B8G8R8;

    // try to create a Ogre::Texture from the input data
    d_texture = TextureManager::getSingleton().loadRawData(
        getUniqueName(), "General", odc,
        buffer_size.d_width, buffer_size.d_height,
        target_fmt, TEX_TYPE_2D, 0, 1.0f);

    // throw exception if no texture was able to be created
    if (d_texture.isNull())
        throw RendererException("OgreTexture::loadFromMemory: Failed to create "
                                "Texture object from memory.");

    d_size.d_width = d_texture->getWidth();
    d_size.d_height = d_texture->getHeight();
    d_dataSize = buffer_size;
    updateCachedScaleValues();
}

//----------------------------------------------------------------------------//
void OgreTexture::saveToMemory(void* buffer)
{
    // TODO:
}

//----------------------------------------------------------------------------//
OgreTexture::OgreTexture() :
    d_isLinked(false),
    d_size(0, 0),
    d_dataSize(0, 0),
    d_texelScaling(0, 0)
{
}

//----------------------------------------------------------------------------//
OgreTexture::OgreTexture(const String& filename, const String& resourceGroup) :
    d_isLinked(false),
    d_size(0, 0),
    d_dataSize(0, 0),
    d_texelScaling(0, 0)
{
    loadFromFile(filename, resourceGroup);
}

//----------------------------------------------------------------------------//
OgreTexture::OgreTexture(const Size& sz) :
    d_isLinked(false),
    d_size(0, 0),
    d_dataSize(0, 0),
    d_texelScaling(0, 0)
{
    // TODO:
}

//----------------------------------------------------------------------------//
OgreTexture::OgreTexture(Ogre::TexturePtr& tex, bool take_ownership) :
    d_isLinked(false),
    d_size(0, 0),
    d_dataSize(0, 0),
    d_texelScaling(0, 0)
{
    setOgreTexture(tex, take_ownership);
}

//----------------------------------------------------------------------------//
OgreTexture::~OgreTexture()
{
    freeOgreTexture();
}

//----------------------------------------------------------------------------//
void OgreTexture::freeOgreTexture()
{
    if (!d_texture.isNull() && !d_isLinked)
        Ogre::TextureManager::getSingleton().remove(d_texture->getHandle());

    d_texture.setNull();
}

//----------------------------------------------------------------------------//
Ogre::String OgreTexture::getUniqueName()
{
    Ogre::StringUtil::StrStreamType strstream;
    strstream << "_cegui_ogre_" << d_textureNumber++;

    return strstream.str();
}

//----------------------------------------------------------------------------//
void OgreTexture::updateCachedScaleValues()
{
    //
    // calculate what to use for x scale
    //
    const float orgW = d_dataSize.d_width;
    const float texW = d_size.d_width;

    // if texture and original data width are the same, scale is based
    // on the original size.
    // if texture is wider (and source data was not stretched), scale
    // is based on the size of the resulting texture.
    d_texelScaling.d_x = 1.0f / ((orgW == texW) ? orgW : texW);

    //
    // calculate what to use for y scale
    //
    const float orgH = d_dataSize.d_height;
    const float texH = d_size.d_height;

    // if texture and original data height are the same, scale is based
    // on the original size.
    // if texture is taller (and source data was not stretched), scale
    // is based on the size of the resulting texture.
    d_texelScaling.d_y = 1.0f / ((orgH == texH) ? orgH : texH);
}

//----------------------------------------------------------------------------//
void OgreTexture::setOgreTexture(Ogre::TexturePtr texture, bool take_ownership)
{
    freeOgreTexture();

    d_texture = texture;
    d_isLinked = !take_ownership;

    if (!d_texture.isNull())
    {
        d_size.d_width = d_texture->getWidth();
        d_size.d_height= d_texture->getHeight();
        d_dataSize = d_size;
    }
    else
        d_size = d_dataSize = Size(0, 0);

    updateCachedScaleValues();
}

//----------------------------------------------------------------------------//
Ogre::TexturePtr OgreTexture::getOgreTexture() const
{
    return d_texture;
}

//----------------------------------------------------------------------------//

} // End of  CEGUI namespace section
<commit_msg>ADD: Implement missing parts in Ogre renderer.<commit_after>/***********************************************************************
    filename:   CEGUIOgreTexture.cpp
    created:    Tue Feb 17 2009
    author:     Paul D Turner
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
 *
 *   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 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 "CEGUIOgreTexture.h"
#include "CEGUIExceptions.h"
#include "CEGUISystem.h"
#include "CEGUIImageCodec.h"
#include <OgreTextureManager.h>
#include <OgreHardwarePixelBuffer.h>

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
// Internal function that reverses all bytes in a buffer
void _byteSwap(unsigned char* b, int n)
{
    register int i = 0;
    register int j = n-1;
    while (i < j)
        std::swap(b[i++], b[j--]);
}
#define byteSwap(x) _byteSwap((unsigned char*) &x,sizeof(x))

//----------------------------------------------------------------------------//
uint32 OgreTexture::d_textureNumber = 0;

//----------------------------------------------------------------------------//
const Size& OgreTexture::getSize() const
{
    return d_size;
}

//----------------------------------------------------------------------------//
const Size& OgreTexture::getOriginalDataSize() const
{
    return d_dataSize;
}

//----------------------------------------------------------------------------//
const Vector2& OgreTexture::getTexelScaling() const
{
    return d_texelScaling;
}

//----------------------------------------------------------------------------//
void OgreTexture::loadFromFile(const String& filename,
                               const String& resourceGroup)
{
    // get and check existence of CEGUI::System object
    System* sys = System::getSingletonPtr();
    if (!sys)
        throw RendererException("OgreTexture::loadFromFile: "
                                "CEGUI::System object has not been created!");

    // load file to memory via resource provider
    RawDataContainer texFile;
    sys->getResourceProvider()->loadRawDataContainer(filename, texFile,
                                                     resourceGroup);

    Texture* res = sys->getImageCodec().load(texFile, this);

    // unload file data buffer
    sys->getResourceProvider()->unloadRawDataContainer(texFile);

    // throw exception if data was load loaded to texture.
    if (!res)
        throw RendererException("OgreTexture::loadFromFile: " +
                                sys->getImageCodec().getIdentifierString()+
                                " failed to load image '" + filename + "'.");
}

//----------------------------------------------------------------------------//
void OgreTexture::loadFromMemory(const void* buffer, const Size& buffer_size,
                                 PixelFormat pixel_format)
{
    using namespace Ogre;

    // get rid of old texture
    freeOgreTexture();

    // wrap input buffer with an Ogre data stream
    const size_t pixel_size = pixel_format == PF_RGBA ? 4 : 3;
    const size_t byte_size = buffer_size.d_width * buffer_size.d_height *
                                pixel_size;

#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
    // FIXME: I think this leaks memory, though need to check!
    unsigned char* swapped_buffer = new unsigned char[byte_size];
    memcpy(swapped_buffer, buffer, byte_size);

    for (size_t i = 0; i < byte_size; i += pixel_size)
        _byteSwap(&swapped_buffer[i], pixel_size);

    DataStreamPtr odc(new MemoryDataStream(static_cast<void*>(swapped_buffer),
                                           byte_size, false));
#else
    DataStreamPtr odc(new MemoryDataStream(const_cast<void*>(buffer),
                                           byte_size, false));
#endif

    // get pixel type for the target texture.
    Ogre::PixelFormat target_fmt =
        (pixel_format == PF_RGBA) ? Ogre::PF_A8B8G8R8 : Ogre::PF_B8G8R8;

    // try to create a Ogre::Texture from the input data
    d_texture = TextureManager::getSingleton().loadRawData(
        getUniqueName(), "General", odc,
        buffer_size.d_width, buffer_size.d_height,
        target_fmt, TEX_TYPE_2D, 0, 1.0f);

    // throw exception if no texture was able to be created
    if (d_texture.isNull())
        throw RendererException("OgreTexture::loadFromMemory: Failed to create "
                                "Texture object from memory.");

    d_size.d_width = d_texture->getWidth();
    d_size.d_height = d_texture->getHeight();
    d_dataSize = buffer_size;
    updateCachedScaleValues();
}

//----------------------------------------------------------------------------//
void OgreTexture::saveToMemory(void* buffer)
{
    if (d_texture.isNull())
        return;

    Ogre::HardwarePixelBufferSharedPtr src = d_texture->getBuffer();

    if (src.isNull())
        throw RendererException("OgreTexture::saveToMemory: unable to obtain "
                                "hardware pixel buffer pointer.");

    const size_t sz = static_cast<size_t>(d_size.d_width * d_size.d_height) * 4;
    src->readData(0, sz, buffer);
}

//----------------------------------------------------------------------------//
OgreTexture::OgreTexture() :
    d_isLinked(false),
    d_size(0, 0),
    d_dataSize(0, 0),
    d_texelScaling(0, 0)
{
}

//----------------------------------------------------------------------------//
OgreTexture::OgreTexture(const String& filename, const String& resourceGroup) :
    d_isLinked(false),
    d_size(0, 0),
    d_dataSize(0, 0),
    d_texelScaling(0, 0)
{
    loadFromFile(filename, resourceGroup);
}

//----------------------------------------------------------------------------//
OgreTexture::OgreTexture(const Size& sz) :
    d_isLinked(false),
    d_size(0, 0),
    d_dataSize(0, 0),
    d_texelScaling(0, 0)
{
    using namespace Ogre;

    // try to create a Ogre::Texture with given dimensions
    d_texture = TextureManager::getSingleton().createManual(
                                   getUniqueName(), "General", TEX_TYPE_2D,
                                   sz.d_width, sz.d_height, 0,
                                   Ogre::PF_A8B8G8R8);

    // throw exception if no texture was able to be created
    if (d_texture.isNull())
        throw RendererException("OgreTexture: Failed to create Texture object "
                                "with spcecified size.");

    d_size.d_width = d_texture->getWidth();
    d_size.d_height = d_texture->getHeight();
    d_dataSize = sz;
    updateCachedScaleValues();
}

//----------------------------------------------------------------------------//
OgreTexture::OgreTexture(Ogre::TexturePtr& tex, bool take_ownership) :
    d_isLinked(false),
    d_size(0, 0),
    d_dataSize(0, 0),
    d_texelScaling(0, 0)
{
    setOgreTexture(tex, take_ownership);
}

//----------------------------------------------------------------------------//
OgreTexture::~OgreTexture()
{
    freeOgreTexture();
}

//----------------------------------------------------------------------------//
void OgreTexture::freeOgreTexture()
{
    if (!d_texture.isNull() && !d_isLinked)
        Ogre::TextureManager::getSingleton().remove(d_texture->getHandle());

    d_texture.setNull();
}

//----------------------------------------------------------------------------//
Ogre::String OgreTexture::getUniqueName()
{
    Ogre::StringUtil::StrStreamType strstream;
    strstream << "_cegui_ogre_" << d_textureNumber++;

    return strstream.str();
}

//----------------------------------------------------------------------------//
void OgreTexture::updateCachedScaleValues()
{
    //
    // calculate what to use for x scale
    //
    const float orgW = d_dataSize.d_width;
    const float texW = d_size.d_width;

    // if texture and original data width are the same, scale is based
    // on the original size.
    // if texture is wider (and source data was not stretched), scale
    // is based on the size of the resulting texture.
    d_texelScaling.d_x = 1.0f / ((orgW == texW) ? orgW : texW);

    //
    // calculate what to use for y scale
    //
    const float orgH = d_dataSize.d_height;
    const float texH = d_size.d_height;

    // if texture and original data height are the same, scale is based
    // on the original size.
    // if texture is taller (and source data was not stretched), scale
    // is based on the size of the resulting texture.
    d_texelScaling.d_y = 1.0f / ((orgH == texH) ? orgH : texH);
}

//----------------------------------------------------------------------------//
void OgreTexture::setOgreTexture(Ogre::TexturePtr texture, bool take_ownership)
{
    freeOgreTexture();

    d_texture = texture;
    d_isLinked = !take_ownership;

    if (!d_texture.isNull())
    {
        d_size.d_width = d_texture->getWidth();
        d_size.d_height= d_texture->getHeight();
        d_dataSize = d_size;
    }
    else
        d_size = d_dataSize = Size(0, 0);

    updateCachedScaleValues();
}

//----------------------------------------------------------------------------//
Ogre::TexturePtr OgreTexture::getOgreTexture() const
{
    return d_texture;
}

//----------------------------------------------------------------------------//

} // End of  CEGUI namespace section
<|endoftext|>