<commit_before>/*-----------------------------------------------------------------------------

 Copyright 2017 Hopsan Group

    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.

 The full license is available in the file LICENSE.
 For details about the 'Hopsan Group' or information about Authors and
 Contributors see the HOPSANGROUP and AUTHORS files that are located in
 the Hopsan source code root directory.

-----------------------------------------------------------------------------*/

// $Id$

#include <QString>
#include <QtTest>
#include <QDir>
#include <QtXml>
#include <QFileInfo>
#include <iostream>
#include "HopsanEssentials.h"
#include "CoreUtilities/HopsanCoreMessageHandler.h"
#include "HopsanCoreVersion.h"

#ifndef DEFAULT_LIBRARY_ROOT
#define DEFAULT_LIBRARY_ROOT "../componentLibraries/defaultLibrary"
#endif

#ifndef HOPSAN_INTERNALDEFAULTCOMPONENTS
#define DEFAULTLIBFILE SHAREDLIB_PREFIX "defaultcomponentlibrary" HOPSAN_DEBUG_POSTFIX "." SHAREDLIB_SUFFIX
const std::string defaultLibraryFilePath = DEFAULT_LIBRARY_ROOT "/" DEFAULTLIBFILE;
#else
const std::string defaultLibraryFilePath = "";
#endif

using namespace hopsan;

class DefaultLibraryXMLTest : public QObject
{
    Q_OBJECT

public:
    DefaultLibraryXMLTest();

private Q_SLOTS:
    void initTestCase();
    void testIconPaths();
    void testPortNames();
    void testSourceCodeLink();

private:
    void recurseCollectXMLFiles(const QDir &rDir);
    void printCoreMessages()
    {
        while (mHopsanCore.getCoreMessageHandler()->getNumWaitingMessages() > 0) {
            HString message, type, tag;
            mHopsanCore.getCoreMessageHandler()->getMessage(message, type, tag);
            std::cout << type.c_str() << ": " << message.c_str() << std::endl;
        }
    }

    QFileInfoList mAllXMLFiles;
    HopsanEssentials mHopsanCore;
};

typedef QMap<QString, QString> IconNameMapT;

QDomElement loadXMLFileToDOM(const QFileInfo &rXMLFileInfo, QDomDocument &rDoc)
{
    QFile file(rXMLFileInfo.absoluteFilePath());
    if (!file.open(QIODevice::ReadOnly))
    {
        return QDomElement();
    }

    rDoc.setContent(&file);
    file.close();

    QDomElement root = rDoc.documentElement();
    if (root.tagName() == "hopsanobjectappearance")
    {
        return root;
    }
    else
    {
        return QDomElement();
    }
}

IconNameMapT extractIconPathsFromMO(const QDomElement dom)
{
    IconNameMapT map;
    QDomElement icon = dom.firstChildElement("icons").firstChildElement("icon");
    while (!icon.isNull())
    {
        map.insert(icon.attribute("type"), icon.attribute("path"));
        icon = icon.nextSiblingElement("icon");
    }
    return map;
}

QStringList extractPortNamesFromMO(const QDomElement dom)
{
    QStringList names;
    QDomElement port = dom.firstChildElement("ports").firstChildElement("port");
    while (!port.isNull())
    {
        names.append(port.attribute("name"));
        port = port.nextSiblingElement("port");
    }
    return names;
}

QString extractTypeNameFromMO(const QDomElement dom)
{
    return dom.attribute("typename");
}

QString extractSourceCodeLinkFromMO(const QDomElement dom)
{
    return dom.attribute("sourcecode");
}

DefaultLibraryXMLTest::DefaultLibraryXMLTest()
{
}

void DefaultLibraryXMLTest::initTestCase()
{
    mAllXMLFiles.clear();

    // Loop through all subdirs, to find all XML files, and store them in a list
    QDir libRoot(DEFAULT_LIBRARY_ROOT);
    QVERIFY2(libRoot.exists(), qPrintable(QString("Libroot: %1 could not be found!").arg(libRoot.absolutePath())));
    recurseCollectXMLFiles(libRoot);

    if (!defaultLibraryFilePath.empty())
    {
        bool loadOK = mHopsanCore.loadExternalComponentLib(defaultLibraryFilePath.c_str());
        if (!loadOK) {
            printCoreMessages();
        }
        QVERIFY2(loadOK, qPrintable(QString("Could not load the default component library file: %1").arg(defaultLibraryFilePath.c_str())));
    }
}

void DefaultLibraryXMLTest::testIconPaths()
{
    bool isOK = true;
    for (int i=0; i<mAllXMLFiles.size(); ++i)
    {
        QDomDocument doc;
        QDomElement mo = loadXMLFileToDOM(mAllXMLFiles[i].absoluteFilePath(),doc).firstChildElement("modelobject");
        while(!mo.isNull())
        {
            IconNameMapT map = extractIconPathsFromMO(mo);
            IconNameMapT::iterator it;
            for (it=map.begin(); it!=map.end(); ++it)
            {
                QString relPath = it.value();
                QFileInfo iconFile(mAllXMLFiles[i].absolutePath()+"/"+relPath);
                if (!iconFile.exists() && !relPath.startsWith(":graphics/"))
                {
                    QWARN(QString("The icon file %1 could not be found, linked from xml file: %2").arg(iconFile.absoluteFilePath()).arg(mAllXMLFiles[i].absoluteFilePath()).toStdString().c_str());
                    isOK = false;
                }
            }
            mo = mo.nextSiblingElement("modelobject");
        }
    }
    QVERIFY2(isOK, "There were at least one icon not found!");
}

void DefaultLibraryXMLTest::testPortNames()
{
    bool isOK = true;
    for (int i=0; i<mAllXMLFiles.size(); ++i)
    {
        QDomDocument doc;
        QDomElement mo = loadXMLFileToDOM(mAllXMLFiles[i].absoluteFilePath(),doc).firstChildElement("modelobject");
        while(!mo.isNull())
        {
            QString typeName = extractTypeNameFromMO(mo);
            QStringList portNames = extractPortNamesFromMO(mo);

            Component* pComponent = mHopsanCore.createComponent(typeName.toStdString().c_str());
            if (pComponent)
            {
                for (int p=0; p<portNames.size(); ++p )
                {
                    Port *pPort = pComponent->getPort(portNames[p].toStdString().c_str());
                    if (pPort == 0)
                    {
                        isOK = false;
                        QWARN(QString("Component: %1    Port: %2    exist in XML but not in CODE!").arg(typeName).arg(portNames[p]).toStdString().c_str());
                    }
                }
                mHopsanCore.removeComponent(pComponent);
            }
            else
            {
                QWARN(QString("Component: %1 exist in XML but not in core!").arg(typeName).toStdString().c_str());
            }
            mo = mo.nextSiblingElement("modelobject");
        }
    }
    QVERIFY2(isOK, "There were at least one port name mismatch in your XML and CODE");
}

void DefaultLibraryXMLTest::testSourceCodeLink()
{
    bool isOK = true;
    for (int i=0; i<mAllXMLFiles.size(); ++i)
    {
        QDomDocument doc;
        QDomElement mo = loadXMLFileToDOM(mAllXMLFiles[i].absoluteFilePath(),doc).firstChildElement("modelobject");
        while(!mo.isNull())
        {
            QString typeName = extractTypeNameFromMO(mo);
            QString sourceCode = extractSourceCodeLinkFromMO(mo);

            if (sourceCode.isEmpty())
            {
                QWARN(QString("SourceCode attribute not set for component %1!").arg(typeName).toStdString().c_str());
                //isOK = false;

                // ===================================
                // Add the code automatically
//                QString codefile = typeName+".hpp";
//                mo.setAttribute("sourcecode", codefile);
//                QFile f(mAllXMLFiles[i].absoluteFilePath());
//                if (f.open(QIODevice::WriteOnly | QIODevice::Text))
//                {
//                    QTextStream out(&f);
//                    QDomDocument doc = mo.ownerDocument();
//                    doc.save(out,4);
//                }
//                f.close();
                // ===================================
            }
            else
            {
                QFileInfo sourceFile(mAllXMLFiles[i].absolutePath()+"/"+sourceCode);
                if(!sourceFile.exists())
                {
                    QWARN(QString("SourceCode file: %1 for component %2 in file %3 is missing!").arg(sourceFile.absoluteFilePath()).arg(typeName).arg(mAllXMLFiles[i].canonicalFilePath()).toStdString().c_str());
                    isOK = false;
                }
            }
            mo = mo.nextSiblingElement("modelobject");
        }
    }
    QVERIFY2(isOK, "There were at least one sourcecode link not working!");
}

void DefaultLibraryXMLTest::recurseCollectXMLFiles(const QDir &rDir)
{
    QFileInfoList contents = rDir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot, QDir::DirsLast);
    for (int i=0;i<contents.size();++i)
    {
        if (contents[i].isFile() && contents[i].suffix().toLower() == "xml")
        {
            mAllXMLFiles.append(contents[i]);
        }
        else if (contents[i].isDir())
        {
            recurseCollectXMLFiles(contents[i].absoluteFilePath());
        }
    }
}

QTEST_APPLESS_MAIN(DefaultLibraryXMLTest)

#include "tst_defaultlibraryxmltest.moc"
<commit_msg>Warn for missing component descriptions in DefaultLibraryXMLTest<commit_after>/*-----------------------------------------------------------------------------

 Copyright 2017 Hopsan Group

    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.

 The full license is available in the file LICENSE.
 For details about the 'Hopsan Group' or information about Authors and
 Contributors see the HOPSANGROUP and AUTHORS files that are located in
 the Hopsan source code root directory.

-----------------------------------------------------------------------------*/

// $Id$

#include <QString>
#include <QtTest>
#include <QDir>
#include <QtXml>
#include <QFileInfo>
#include <iostream>
#include "HopsanEssentials.h"
#include "CoreUtilities/HopsanCoreMessageHandler.h"
#include "HopsanCoreVersion.h"

#ifndef DEFAULT_LIBRARY_ROOT
#define DEFAULT_LIBRARY_ROOT "../componentLibraries/defaultLibrary"
#endif

#ifndef HOPSAN_INTERNALDEFAULTCOMPONENTS
#define DEFAULTLIBFILE SHAREDLIB_PREFIX "defaultcomponentlibrary" HOPSAN_DEBUG_POSTFIX "." SHAREDLIB_SUFFIX
const std::string defaultLibraryFilePath = DEFAULT_LIBRARY_ROOT "/" DEFAULTLIBFILE;
#else
const std::string defaultLibraryFilePath = "";
#endif

using namespace hopsan;

class DefaultLibraryXMLTest : public QObject
{
    Q_OBJECT

public:
    DefaultLibraryXMLTest();

private Q_SLOTS:
    void initTestCase();
    void testIconPaths();
    void testPortNames();
    void testSourceCodeLink();
    void testDescriptionExists();

private:
    void recurseCollectXMLFiles(const QDir &rDir);
    void printCoreMessages()
    {
        while (mHopsanCore.getCoreMessageHandler()->getNumWaitingMessages() > 0) {
            HString message, type, tag;
            mHopsanCore.getCoreMessageHandler()->getMessage(message, type, tag);
            std::cout << type.c_str() << ": " << message.c_str() << std::endl;
        }
    }

    QFileInfoList mAllXMLFiles;
    HopsanEssentials mHopsanCore;
};

typedef QMap<QString, QString> IconNameMapT;

QDomElement loadXMLFileToDOM(const QFileInfo &rXMLFileInfo, QDomDocument &rDoc)
{
    QFile file(rXMLFileInfo.absoluteFilePath());
    if (!file.open(QIODevice::ReadOnly))
    {
        return QDomElement();
    }

    rDoc.setContent(&file);
    file.close();

    QDomElement root = rDoc.documentElement();
    if (root.tagName() == "hopsanobjectappearance")
    {
        return root;
    }
    else
    {
        return QDomElement();
    }
}

IconNameMapT extractIconPathsFromMO(const QDomElement dom)
{
    IconNameMapT map;
    QDomElement icon = dom.firstChildElement("icons").firstChildElement("icon");
    while (!icon.isNull())
    {
        map.insert(icon.attribute("type"), icon.attribute("path"));
        icon = icon.nextSiblingElement("icon");
    }
    return map;
}

QStringList extractPortNamesFromMO(const QDomElement dom)
{
    QStringList names;
    QDomElement port = dom.firstChildElement("ports").firstChildElement("port");
    while (!port.isNull())
    {
        names.append(port.attribute("name"));
        port = port.nextSiblingElement("port");
    }
    return names;
}

QString extractTypeNameFromMO(const QDomElement dom)
{
    return dom.attribute("typename");
}

QString extractSourceCodeLinkFromMO(const QDomElement dom)
{
    return dom.attribute("sourcecode");
}

DefaultLibraryXMLTest::DefaultLibraryXMLTest()
{
}

void DefaultLibraryXMLTest::initTestCase()
{
    mAllXMLFiles.clear();

    // Loop through all subdirs, to find all XML files, and store them in a list
    QDir libRoot(DEFAULT_LIBRARY_ROOT);
    QVERIFY2(libRoot.exists(), qPrintable(QString("Libroot: %1 could not be found!").arg(libRoot.absolutePath())));
    recurseCollectXMLFiles(libRoot);

    if (!defaultLibraryFilePath.empty())
    {
        bool loadOK = mHopsanCore.loadExternalComponentLib(defaultLibraryFilePath.c_str());
        if (!loadOK) {
            printCoreMessages();
        }
        QVERIFY2(loadOK, qPrintable(QString("Could not load the default component library file: %1").arg(defaultLibraryFilePath.c_str())));
    }
}

void DefaultLibraryXMLTest::testIconPaths()
{
    bool isOK = true;
    for (int i=0; i<mAllXMLFiles.size(); ++i)
    {
        QDomDocument doc;
        QDomElement mo = loadXMLFileToDOM(mAllXMLFiles[i].absoluteFilePath(),doc).firstChildElement("modelobject");
        while(!mo.isNull())
        {
            IconNameMapT map = extractIconPathsFromMO(mo);
            IconNameMapT::iterator it;
            for (it=map.begin(); it!=map.end(); ++it)
            {
                QString relPath = it.value();
                QFileInfo iconFile(mAllXMLFiles[i].absolutePath()+"/"+relPath);
                if (!iconFile.exists() && !relPath.startsWith(":graphics/"))
                {
                    QWARN(QString("The icon file %1 could not be found, linked from xml file: %2").arg(iconFile.absoluteFilePath()).arg(mAllXMLFiles[i].absoluteFilePath()).toStdString().c_str());
                    isOK = false;
                }
            }
            mo = mo.nextSiblingElement("modelobject");
        }
    }
    QVERIFY2(isOK, "There were at least one icon not found!");
}

void DefaultLibraryXMLTest::testPortNames()
{
    bool isOK = true;
    for (int i=0; i<mAllXMLFiles.size(); ++i)
    {
        QDomDocument doc;
        QDomElement mo = loadXMLFileToDOM(mAllXMLFiles[i].absoluteFilePath(),doc).firstChildElement("modelobject");
        while(!mo.isNull())
        {
            QString typeName = extractTypeNameFromMO(mo);
            QStringList portNames = extractPortNamesFromMO(mo);

            Component* pComponent = mHopsanCore.createComponent(typeName.toStdString().c_str());
            if (pComponent)
            {
                for (int p=0; p<portNames.size(); ++p )
                {
                    Port *pPort = pComponent->getPort(portNames[p].toStdString().c_str());
                    if (pPort == 0)
                    {
                        isOK = false;
                        QWARN(QString("Component: %1    Port: %2    exist in XML but not in CODE!").arg(typeName).arg(portNames[p]).toStdString().c_str());
                    }
                }
                mHopsanCore.removeComponent(pComponent);
            }
            else
            {
                QWARN(QString("Component: %1 exist in XML but not in core!").arg(typeName).toStdString().c_str());
            }
            mo = mo.nextSiblingElement("modelobject");
        }
    }
    QVERIFY2(isOK, "There were at least one port name mismatch in your XML and CODE");
}

void DefaultLibraryXMLTest::testSourceCodeLink()
{
    bool isOK = true;
    for (int i=0; i<mAllXMLFiles.size(); ++i)
    {
        QDomDocument doc;
        QDomElement mo = loadXMLFileToDOM(mAllXMLFiles[i].absoluteFilePath(),doc).firstChildElement("modelobject");
        while(!mo.isNull())
        {
            QString typeName = extractTypeNameFromMO(mo);
            QString sourceCode = extractSourceCodeLinkFromMO(mo);

            if (sourceCode.isEmpty())
            {
                QWARN(QString("SourceCode attribute not set for component %1!").arg(typeName).toStdString().c_str());
                //isOK = false;

                // ===================================
                // Add the code automatically
//                QString codefile = typeName+".hpp";
//                mo.setAttribute("sourcecode", codefile);
//                QFile f(mAllXMLFiles[i].absoluteFilePath());
//                if (f.open(QIODevice::WriteOnly | QIODevice::Text))
//                {
//                    QTextStream out(&f);
//                    QDomDocument doc = mo.ownerDocument();
//                    doc.save(out,4);
//                }
//                f.close();
                // ===================================
            }
            else
            {
                QFileInfo sourceFile(mAllXMLFiles[i].absolutePath()+"/"+sourceCode);
                if(!sourceFile.exists())
                {
                    QWARN(QString("SourceCode file: %1 for component %2 in file %3 is missing!").arg(sourceFile.absoluteFilePath()).arg(typeName).arg(mAllXMLFiles[i].canonicalFilePath()).toStdString().c_str());
                    isOK = false;
                }
            }
            mo = mo.nextSiblingElement("modelobject");
        }
    }
    QVERIFY2(isOK, "There were at least one sourcecode link not working!");
}

void DefaultLibraryXMLTest::testDescriptionExists()
{
    bool isOK = true;
    for (int i=0; i<mAllXMLFiles.size(); ++i)
    {
        QDomDocument doc;
        QDomElement mo = loadXMLFileToDOM(mAllXMLFiles[i].absoluteFilePath(),doc).firstChildElement("modelobject");
        while(!mo.isNull())
        {
            QString typeName = extractTypeNameFromMO(mo);

            if(mo.firstChildElement("help").isNull()) {
                QWARN(QString("No description available for component %1").arg(typeName).toStdString().c_str());
            }
            else {
                QDomElement mdElement = mo.firstChildElement("help").firstChildElement("md");
                if(!mdElement.isNull()) {
                    QFileInfo mdFile(mAllXMLFiles[i].absolutePath()+"/"+mdElement.text());
                    if(!mdFile.exists())
                    {
                        QWARN(QString("Description file: %1 for component %2 in file %3 is missing!").arg(mdFile.absoluteFilePath()).arg(typeName).arg(mAllXMLFiles[i].canonicalFilePath()).toStdString().c_str());
                        isOK = false;
                    }
                }
            }
            mo = mo.nextSiblingElement("modelobject");
        }
    }
    QVERIFY2(isOK, "There were at least one description file link not working.");
}

void DefaultLibraryXMLTest::recurseCollectXMLFiles(const QDir &rDir)
{
    QFileInfoList contents = rDir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot, QDir::DirsLast);
    for (int i=0;i<contents.size();++i)
    {
        if (contents[i].isFile() && contents[i].suffix().toLower() == "xml")
        {
            mAllXMLFiles.append(contents[i]);
        }
        else if (contents[i].isDir())
        {
            recurseCollectXMLFiles(contents[i].absoluteFilePath());
        }
    }
}

QTEST_APPLESS_MAIN(DefaultLibraryXMLTest)

#include "tst_defaultlibraryxmltest.moc"
<|endoftext|>


<commit_before>/*******************************************************************************
 * tests/common/fast_string_test.cpp
 *
 * Part of Project Thrill.
 *
 * Copyright (C) 2015 Alexander Noe <aleexnoe@gmail.com>
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#include <gtest/gtest.h>
#include <thrill/common/fast_string.hpp>
#include <thrill/common/logger.hpp>

#include <string>

using thrill::common::FastString;

TEST(FastStringTest, ConstructEmpty) {
	FastString empty;
	ASSERT_EQ(empty.Size(), 0);
}

TEST(FastStringTest, AssignAndCompare) {

	std::string input = "This is a string which does things and is our input.";
	std::string input2 = "is a string1";

	FastString other_str;
	FastString fast_str = FastString::Ref(&input[5], 11); //"is a string"
	ASSERT_EQ(fast_str.Size(), 11);

	std::string cmp = "is a string";
	ASSERT_TRUE(fast_str == cmp);

	std::string different = "is another string";
	ASSERT_FALSE(fast_str == different);

	std::string subset = "is a strin";
	ASSERT_FALSE(fast_str == subset);

	other_str.Ref(&input[6], 11); //"s a string "
	ASSERT_FALSE(fast_str == other_str);
	ASSERT_TRUE(fast_str != other_str);
	FastString equal_str = FastString::Ref(&input2[0], 11); //"is a string"
	ASSERT_TRUE(fast_str == equal_str);
	ASSERT_FALSE(fast_str != equal_str);
}

TEST(FastStringTest, CopyFastString) {

	FastString str;
	{
		std::string input = "input string";
		FastString str2 = FastString::Ref(&input[0], 12);
		str = str2;
		std::string().swap(input);
	}

	ASSERT_TRUE(str == "input string");
	ASSERT_EQ(str.Size(), 12);
}

TEST(FastStringTest, MoveFastString) {
	FastString str;
	std::string input = "input string";
	FastString str2 = FastString::Ref(&input[0], 12);
	str = std::move(str2);
	std::string().swap(input);
	ASSERT_TRUE(str == "input string");
	ASSERT_EQ(str.Size(), 12);
}

/******************************************************************************/
<commit_msg>add copies to faststringtest<commit_after>/*******************************************************************************
 * tests/common/fast_string_test.cpp
 *
 * Part of Project Thrill.
 *
 * Copyright (C) 2015 Alexander Noe <aleexnoe@gmail.com>
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#include <gtest/gtest.h>
#include <thrill/common/fast_string.hpp>
#include <thrill/common/logger.hpp>

#include <string>

using thrill::common::FastString;

TEST(FastStringTest, ConstructEmpty) {
	FastString empty;
	ASSERT_EQ(empty.Size(), 0);
}

TEST(FastStringTest, AssignAndCompare) {

	std::string input = "This is a string which does things and is our input.";
	std::string input2 = "is a string1";

	FastString other_str;
	FastString fast_str = FastString::Ref(&input[5], 11); //"is a string"
	ASSERT_EQ(fast_str.Size(), 11);

	std::string cmp = "is a string";
	ASSERT_TRUE(fast_str == cmp);

	std::string different = "is another string";
	ASSERT_FALSE(fast_str == different);

	std::string subset = "is a strin";
	ASSERT_FALSE(fast_str == subset);

	other_str.Ref(&input[6], 11); //"s a string "
	ASSERT_FALSE(fast_str == other_str);
	ASSERT_TRUE(fast_str != other_str);
	FastString equal_str = FastString::Ref(&input2[0], 11); //"is a string"
	ASSERT_TRUE(fast_str == equal_str);
	ASSERT_FALSE(fast_str != equal_str);
}

TEST(FastStringTest, CopyFastString) {

	FastString str;
	{
		std::string input = "input string";
		FastString str2 = FastString::Ref(&input[0], 12);
		str = str2;
		FastString str3 = FastString::Copy(str2.Start(), str2.Size());
		std::string().swap(input);
		ASSERT_TRUE(str3 == "input string");
	}

	ASSERT_TRUE(str == "input string");
	ASSERT_EQ(str.Size(), 12);
}

TEST(FastStringTest, MoveFastString) {
	FastString str;
	std::string input = "input string";
	FastString str2 = FastString::Copy(&input[0], 12);
	str = std::move(str2);
	std::string().swap(input);
	ASSERT_TRUE(str == "input string");
	ASSERT_EQ(str.Size(), 12);
}

/******************************************************************************/
<|endoftext|>


<commit_before>
#include <iostream>
#include <set>
/* This file includes the main function */

//#include <boost/program_options.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

#include <GPUManager.hpp>
#include <OptiXRenderView.hpp>
#include <ImageSaverView.hpp>
#include <ParseJSONController.hpp>

int main(int argc, char ** argv)
{
    std::string json_file;
    std::string img_file;

#if 0
    // Setup program options
    boost::program_options::options_description desc("Allowed options");
    desc.add_options()
        ("help,h","display this text")
        ("jsonfile,j",boost::program_options::value<std::string>(&json_file)->required(),"path to the json file describing the scene to render")
        ("imgfile,i",boost::program_options::value<std::string>(&img_file),"path to save the rendered png file")
    ;

    // Parse program options
    boost::program_options::variables_map vm;
    boost::program_options::store(boost::program_options::parse_command_line(argc,argv,desc), vm);

    if (vm.count("help")) {
        std::cout << desc << std::endl;
        return 1;
    }

    try {
        boost::program_options::notify(vm);
    } catch (std::exception & e) {
        std::cerr << "Program Options Parsing Error: " << e.what() << std::endl;
        return -1;
    }
#else
	if (argc<2)
	{
		std::cout<<"Usage: "<<argv[0]<<" json_file"<<std::endl;
		std::cout<<"Where json_file is json parameter file that describing the scene (required)"<<std::endl;

	}
	else
	{
		json_file = argv[1];
	}
	if (argc>2)
	{
		img_file = argv[2];
	}
	std::cout<<"Got command line arguments json_file = "<<json_file<<std::endl;
#endif

    // Create a model
    grt::Model model;

	// Setup optix renderer
	grt::OptiXRenderView optiXRenderView(argc, argv);
	model.registerObserver(&optiXRenderView);

    // Setup Image Saver
    std::auto_ptr<grt::ImageSaverView> imagefileview( (img_file.empty()) ? 0 : new grt::ImageSaverView(img_file) );

    // Register views with Model
    //model.registerObserver(&gman);
    if (imagefileview.get()) model.registerObserver(imagefileview.get());

    try {
        grt::ParseJSONController jsonParser(model,json_file);
        jsonParser.execute(); // notifies model observers
    } catch (std::exception & e) {
        std::cerr << "Unable to ParseJSON: " << e.what() << std::endl;
        return -2;
    }

    // Cleanup

    // Register views with Model
    //model.unregisterObserver(&gman);
    if (imagefileview.get()) model.unregisterObserver(imagefileview.get());

    return 0;
}
<commit_msg>small change relating to last<commit_after>
#include <iostream>
#include <set>
/* This file includes the main function */

//#include <boost/program_options.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

#include <GPUManager.hpp>
#include <OptiXRenderView.hpp>
#include <ImageSaverView.hpp>
#include <ParseJSONController.hpp>

int main(int argc, char ** argv)
{
    std::string json_file;
    std::string img_file;

#if 0
    // Setup program options
    boost::program_options::options_description desc("Allowed options");
    desc.add_options()
        ("help,h","display this text")
        ("jsonfile,j",boost::program_options::value<std::string>(&json_file)->required(),"path to the json file describing the scene to render")
        ("imgfile,i",boost::program_options::value<std::string>(&img_file),"path to save the rendered png file")
    ;

    // Parse program options
    boost::program_options::variables_map vm;
    boost::program_options::store(boost::program_options::parse_command_line(argc,argv,desc), vm);

    if (vm.count("help")) {
        std::cout << desc << std::endl;
        return 1;
    }

    try {
        boost::program_options::notify(vm);
    } catch (std::exception & e) {
        std::cerr << "Program Options Parsing Error: " << e.what() << std::endl;
        return -1;
    }
#else
	if (argc<2)
	{
		std::cout<<"Usage: "<<argv[0]<<" json_file"<<std::endl;
		std::cout<<"Where json_file is json parameter file that describing the scene (required)"<<std::endl;

	}
	else
	{
		json_file = argv[1];
	}
	/*
	if (argc>2)
	{
		img_file = argv[2];
	} */
	std::cout<<"Got command line arguments json_file = "<<json_file<<std::endl;
#endif

    // Create a model
    grt::Model model;

	// Setup optix renderer
	grt::OptiXRenderView optiXRenderView(argc, argv);
	model.registerObserver(&optiXRenderView);

    // Setup Image Saver
    std::auto_ptr<grt::ImageSaverView> imagefileview( (img_file.empty()) ? 0 : new grt::ImageSaverView(img_file) );

    // Register views with Model
    //model.registerObserver(&gman);
    if (imagefileview.get()) model.registerObserver(imagefileview.get());

    try {
        grt::ParseJSONController jsonParser(model,json_file);
        jsonParser.execute(); // notifies model observers
    } catch (std::exception & e) {
        std::cerr << "Unable to ParseJSON: " << e.what() << std::endl;
        return -2;
    }

    // Cleanup

    // Register views with Model
    //model.unregisterObserver(&gman);
    if (imagefileview.get()) model.unregisterObserver(imagefileview.get());

    return 0;
}
<|endoftext|>


<commit_before><commit_msg>Temporarily rolling back to Mac OS X version<commit_after><|endoftext|>


<commit_before>/*  This file is part of the KDE project
    Copyright (C) 2006 Matthias Kretz <kretz@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

*/

#include "audiooutput.h"
#include <QVector>
#include <kdebug.h>

#include <config.h>
#ifdef HAVE_SYS_SOUNDCARD_H
#include <sys/soundcard.h>
#endif
#include <sys/ioctl.h>
#include <iostream>

namespace Phonon
{
namespace Fake
{
AudioOutput::AudioOutput( QObject* parent )
	: AbstractAudioOutput( parent )
	, m_device( 1 )
	, m_dsp( "/dev/dsp" )
{
}

AudioOutput::~AudioOutput()
{
}

QString AudioOutput::name() const
{
	return m_name;
}

float AudioOutput::volume() const
{
	return m_volume;
}

int AudioOutput::outputDevice() const
{
	return m_device;
}

void AudioOutput::setName( const QString& newName )
{
	m_name = newName;
}

void AudioOutput::setVolume( float newVolume )
{
	m_volume = newVolume;
	emit volumeChanged( m_volume );
}

void AudioOutput::setOutputDevice( int newDevice )
{
	Q_ASSERT( newDevice >= 1 );
	Q_ASSERT( newDevice <= 2 );
	m_device = newDevice;
}

void AudioOutput::processBuffer( const QVector<float>& buffer )
{
	//static QFile indump( "indump" );
	//if( !indump.isOpen() )
		//indump.open( QIODevice::WriteOnly );
	//static QFile outdump( "outdump" );
	//if( !outdump.isOpen() )
		//outdump.open( QIODevice::WriteOnly );
	openDevice();
	if( !m_dsp.isOpen() )
		return;

	// we dump the data in /dev/dsp
	qint16* pcm = new qint16[ 2*buffer.size() ]; // 2* for stereo
	char* towrite = reinterpret_cast<char*>( pcm );
	int converted;
	for( int i = 0; i < buffer.size(); ++i )
	{
		//indump.write( QByteArray::number( buffer[ i ] ) + "\n" );
		converted = static_cast<qint16>( m_volume * buffer[ i ] * static_cast<float>( 0x7FFF ) );
		//outdump.write( QByteArray::number( converted ) + "\n" );
		*pcm++ = converted;
		*pcm++ = converted;
	}
	int size = sizeof( qint16 ) * 2 * buffer.size();
	int written;
	while( size > 0 )
	{
		written = m_dsp.write( towrite, size );
		if (written < 0) {
			if (errno == EINTR)
				continue;
			break;
		}
		size = size - written;
		if( size > 0 )
		{
			towrite += written;
			kWarning() << "only " << written << " bytes written to /dev/dsp" << endl;
		}
	}

	pcm -= 2*buffer.size();
	delete[] pcm;
}

void AudioOutput::openDevice()
{
	if( m_dsp.isOpen() )
		return;

#ifdef HAVE_SYS_SOUNDCARD_H
	if( !m_dsp.open( QIODevice::WriteOnly ) )
		kWarning() << "couldn't open /dev/dsp for writing" << endl;
	else
	{
		int fd = m_dsp.handle();
		int format = AFMT_S16_LE;
		int stereo = 1;
		int samplingRate = 44100;
		ioctl( fd, SNDCTL_DSP_SETFMT, &format );
		ioctl( fd, SNDCTL_DSP_STEREO, &stereo );
		ioctl( fd, SNDCTL_DSP_SPEED, &samplingRate );
	}
#endif
}

void AudioOutput::closeDevice()
{
	m_dsp.close();
}

}} //namespace Phonon::Fake

#include "audiooutput.moc"
// vim: sw=4 ts=4 noet
<commit_msg>compile again<commit_after>/*  This file is part of the KDE project
    Copyright (C) 2006 Matthias Kretz <kretz@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

*/

#include "audiooutput.h"
#include <QVector>
#include <kdebug.h>

#include <config.h>
#ifdef HAVE_SYS_SOUNDCARD_H
#include <sys/soundcard.h>
#endif
#include <sys/ioctl.h>
#include <iostream>

namespace Phonon
{
namespace Fake
{
AudioOutput::AudioOutput( QObject* parent )
	: AbstractAudioOutput( parent )
	, m_device( 1 )
	, m_dsp( "/dev/dsp" )
{
}

AudioOutput::~AudioOutput()
{
}

QString AudioOutput::name() const
{
	return m_name;
}

float AudioOutput::volume() const
{
	return m_volume;
}

int AudioOutput::outputDevice() const
{
	return m_device;
}

void AudioOutput::setName( const QString& newName )
{
	m_name = newName;
}

void AudioOutput::setVolume( float newVolume )
{
	m_volume = newVolume;
	emit volumeChanged( m_volume );
}

void AudioOutput::setOutputDevice( int newDevice )
{
	Q_ASSERT( newDevice >= 1 );
	Q_ASSERT( newDevice <= 2 );
	m_device = newDevice;
}

void AudioOutput::processBuffer( const QVector<float>& buffer )
{
	//static QFile indump( "indump" );
	//if( !indump.isOpen() )
		//indump.open( QIODevice::WriteOnly );
	//static QFile outdump( "outdump" );
	//if( !outdump.isOpen() )
		//outdump.open( QIODevice::WriteOnly );
	openDevice();
	if( !m_dsp.isOpen() )
		return;

	// we dump the data in /dev/dsp
	qint16* pcm = new qint16[ 2*buffer.size() ]; // 2* for stereo
	char* towrite = reinterpret_cast<char*>( pcm );
	int converted;
	for( int i = 0; i < buffer.size(); ++i )
	{
		//indump.write( QByteArray::number( buffer[ i ] ) + "\n" );
		converted = static_cast<qint16>( m_volume * buffer[ i ] * static_cast<float>( 0x7FFF ) );
		//outdump.write( QByteArray::number( converted ) + "\n" );
		*pcm++ = converted;
		*pcm++ = converted;
	}
	int size = sizeof( qint16 ) * 2 * buffer.size();
	int written;
	while( size > 0 )
	{
		written = m_dsp.write( towrite, size );
		// QFSFileEngine loops until errno != EINTR
		if( written < 0 )
			break;
		size = size - written;
		if( size > 0 )
		{
			towrite += written;
			kWarning() << "only " << written << " bytes written to /dev/dsp" << endl;
		}
	}

	pcm -= 2*buffer.size();
	delete[] pcm;
}

void AudioOutput::openDevice()
{
	if( m_dsp.isOpen() )
		return;

#ifdef HAVE_SYS_SOUNDCARD_H
	if( !m_dsp.open( QIODevice::WriteOnly ) )
		kWarning() << "couldn't open /dev/dsp for writing" << endl;
	else
	{
		int fd = m_dsp.handle();
		int format = AFMT_S16_LE;
		int stereo = 1;
		int samplingRate = 44100;
		ioctl( fd, SNDCTL_DSP_SETFMT, &format );
		ioctl( fd, SNDCTL_DSP_STEREO, &stereo );
		ioctl( fd, SNDCTL_DSP_SPEED, &samplingRate );
	}
#endif
}

void AudioOutput::closeDevice()
{
	m_dsp.close();
}

}} //namespace Phonon::Fake

#include "audiooutput.moc"
// vim: sw=4 ts=4 noet
<|endoftext|>


<commit_before>/*
 * Copyright 2016 neurodata (http://neurodata.io/)
 * Written by Disa Mhembere (disa@jhu.edu)
 *
 * This file is part of k-par-means
 *
 * 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 CURRENT_KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef __KNORI_HPP__
#define __KNORI_HPP__

#include <limits>
#include <numa.h>

#include "signal.h"
#include "io.hpp"
#include "kmeans.hpp"

#include "kmeans_coordinator.hpp"
#include "kmeans_task_coordinator.hpp"
#include "util.hpp"

namespace kpmeans { namespace base {
kpmbase::kmeans_t kmeans(const std::string datafn, const size_t nrow,
        const size_t ncol, const unsigned k,
        size_t max_iters=std::numeric_limits<size_t>::max(),
        unsigned nnodes=numa_num_task_nodes(), unsigned nthread=kpmbase::get_num_omp_threads(),
        double* p_centers=NULL, std::string init="kmeanspp",
        double tolerance=-1, std::string dist_type="eucl",
        std::string centersfn = "", bool omp=false) {

    kpmbase::kmeans_t ret;

    if (kpmbase::is_file_exist(centersfn.c_str())) {
        p_centers = new double [k*ncol];
        kpmbase::bin_io<double> br2(centersfn, k, ncol);
        br2.read(p_centers);
        printf("Read centers!\n");
    }

    if (omp) {
        //printf("Calling FULL kmeans ..\n");
        kpmeans::kmeans_coordinator::ptr kc =
            kpmeans::kmeans_coordinator::create(datafn,
                    nrow, ncol, k, max_iters, nnodes, nthread, p_centers,
                    init, tolerance, dist_type);
        ret = kc->run_kmeans();
    } else {
        //printf("Calling PRUNED kmeans ..\n");
        kpmprune::kmeans_task_coordinator::ptr kc =
            kpmprune::kmeans_task_coordinator::create(
                    datafn, nrow, ncol, k, max_iters, nnodes, nthread, p_centers,
                    init, tolerance, dist_type);
        ret = kc->run_kmeans();
    }

    ret.print();
    if (p_centers) { delete [] p_centers; }
    return ret;
}

} } // End namespace kpmeans::base
#endif
<commit_msg>binding: in-memory data & centroids hook<commit_after>/*
 * Copyright 2016 neurodata (http://neurodata.io/)
 * Written by Disa Mhembere (disa@jhu.edu)
 *
 * This file is part of k-par-means
 *
 * 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 CURRENT_KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef __KNORI_HPP__
#define __KNORI_HPP__

#include <limits>
#include <numa.h>

#include "signal.h"
#include "io.hpp"
#include "kmeans.hpp"

#include "kmeans_coordinator.hpp"
#include "kmeans_task_coordinator.hpp"
#include "util.hpp"

namespace {

}

namespace kpmeans { namespace base {
    // NOTE: It is the callers job to allocate/free data & p_centers

    kpmbase::kmeans_t kmeans(double* data, const size_t nrow,
            const size_t ncol, const unsigned k,
            size_t max_iters=std::numeric_limits<size_t>::max(),
            unsigned nnodes=numa_num_task_nodes(),
            unsigned nthread=kpmbase::get_num_omp_threads(),
            double* p_centers=NULL, std::string init="kmeanspp",
            double tolerance=-1, std::string dist_type="eucl",
            std::string centersfn = "", bool omp=false) {

        if (p_centers)
            init = "none";

        kpmbase::kmeans_t ret;

        if (omp) {
            printf("Calling FULL kmeans ..\n");
            kpmeans::kmeans_coordinator::ptr kc =
                kpmeans::kmeans_coordinator::create("",
                        nrow, ncol, k, max_iters, nnodes, nthread, p_centers,
                        init, tolerance, dist_type);
            ret = kc->run_kmeans(data);
        } else {
            printf("Calling PRUNED kmeans ..\n");
            kpmprune::kmeans_task_coordinator::ptr kc =
                kpmprune::kmeans_task_coordinator::create(
                        "", nrow, ncol, k, max_iters, nnodes,
                        nthread, p_centers,
                        init, tolerance, dist_type);
            ret = kc->run_kmeans(data);
        }

        return ret;
    }

kpmbase::kmeans_t kmeans(const std::string datafn, const size_t nrow,
        const size_t ncol, const unsigned k,
        size_t max_iters=std::numeric_limits<size_t>::max(),
        unsigned nnodes=numa_num_task_nodes(),
        unsigned nthread=kpmbase::get_num_omp_threads(),
        double* p_centers=NULL, std::string init="kmeanspp",
        double tolerance=-1, std::string dist_type="eucl",
        std::string centersfn = "", bool omp=false) {

    kpmbase::kmeans_t ret;

    if (kpmbase::is_file_exist(centersfn.c_str())) {
        p_centers = new double [k*ncol];
        kpmbase::bin_io<double> br2(centersfn, k, ncol);
        br2.read(p_centers);
        printf("Read centers!\n");
    }

    if (omp) {
        printf("calling full kmeans ..\n");
        kpmeans::kmeans_coordinator::ptr kc =
            kpmeans::kmeans_coordinator::create(datafn,
                    nrow, ncol, k, max_iters, nnodes, nthread, p_centers,
                    init, tolerance, dist_type);
        ret = kc->run_kmeans();
    } else {
        printf("calling pruned kmeans ..\n");
        kpmprune::kmeans_task_coordinator::ptr kc =
            kpmprune::kmeans_task_coordinator::create(
                    datafn, nrow, ncol, k, max_iters, nnodes, nthread, p_centers,
                    init, tolerance, dist_type);
        ret = kc->run_kmeans();
    }

    if (p_centers) { delete [] p_centers; }
    return ret;
}

} } // End namespace kpmeans::base
#endif
<|endoftext|>


<commit_before><commit_msg>fixed the conversion between animation values, and world values, animation now doesn't draw a triangle for the test 'circle'<commit_after><|endoftext|>


<commit_before><commit_msg>shift list<commit_after><|endoftext|>


<commit_before>#include "init.h"
#include "widgets/wizards/setupwizard.h"
#include "defines.h"
#include "widgets/stack/library.h"
#include "database.h"

#include <QApplication>
#include <QFile>
#include <QIcon>
#include <QTextStream>

#include <QCommandLineParser>
#include <QCommandLineOption>

#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>

#ifdef Q_OS_WIN
    #include "src/widgets/window/borderlesswindow.h"
#else
    #include "src/widgets/window/unixwindow.h"
#endif

int main(int argc, char* argv[])
{
    QCoreApplication::addLibraryPath("./");

    QApplication::setStyle("fusion");
    QApplication* application = new QApplication(argc, argv);
    application->setApplicationName("Horizon Launcher");

    QTranslator horizonTranslator;
    horizonTranslator.load("horizon_" + QLocale::system().name());
    application->installTranslator(&horizonTranslator);

    QDir configFolder(CONFIG_FOLDER);
    if (!configFolder.exists())
    {
        configFolder.cdUp();
        configFolder.mkdir("HorizonLauncher");
    }

    QDir imageDirectory(CONFIG_FOLDER + QDir::separator() + "image");
    if (!imageDirectory.exists())
    {
        imageDirectory.cdUp();
        imageDirectory.mkdir("image");
    }

    bool dbExists = QFile(QDir(CONFIG_FOLDER).filePath("horizon.db")).exists();

    if (!Library::db.init())
    {
        QMessageBox error;
        error.critical(0, QWidget::tr("Error!"), QWidget::tr("An error occurred while trying to load the database."));
        exit(EXIT_FAILURE);
    }

    QCommandLineParser parser;

    parser.setApplicationDescription("Horizon Launcher");
    parser.addHelpOption();

    QCommandLineOption noLaunchOption(QStringList() << "n" << "nolaunch",
                                  QWidget::tr("Don't launch Horizon's GUI -- exit after processing command-line arguments."));
    parser.addOption(noLaunchOption);

    QCommandLineOption jsonOption(QStringList() << "json",
                                  QWidget::tr("Output in JSON format instead of human-readable."));
    parser.addOption(jsonOption);

    QCommandLineOption listOption(QStringList() << "l" << "list",
                                  QWidget::tr("List all games in the Horizon database."));
    parser.addOption(listOption);

    parser.process(*application);

    if (parser.isSet(listOption))
    {
        QTextStream sout(stdout);

        if (parser.isSet(jsonOption))
        {
            QJsonArray gamesJSON;
            for (Game game : Library::db.getGames())
            {
                QJsonObject gameJSON;
                gameJSON["id"] = QString::number(game.id);
                gameJSON["name"] = game.gameName;
                gameJSON["directory"] = game.gameDirectory;
                gameJSON["executable"] = game.executablePath;
                gameJSON["arguments"] = game.arguments;
                gameJSON["drm"] = game.drm;

                gamesJSON.append(gameJSON);
            }

            QJsonDocument doc(gamesJSON);

            sout << doc.toJson(QJsonDocument::Compact) << "\r\n";
            sout.flush();
        }
        else
        {
            QList<Game> games = Library::db.getGames();
            int largestID = QString::number(games[0].id).length();
            int largestName = games[0].gameName.length();
            int largestDir = games[0].gameDirectory.length();
            int largestBin = games[0].executablePath.length();
            int largestArgs = games[0].arguments.length();
            int largestDRM = Database::getDRMString(games[0].drm).length();

            for (Game game : games)
            {
                int idLen = QString::number(game.id).length();
                int nameLen = game.gameName.length();
                int dirLen = game.gameDirectory.length();
                int binLen = game.executablePath.length();
                int argLen = game.arguments.length();
                int drmLen = Database::getDRMString(game.drm).length();

                if (idLen > largestID)
                {
                    largestID = idLen;
                }
                if (nameLen > largestName)
                {
                    largestName = nameLen;
                }
                if (dirLen > largestDir)
                {
                    largestDir = dirLen;
                }
                if (binLen > largestBin)
                {
                    largestBin = binLen;
                }
                if (argLen > largestArgs)
                {
                    largestArgs = argLen;
                }
                if (drmLen > largestDRM)
                {
                    largestDRM = drmLen;
                }
            }

            sout << QString("ID").leftJustified(largestID, ' ') + "\t" +
                    QString("NAME").leftJustified(largestName, ' ') + "\t" +
                    QString("DIR").leftJustified(largestDir, ' ') + "\t" +
                    QString("BIN").leftJustified(largestBin, ' ') + "\t" +
                    QString("ARGS").leftJustified(largestArgs, ' ') + "\t" +
                    QString("DRM").leftJustified(largestDRM, ' ') + "\r\n";
            for (Game game : games)
            {
                QJsonObject gameJSON;
                sout << QString::number(game.id).leftJustified(largestID, ' ') + "\t" +
                        QString(game.gameName).leftJustified(largestName, ' ') + "\t" +
                        QString(game.gameDirectory).leftJustified(largestDir, ' ') + "\t" +
                        QString(game.executablePath).leftJustified(largestBin, ' ') + "\t" +
                        QString(game.arguments).leftJustified(largestArgs, ' ') + "\t" +
                        Database::getDRMString(game.drm).leftJustified(largestDRM, ' ') + "\r\n";
            }
            sout.flush();
        }
    }

    SetupWizard* wiz = new SetupWizard();

    #ifndef Q_OS_WIN
        // dynamic loading of the icon under Linux/UNIX
        application->setWindowIcon(QIcon(":/res/icon/Horizon.ico"));
    #endif

    // Global stylesheet
    QFile stylesheet(":/Styles/horizon.css");
    if (stylesheet.open(QFile::ReadOnly))
    {
        QString styleSheet = stylesheet.readAll();
        application->setStyleSheet(styleSheet);
    }

    entryPoint::initSettings(*application);
    entryPoint::initFonts(*application);

    if (!parser.isSet(noLaunchOption))
    {
        #ifdef Q_OS_WIN
            // Background color
            // This is only for WinApi window, Qt widgets use BorderlessWindow.css stylesheet
            HBRUSH windowBackground = CreateSolidBrush(RGB(15, 15, 15));

            // Create a Win window
            BorderlessWindow window(application, windowBackground, 1152, 648);
            window.setMinimumSize(1152, 648);
        #else
            // Create a Unix window
            UnixWindow window;
            window.setMinimumSize(1152, 648);
        #endif

        if (!dbExists)
        {
            wiz->show();
        }
        application->exec();
    }
    else
    {
        application->quit();
    }

    return 0;
}
<commit_msg>Catch exceptions in main (Closes: #79)<commit_after>#include "init.h"
#include "widgets/wizards/setupwizard.h"
#include "defines.h"
#include "widgets/stack/library.h"
#include "database.h"

#include <QApplication>
#include <QFile>
#include <QIcon>
#include <QTextStream>

#include <QCommandLineParser>
#include <QCommandLineOption>

#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>

#ifdef Q_OS_WIN
    #include "src/widgets/window/borderlesswindow.h"
#else
    #include "src/widgets/window/unixwindow.h"
#endif

int main(int argc, char* argv[])
{
    try
    {
        QCoreApplication::addLibraryPath("./");

        QApplication::setStyle("fusion");
        QApplication* application = new QApplication(argc, argv);
        application->setApplicationName("Horizon Launcher");

        QTranslator horizonTranslator;
        horizonTranslator.load("horizon_" + QLocale::system().name());
        application->installTranslator(&horizonTranslator);

        QDir configFolder(CONFIG_FOLDER);
        if (!configFolder.exists())
        {
            configFolder.cdUp();
            configFolder.mkdir("HorizonLauncher");
        }

        QDir imageDirectory(CONFIG_FOLDER + QDir::separator() + "image");
        if (!imageDirectory.exists())
        {
            imageDirectory.cdUp();
            imageDirectory.mkdir("image");
        }

        bool dbExists = QFile(QDir(CONFIG_FOLDER).filePath("horizon.db")).exists();

        if (!Library::db.init())
        {
            QMessageBox error;
            error.critical(0, QWidget::tr("Error!"), QWidget::tr("An error occurred while trying to load the database."));
            exit(EXIT_FAILURE);
        }

        QCommandLineParser parser;

        parser.setApplicationDescription("Horizon Launcher");
        parser.addHelpOption();

        QCommandLineOption noLaunchOption(QStringList() << "n" << "nolaunch",
                                      QWidget::tr("Don't launch Horizon's GUI -- exit after processing command-line arguments."));
        parser.addOption(noLaunchOption);

        QCommandLineOption jsonOption(QStringList() << "json",
                                      QWidget::tr("Output in JSON format instead of human-readable."));
        parser.addOption(jsonOption);

        QCommandLineOption listOption(QStringList() << "l" << "list",
                                      QWidget::tr("List all games in the Horizon database."));
        parser.addOption(listOption);

        parser.process(*application);

        if (parser.isSet(listOption))
        {
            QTextStream sout(stdout);

            if (parser.isSet(jsonOption))
            {
                QJsonArray gamesJSON;
                for (Game game : Library::db.getGames())
                {
                    QJsonObject gameJSON;
                    gameJSON["id"] = QString::number(game.id);
                    gameJSON["name"] = game.gameName;
                    gameJSON["directory"] = game.gameDirectory;
                    gameJSON["executable"] = game.executablePath;
                    gameJSON["arguments"] = game.arguments;
                    gameJSON["drm"] = game.drm;

                    gamesJSON.append(gameJSON);
                }

                QJsonDocument doc(gamesJSON);

                sout << doc.toJson(QJsonDocument::Compact) << "\r\n";
                sout.flush();
            }
            else
            {
                QList<Game> games = Library::db.getGames();
                int largestID = QString::number(games[0].id).length();
                int largestName = games[0].gameName.length();
                int largestDir = games[0].gameDirectory.length();
                int largestBin = games[0].executablePath.length();
                int largestArgs = games[0].arguments.length();
                int largestDRM = Database::getDRMString(games[0].drm).length();

                for (Game game : games)
                {
                    int idLen = QString::number(game.id).length();
                    int nameLen = game.gameName.length();
                    int dirLen = game.gameDirectory.length();
                    int binLen = game.executablePath.length();
                    int argLen = game.arguments.length();
                    int drmLen = Database::getDRMString(game.drm).length();

                    if (idLen > largestID)
                    {
                        largestID = idLen;
                    }
                    if (nameLen > largestName)
                    {
                        largestName = nameLen;
                    }
                    if (dirLen > largestDir)
                    {
                        largestDir = dirLen;
                    }
                    if (binLen > largestBin)
                    {
                        largestBin = binLen;
                    }
                    if (argLen > largestArgs)
                    {
                        largestArgs = argLen;
                    }
                    if (drmLen > largestDRM)
                    {
                        largestDRM = drmLen;
                    }
                }

                sout << QString("ID").leftJustified(largestID, ' ') + "\t" +
                        QString("NAME").leftJustified(largestName, ' ') + "\t" +
                        QString("DIR").leftJustified(largestDir, ' ') + "\t" +
                        QString("BIN").leftJustified(largestBin, ' ') + "\t" +
                        QString("ARGS").leftJustified(largestArgs, ' ') + "\t" +
                        QString("DRM").leftJustified(largestDRM, ' ') + "\r\n";
                for (Game game : games)
                {
                    QJsonObject gameJSON;
                    sout << QString::number(game.id).leftJustified(largestID, ' ') + "\t" +
                            QString(game.gameName).leftJustified(largestName, ' ') + "\t" +
                            QString(game.gameDirectory).leftJustified(largestDir, ' ') + "\t" +
                            QString(game.executablePath).leftJustified(largestBin, ' ') + "\t" +
                            QString(game.arguments).leftJustified(largestArgs, ' ') + "\t" +
                            Database::getDRMString(game.drm).leftJustified(largestDRM, ' ') + "\r\n";
                }
                sout.flush();
            }
        }

        SetupWizard* wiz = new SetupWizard();

        #ifndef Q_OS_WIN
            // dynamic loading of the icon under Linux/UNIX
            application->setWindowIcon(QIcon(":/res/icon/Horizon.ico"));
        #endif

        // Global stylesheet
        QFile stylesheet(":/Styles/horizon.css");
        if (stylesheet.open(QFile::ReadOnly))
        {
            QString styleSheet = stylesheet.readAll();
            application->setStyleSheet(styleSheet);
        }

        entryPoint::initSettings(*application);
        entryPoint::initFonts(*application);

        if (!parser.isSet(noLaunchOption))
        {
            #ifdef Q_OS_WIN
                // Background color
                // This is only for WinApi window, Qt widgets use BorderlessWindow.css stylesheet
                HBRUSH windowBackground = CreateSolidBrush(RGB(15, 15, 15));

                // Create a Win window
                BorderlessWindow window(application, windowBackground, 1152, 648);
                window.setMinimumSize(1152, 648);
            #else
                // Create a Unix window
                UnixWindow window;
                window.setMinimumSize(1152, 648);
            #endif

            if (!dbExists)
            {
                wiz->show();
            }
            application->exec();
        }
        else
        {
            application->quit();
        }
    }
    catch (std::exception& exc)
    {
        return 1;
    }

    return 0;
}
<|endoftext|>


<commit_before><commit_msg>Fixes a race condition in CreateNewBlock and a future null deref on testnet.<commit_after><|endoftext|>


<commit_before><commit_msg>change settings for new test chain<commit_after><|endoftext|>


<commit_before><commit_msg>Changes observed during last class<commit_after><|endoftext|>


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

#include <pcl/visualization/interactor.h>
#include <vtkCommand.h>

namespace pcl
{
  namespace visualization
  {
    // Standard VTK macro for *New ()
    vtkStandardNewMacro (PCLVisualizerInteractor);

/*    void
    PCLVisualizerInteractor::TerminateApp ()
    {
      stopped = true;
    }
*/
    //////////////////////////////////////////////////////////////////////////
    void
    PCLVisualizerInteractor::stopLoop ()
    {
#if defined _WIN32 || defined VTK_USE_CARBON || defined VTK_USE_CARBON
      BreakLoopFlagOn ();
      // Send a VTK_BreakWin32Loop ClientMessage event to be sure we pop out of the
      // event loop.  This "wakes up" the event loop.  Otherwise, it might sit idle
      // waiting for an event before realizing an exit was requested.
      SendMessage (this->WindowId, RegisterWindowMessage (TEXT ("VTK_BreakWin32Loop")), 0, 0);
#else
      BreakLoopFlagOn ();
/*      XClientMessageEvent client;
      memset (&client, 0, sizeof (client));
      client.type = ClientMessage;
      client.display = DisplayId;
      client.window = WindowId;
      client.message_type = XInternAtom (client.display, "spinOnce exit", false);
      client.format = 32; // indicates size of data chunks: 8, 16 or 32 bits...
      XSendEvent (client.display, client.window, True, NoEventMask, reinterpret_cast<XEvent *>(&client));
      XFlush (client.display);*/
#endif
    }

#if defined _WIN32 || defined VTK_USE_CARBON || defined VTK_USE_CARBON
    //////////////////////////////////////////////////////////////////////////
    void
    PCLVisualizerInteractor::Start ()
    {
      // Let the compositing handle the event loop if it wants to.
      if (this->HasObserver(vtkCommand::StartEvent) && !this->HandleEventLoop)
      {
        this->InvokeEvent (vtkCommand::StartEvent, NULL);
        return;
      }

      // No need to do anything if this is a 'mapped' interactor
      if (!this->Enabled || !this->InstallMessageProc)
        return;

      this->StartedMessageLoop = 1;

      MSG msg;
      this->BreakLoopFlag=0;

      while (GetMessage (&msg, NULL, 0, 0) && this->BreakLoopFlag == 0)
      {
        TranslateMessage (&msg);
        DispatchMessage (&msg);
      }
    }

    //////////////////////////////////////////////////////////////////////////
    void
    PCLVisualizerInteractor::SetBreakLoopFlag (int f)
    {
      if (f)
        this->BreakLoopFlagOn ();
      else
        this->BreakLoopFlagOff ();
    }

    //////////////////////////////////////////////////////////////////////////
    void
    PCLVisualizerInteractor::BreakLoopFlagOff ()
    {
      this->BreakLoopFlag = 0;
      this->Modified ();
    }

    //////////////////////////////////////////////////////////////////////////
    void
    PCLVisualizerInteractor::BreakLoopFlagOn ()
    {
      this->BreakLoopFlag = 1;
      this->Modified ();
    }
#endif
  }
}

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

#include <pcl/visualization/interactor.h>
#include <vtkCommand.h>

namespace pcl
{
  namespace visualization
  {
    // Standard VTK macro for *New ()
    vtkStandardNewMacro (PCLVisualizerInteractor);

/*    void
    PCLVisualizerInteractor::TerminateApp ()
    {
      stopped = true;
    }
*/
    //////////////////////////////////////////////////////////////////////////
    void
    PCLVisualizerInteractor::stopLoop ()
    {
#if defined _WIN32 || defined VTK_USE_CARBON || defined VTK_USE_CARBON
      BreakLoopFlagOn ();
      // Send a VTK_BreakWin32Loop ClientMessage event to be sure we pop out of the
      // event loop.  This "wakes up" the event loop.  Otherwise, it might sit idle
      // waiting for an event before realizing an exit was requested.
      SendMessage (this->WindowId, RegisterWindowMessage (TEXT ("VTK_BreakWin32Loop")), 0, 0);
#else
      BreakLoopFlagOn ();
      XClientMessageEvent client;
      memset (&client, 0, sizeof (client));
      client.type = ClientMessage;
      client.display = DisplayId;
      client.window = WindowId;
      client.message_type = XInternAtom (client.display, "spinOnce exit", false);
      client.format = 32; // indicates size of data chunks: 8, 16 or 32 bits...
      XSendEvent (client.display, client.window, True, NoEventMask, reinterpret_cast<XEvent *>(&client));
      XFlush (client.display);
#endif
    }

#if defined _WIN32 || defined VTK_USE_CARBON || defined VTK_USE_CARBON
    //////////////////////////////////////////////////////////////////////////
    void
    PCLVisualizerInteractor::Start ()
    {
      // Let the compositing handle the event loop if it wants to.
      if (this->HasObserver(vtkCommand::StartEvent) && !this->HandleEventLoop)
      {
        this->InvokeEvent (vtkCommand::StartEvent, NULL);
        return;
      }

      // No need to do anything if this is a 'mapped' interactor
      if (!this->Enabled || !this->InstallMessageProc)
        return;

      this->StartedMessageLoop = 1;

      MSG msg;
      this->BreakLoopFlag=0;

      while (GetMessage (&msg, NULL, 0, 0) && this->BreakLoopFlag == 0)
      {
        TranslateMessage (&msg);
        DispatchMessage (&msg);
      }
    }

    //////////////////////////////////////////////////////////////////////////
    void
    PCLVisualizerInteractor::SetBreakLoopFlag (int f)
    {
      if (f)
        this->BreakLoopFlagOn ();
      else
        this->BreakLoopFlagOff ();
    }

    //////////////////////////////////////////////////////////////////////////
    void
    PCLVisualizerInteractor::BreakLoopFlagOff ()
    {
      this->BreakLoopFlag = 0;
      this->Modified ();
    }

    //////////////////////////////////////////////////////////////////////////
    void
    PCLVisualizerInteractor::BreakLoopFlagOn ()
    {
      this->BreakLoopFlag = 1;
      this->Modified ();
    }
#endif
  }
}

<|endoftext|>


<commit_before><commit_msg>made upnp log the entire HTTP message sent to the router<commit_after><|endoftext|>


<commit_before><commit_msg>Rewritten the chunk update code handling chunk add and remove queues for the player<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <KAI/Console/Console.h>
#include "Fluid/Window.h"

using namespace std;
using namespace kai;

struct FluidConsole;

shared_ptr<Console> console;
shared_ptr<FluidConsole> fluidConsole;

struct FluidConsole
{
	Value<Executor> _exec;
	Value<Stack> _data;
	Value<Stack> _context;
	Fl_Text_Buffer *_dataOutput;
	Fl_Text_Buffer *_contextOutput;
	Registry *_reg;

	static FluidConsole *self;

	FluidConsole()
	{
		KaiEnter->callback(EnterPressed, 0);

		self = this;
		_exec = console->GetExecutor();
		_data = _exec->GetDataStack();
		_context = _exec->GetContextStack();
		_reg = &console->GetRegistry();

		auto d = new Fl_Text_Buffer();
		auto c = new Fl_Text_Buffer();

		KaiOutputData->buffer(d);
		KaiOutputContext->buffer(c);
		_dataOutput = KaiOutputData->buffer();
		_contextOutput = KaiOutputContext->buffer();
	}

	static void EnterPressed(Fl_Widget *, void *)
	{
		Stack &stack = *self->_data;
		try {
			console->Process(KaiInput->value());
		}
		catch (kai::Exception::Base &e) {
			stack.Push(self->_data.GetRegistry()->New<String>(e.ToString()));
		}
		catch (std::exception &e) {
			stack.Push(self->_data.GetRegistry()->New<String>(e.what()));
		}
		catch (...) {
			stack.Push(self->_reg->New<String>("Exceptional!"));
		}

		KaiInput->value("");

		Refresh();
	}

	static void Refresh()
	{
		RefreshData();
		RefreshContext();
	}

	static void RefreshData()
	{
		RefreshView(self->_data, self->_dataOutput);
	}

	static void RefreshContext()
	{
		RefreshView(self->_context, self->_contextOutput);
	}

	static void RefreshView(Value<Stack> &stack, Fl_Text_Buffer *text)
	{
		StringStream str;
		int n = stack->Size() - 1;
		for (const auto &obj : *self->_data)
		{
			str << "[" << n-- << "] "  << obj << "\n";
		}

		text->text(str.ToString().c_str());
	}
};

FluidConsole *FluidConsole::self;

void StartKai()
{
	cout << "Starting Kai" << endl;
	console = make_shared<kai::Console>();
	console->SetLanguage(Language::Pi);
	fluidConsole = make_shared<FluidConsole>();
}

<commit_msg>Whitepsace  changes<commit_after>#include <iostream>
#include <KAI/Console/Console.h>
#include "Fluid/Window.h"

using namespace std;
using namespace kai;

struct FluidConsole;

shared_ptr<Console> console;
shared_ptr<FluidConsole> fluidConsole;

struct FluidConsole
{
	Value<Executor> _exec;
	Value<Stack> _data;
	Value<Stack> _context;
	Fl_Text_Buffer *_dataOutput;
	Fl_Text_Buffer *_contextOutput;
	Registry *_reg;

	static FluidConsole *self;

	FluidConsole()
	{
		KaiEnter->callback(EnterPressed, 0);

		self = this;
		_exec = console->GetExecutor();
		_data = _exec->GetDataStack();
		_context = _exec->GetContextStack();
		_reg = &console->GetRegistry();

		auto d = new Fl_Text_Buffer();
		auto c = new Fl_Text_Buffer();

		KaiOutputData->buffer(d);
		KaiOutputContext->buffer(c);
		_dataOutput = KaiOutputData->buffer();
		_contextOutput = KaiOutputContext->buffer();
	}

	static void EnterPressed(Fl_Widget *, void *)
	{
		Stack &stack = *self->_data;
		auto &reg = *self->_reg;

		try
		{
			console->Process(KaiInput->value());
		}
		catch (kai::Exception::Base &e)
		{
			stack.Push(reg.New<String>(e.ToString()));
		}
		catch (std::exception &e)
		{
			stack.Push(reg.New<String>(e.what()));
		}
		catch (...)
		{
			stack.Push(reg.New<String>("Exceptional!"));
		}

		KaiInput->value("");

		Refresh();
	}

	static void Refresh()
	{
		RefreshData();
		RefreshContext();
	}

	static void RefreshData()
	{
		RefreshView(self->_data, self->_dataOutput);
	}

	static void RefreshContext()
	{
		RefreshView(self->_context, self->_contextOutput);
	}

	static void RefreshView(Value<Stack> &stack, Fl_Text_Buffer *text)
	{
		StringStream str;
		int n = stack->Size() - 1;
		for (const auto &obj : *self->_data)
		{
			str << "[" << n-- << "] "  << obj << "\n";
		}

		text->text(str.ToString().c_str());
	}
};

FluidConsole *FluidConsole::self;

void StartKai()
{
	cout << "Starting Kai" << endl;
	console = make_shared<kai::Console>();
	console->SetLanguage(Language::Pi);
	fluidConsole = make_shared<FluidConsole>();
}

<|endoftext|>


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

#include <QtCore/qvariant.h>
#include <QtCore/qdebug.h>
#include <QtGui/qwidget.h>

#include "s60mediaplayerservice.h"
#include "s60mediaplayercontrol.h"
#include "s60videoplayersession.h"
#include "s60audioplayersession.h"
#include "s60mediametadataprovider.h"
#include "s60videowidget.h"
#include "s60mediarecognizer.h"
#include "s60videooverlay.h"
#ifdef HAS_VIDEORENDERERCONTROL_IN_VIDEOPLAYER
#include "s60videorenderer.h"
#endif
#include "s60mediaplayeraudioendpointselector.h"
#include "s60mediastreamcontrol.h"

#include <qmediaplaylistnavigator.h>
#include <qmediaplaylist.h>

S60MediaPlayerService::S60MediaPlayerService(QObject *parent)
    : QMediaService(parent)
    , m_control(NULL)
    , m_videoPlayerSession(NULL)
    , m_audioPlayerSession(NULL)
    , m_metaData(NULL)
    , m_audioEndpointSelector(NULL)
    , m_streamControl(NULL)
    , m_videoOutput(NULL)
{
    m_control = new S60MediaPlayerControl(*this, this);
    m_metaData = new S60MediaMetaDataProvider(m_control, this);
    m_audioEndpointSelector = new S60MediaPlayerAudioEndpointSelector(m_control, this);
    m_streamControl = new S60MediaStreamControl(m_control, this);
}

S60MediaPlayerService::~S60MediaPlayerService()
{
}

QMediaControl *S60MediaPlayerService::requestControl(const char *name)
{
    if (qstrcmp(name, QMediaPlayerControl_iid) == 0)
        return m_control;

    if (qstrcmp(name, QMetaDataReaderControl_iid) == 0)
        return m_metaData;

    if (qstrcmp(name, QAudioEndpointSelector_iid) == 0)
        return m_audioEndpointSelector;

    if (qstrcmp(name, QMediaStreamsControl_iid) == 0)
        return m_streamControl;

    if (!m_videoOutput) {
        if (qstrcmp(name, QVideoWidgetControl_iid) == 0) {
            m_videoOutput = new S60VideoWidgetControl(this);
        }
#ifdef HAS_VIDEORENDERERCONTROL_IN_VIDEOPLAYER
        else if (qstrcmp(name, QVideoRendererControl_iid) == 0) {
            m_videoOutput = new S60VideoRenderer(this);
        }
#endif /* HAS_VIDEORENDERERCONTROL_IN_VIDEOPLAYER */
        else if (qstrcmp(name, QVideoWindowControl_iid) == 0) {
            m_videoOutput = new S60VideoOverlay(this);
        }

        if (m_videoOutput) {
            m_control->setVideoOutput(m_videoOutput);
            return m_videoOutput;
        }
    }else {
        if (qstrcmp(name, QVideoWidgetControl_iid) == 0 ||
#ifdef HAS_VIDEORENDERERCONTROL_IN_VIDEOPLAYER
            qstrcmp(name, QVideoRendererControl_iid) == 0 ||
#endif /* HAS_VIDEORENDERERCONTROL_IN_VIDEOPLAYER */
            qstrcmp(name, QVideoWindowControl_iid) == 0){
            return m_videoOutput;
        }
    }
    return 0;
}

void S60MediaPlayerService::releaseControl(QMediaControl *control)
{
    if (control == m_videoOutput) {
        m_videoOutput = 0;
        m_control->setVideoOutput(m_videoOutput);
    }
}

S60MediaPlayerSession* S60MediaPlayerService::PlayerSession()
{
    QUrl url = m_control->media().canonicalUrl();

    if (url.isEmpty() == true) {
        return NULL;
    }

    S60MediaRecognizer *m_mediaRecognizer = new S60MediaRecognizer(this);
    S60MediaRecognizer::MediaType mediaType = m_mediaRecognizer->mediaType(url);

    switch (mediaType) {
    case S60MediaRecognizer::Video:
    case S60MediaRecognizer::Url:
        {
        m_control->setMediaType(S60MediaSettings::Video);
        return VideoPlayerSession();
        }
    case S60MediaRecognizer::Audio:
        {
        m_control->setMediaType(S60MediaSettings::Audio);
        return AudioPlayerSession();
        }
    default:
        m_control->setMediaType(S60MediaSettings::Unknown);
        break;
    }

    return NULL;
}

S60MediaPlayerSession* S60MediaPlayerService::VideoPlayerSession()
{
    if (!m_videoPlayerSession) {
        m_videoPlayerSession = new S60VideoPlayerSession(this);

        connect(m_videoPlayerSession, SIGNAL(positionChanged(qint64)),
                m_control, SIGNAL(positionChanged(qint64)));
        connect(m_videoPlayerSession, SIGNAL(durationChanged(qint64)),
                m_control, SIGNAL(durationChanged(qint64)));
        connect(m_videoPlayerSession, SIGNAL(stateChanged(QMediaPlayer::State)),
                m_control, SIGNAL(stateChanged(QMediaPlayer::State)));
        connect(m_videoPlayerSession, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)),
                m_control, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)));
        connect(m_videoPlayerSession,SIGNAL(bufferStatusChanged(int)),
                m_control, SIGNAL(bufferStatusChanged(int)));
        connect(m_videoPlayerSession, SIGNAL(videoAvailableChanged(bool)),
                m_control, SIGNAL(videoAvailableChanged(bool)));
        connect(m_videoPlayerSession, SIGNAL(audioAvailableChanged(bool)),
                m_control, SIGNAL(audioAvailableChanged(bool)));
        connect(m_videoPlayerSession, SIGNAL(seekableChanged(bool)),
                m_control, SIGNAL(seekableChanged(bool)));
        connect(m_videoPlayerSession, SIGNAL(availablePlaybackRangesChanged(const QMediaTimeRange&)),
                m_control, SIGNAL(availablePlaybackRangesChanged(const QMediaTimeRange&)));
        connect(m_videoPlayerSession, SIGNAL(error(int, const QString &)),
                m_control, SIGNAL(error(int, const QString &)));
        connect(m_videoPlayerSession, SIGNAL(metaDataChanged()),
                m_metaData, SIGNAL(metaDataChanged()));
        connect(m_videoPlayerSession, SIGNAL(activeEndpointChanged(const QString&)),
                m_audioEndpointSelector, SIGNAL(activeEndpointChanged(const QString&)));
        connect(m_videoPlayerSession, SIGNAL(mediaChanged()),
                m_streamControl, SLOT(handleStreamsChanged()));
    }

    m_videoPlayerSession->setVolume(m_control->mediaControlSettings().volume());
    m_videoPlayerSession->setMuted(m_control->mediaControlSettings().isMuted());
    m_videoPlayerSession->setAudioEndpoint(m_control->mediaControlSettings().audioEndpoint());
    return m_videoPlayerSession;
}

S60MediaPlayerSession* S60MediaPlayerService::AudioPlayerSession()
{
    if (!m_audioPlayerSession) {
        m_audioPlayerSession = new S60AudioPlayerSession(this);

        connect(m_audioPlayerSession, SIGNAL(positionChanged(qint64)),
                m_control, SIGNAL(positionChanged(qint64)));
        connect(m_audioPlayerSession, SIGNAL(durationChanged(qint64)),
                m_control, SIGNAL(durationChanged(qint64)));
        connect(m_audioPlayerSession, SIGNAL(stateChanged(QMediaPlayer::State)),
                m_control, SIGNAL(stateChanged(QMediaPlayer::State)));
        connect(m_audioPlayerSession, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)),
                m_control, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)));
        connect(m_audioPlayerSession,SIGNAL(bufferStatusChanged(int)),
                m_control, SIGNAL(bufferStatusChanged(int)));
        connect(m_audioPlayerSession, SIGNAL(videoAvailableChanged(bool)),
                m_control, SIGNAL(videoAvailableChanged(bool)));
        connect(m_audioPlayerSession, SIGNAL(audioAvailableChanged(bool)),
                m_control, SIGNAL(audioAvailableChanged(bool)));
        connect(m_audioPlayerSession, SIGNAL(seekableChanged(bool)),
                m_control, SIGNAL(seekableChanged(bool)));
        connect(m_audioPlayerSession, SIGNAL(availablePlaybackRangesChanged(const QMediaTimeRange&)),
                m_control, SIGNAL(availablePlaybackRangesChanged(const QMediaTimeRange&)));
        connect(m_audioPlayerSession, SIGNAL(error(int, const QString &)),
                m_control, SIGNAL(error(int, const QString &)));
        connect(m_audioPlayerSession, SIGNAL(metaDataChanged()),
                m_metaData, SIGNAL(metaDataChanged()));
        connect(m_audioPlayerSession, SIGNAL(activeEndpointChanged(const QString&)),
                m_audioEndpointSelector, SIGNAL(activeEndpointChanged(const QString&)));
        connect(m_audioPlayerSession, SIGNAL(mediaChanged()),
                m_streamControl, SLOT(handleStreamsChanged()));
    }

    m_audioPlayerSession->setVolume(m_control->mediaControlSettings().volume());
    m_audioPlayerSession->setMuted(m_control->mediaControlSettings().isMuted());
    m_audioPlayerSession->setAudioEndpoint(m_control->mediaControlSettings().audioEndpoint());
    return m_audioPlayerSession;
}
<commit_msg>Fixed memory leak in Symbian MMF MediaPlayer backend<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtCore/qvariant.h>
#include <QtCore/qdebug.h>
#include <QtGui/qwidget.h>

#include "s60mediaplayerservice.h"
#include "s60mediaplayercontrol.h"
#include "s60videoplayersession.h"
#include "s60audioplayersession.h"
#include "s60mediametadataprovider.h"
#include "s60videowidget.h"
#include "s60mediarecognizer.h"
#include "s60videooverlay.h"
#ifdef HAS_VIDEORENDERERCONTROL_IN_VIDEOPLAYER
#include "s60videorenderer.h"
#endif
#include "s60mediaplayeraudioendpointselector.h"
#include "s60mediastreamcontrol.h"

#include <qmediaplaylistnavigator.h>
#include <qmediaplaylist.h>

S60MediaPlayerService::S60MediaPlayerService(QObject *parent)
    : QMediaService(parent)
    , m_control(NULL)
    , m_videoPlayerSession(NULL)
    , m_audioPlayerSession(NULL)
    , m_metaData(NULL)
    , m_audioEndpointSelector(NULL)
    , m_streamControl(NULL)
    , m_videoOutput(NULL)
{
    m_control = new S60MediaPlayerControl(*this, this);
    m_metaData = new S60MediaMetaDataProvider(m_control, this);
    m_audioEndpointSelector = new S60MediaPlayerAudioEndpointSelector(m_control, this);
    m_streamControl = new S60MediaStreamControl(m_control, this);
}

S60MediaPlayerService::~S60MediaPlayerService()
{
}

QMediaControl *S60MediaPlayerService::requestControl(const char *name)
{
    if (qstrcmp(name, QMediaPlayerControl_iid) == 0)
        return m_control;

    if (qstrcmp(name, QMetaDataReaderControl_iid) == 0)
        return m_metaData;

    if (qstrcmp(name, QAudioEndpointSelector_iid) == 0)
        return m_audioEndpointSelector;

    if (qstrcmp(name, QMediaStreamsControl_iid) == 0)
        return m_streamControl;

    if (!m_videoOutput) {
        if (qstrcmp(name, QVideoWidgetControl_iid) == 0) {
            m_videoOutput = new S60VideoWidgetControl(this);
        }
#ifdef HAS_VIDEORENDERERCONTROL_IN_VIDEOPLAYER
        else if (qstrcmp(name, QVideoRendererControl_iid) == 0) {
            m_videoOutput = new S60VideoRenderer(this);
        }
#endif /* HAS_VIDEORENDERERCONTROL_IN_VIDEOPLAYER */
        else if (qstrcmp(name, QVideoWindowControl_iid) == 0) {
            m_videoOutput = new S60VideoOverlay(this);
        }

        if (m_videoOutput) {
            m_control->setVideoOutput(m_videoOutput);
            return m_videoOutput;
        }
    }else {
        if (qstrcmp(name, QVideoWidgetControl_iid) == 0 ||
#ifdef HAS_VIDEORENDERERCONTROL_IN_VIDEOPLAYER
            qstrcmp(name, QVideoRendererControl_iid) == 0 ||
#endif /* HAS_VIDEORENDERERCONTROL_IN_VIDEOPLAYER */
            qstrcmp(name, QVideoWindowControl_iid) == 0){
            return m_videoOutput;
        }
    }
    return 0;
}

void S60MediaPlayerService::releaseControl(QMediaControl *control)
{
    if (control == m_videoOutput) {
        m_videoOutput = 0;
        m_control->setVideoOutput(m_videoOutput);
    }
}

S60MediaPlayerSession* S60MediaPlayerService::PlayerSession()
{
    QUrl url = m_control->media().canonicalUrl();

    if (url.isEmpty() == true) {
        return NULL;
    }

    QScopedPointer<S60MediaRecognizer> mediaRecognizer(new S60MediaRecognizer);
    S60MediaRecognizer::MediaType mediaType = mediaRecognizer->mediaType(url);
    mediaRecognizer.reset();

    switch (mediaType) {
    case S60MediaRecognizer::Video:
    case S60MediaRecognizer::Url:
        {
        m_control->setMediaType(S60MediaSettings::Video);
        return VideoPlayerSession();
        }
    case S60MediaRecognizer::Audio:
        {
        m_control->setMediaType(S60MediaSettings::Audio);
        return AudioPlayerSession();
        }
    default:
        m_control->setMediaType(S60MediaSettings::Unknown);
        break;
    }

    return NULL;
}

S60MediaPlayerSession* S60MediaPlayerService::VideoPlayerSession()
{
    if (!m_videoPlayerSession) {
        m_videoPlayerSession = new S60VideoPlayerSession(this);

        connect(m_videoPlayerSession, SIGNAL(positionChanged(qint64)),
                m_control, SIGNAL(positionChanged(qint64)));
        connect(m_videoPlayerSession, SIGNAL(durationChanged(qint64)),
                m_control, SIGNAL(durationChanged(qint64)));
        connect(m_videoPlayerSession, SIGNAL(stateChanged(QMediaPlayer::State)),
                m_control, SIGNAL(stateChanged(QMediaPlayer::State)));
        connect(m_videoPlayerSession, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)),
                m_control, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)));
        connect(m_videoPlayerSession,SIGNAL(bufferStatusChanged(int)),
                m_control, SIGNAL(bufferStatusChanged(int)));
        connect(m_videoPlayerSession, SIGNAL(videoAvailableChanged(bool)),
                m_control, SIGNAL(videoAvailableChanged(bool)));
        connect(m_videoPlayerSession, SIGNAL(audioAvailableChanged(bool)),
                m_control, SIGNAL(audioAvailableChanged(bool)));
        connect(m_videoPlayerSession, SIGNAL(seekableChanged(bool)),
                m_control, SIGNAL(seekableChanged(bool)));
        connect(m_videoPlayerSession, SIGNAL(availablePlaybackRangesChanged(const QMediaTimeRange&)),
                m_control, SIGNAL(availablePlaybackRangesChanged(const QMediaTimeRange&)));
        connect(m_videoPlayerSession, SIGNAL(error(int, const QString &)),
                m_control, SIGNAL(error(int, const QString &)));
        connect(m_videoPlayerSession, SIGNAL(metaDataChanged()),
                m_metaData, SIGNAL(metaDataChanged()));
        connect(m_videoPlayerSession, SIGNAL(activeEndpointChanged(const QString&)),
                m_audioEndpointSelector, SIGNAL(activeEndpointChanged(const QString&)));
        connect(m_videoPlayerSession, SIGNAL(mediaChanged()),
                m_streamControl, SLOT(handleStreamsChanged()));
    }

    m_videoPlayerSession->setVolume(m_control->mediaControlSettings().volume());
    m_videoPlayerSession->setMuted(m_control->mediaControlSettings().isMuted());
    m_videoPlayerSession->setAudioEndpoint(m_control->mediaControlSettings().audioEndpoint());
    return m_videoPlayerSession;
}

S60MediaPlayerSession* S60MediaPlayerService::AudioPlayerSession()
{
    if (!m_audioPlayerSession) {
        m_audioPlayerSession = new S60AudioPlayerSession(this);

        connect(m_audioPlayerSession, SIGNAL(positionChanged(qint64)),
                m_control, SIGNAL(positionChanged(qint64)));
        connect(m_audioPlayerSession, SIGNAL(durationChanged(qint64)),
                m_control, SIGNAL(durationChanged(qint64)));
        connect(m_audioPlayerSession, SIGNAL(stateChanged(QMediaPlayer::State)),
                m_control, SIGNAL(stateChanged(QMediaPlayer::State)));
        connect(m_audioPlayerSession, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)),
                m_control, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)));
        connect(m_audioPlayerSession,SIGNAL(bufferStatusChanged(int)),
                m_control, SIGNAL(bufferStatusChanged(int)));
        connect(m_audioPlayerSession, SIGNAL(videoAvailableChanged(bool)),
                m_control, SIGNAL(videoAvailableChanged(bool)));
        connect(m_audioPlayerSession, SIGNAL(audioAvailableChanged(bool)),
                m_control, SIGNAL(audioAvailableChanged(bool)));
        connect(m_audioPlayerSession, SIGNAL(seekableChanged(bool)),
                m_control, SIGNAL(seekableChanged(bool)));
        connect(m_audioPlayerSession, SIGNAL(availablePlaybackRangesChanged(const QMediaTimeRange&)),
                m_control, SIGNAL(availablePlaybackRangesChanged(const QMediaTimeRange&)));
        connect(m_audioPlayerSession, SIGNAL(error(int, const QString &)),
                m_control, SIGNAL(error(int, const QString &)));
        connect(m_audioPlayerSession, SIGNAL(metaDataChanged()),
                m_metaData, SIGNAL(metaDataChanged()));
        connect(m_audioPlayerSession, SIGNAL(activeEndpointChanged(const QString&)),
                m_audioEndpointSelector, SIGNAL(activeEndpointChanged(const QString&)));
        connect(m_audioPlayerSession, SIGNAL(mediaChanged()),
                m_streamControl, SLOT(handleStreamsChanged()));
    }

    m_audioPlayerSession->setVolume(m_control->mediaControlSettings().volume());
    m_audioPlayerSession->setMuted(m_control->mediaControlSettings().isMuted());
    m_audioPlayerSession->setAudioEndpoint(m_control->mediaControlSettings().audioEndpoint());
    return m_audioPlayerSession;
}
<|endoftext|>