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

#include <memory>

#include <gtest/gtest.h>

#include "SurgSim/Framework/ApplicationData.h"
#include "SurgSim/Framework/FrameworkConvert.h"
#include "SurgSim/Framework/Runtime.h"
#include "SurgSim/Math/MeshShape.h"
#include "SurgSim/Math/OdeSolver.h"
#include "SurgSim/Math/Vector.h"
#include "SurgSim/Physics/DeformableCollisionRepresentation.h"
#include "SurgSim/Physics/DeformableRepresentation.h"
#include "SurgSim/Physics/Fem3DRepresentation.h"
#include "SurgSim/Physics/UnitTests/MockObjects.h"

namespace
{
const double epsilon = 1e-10;
}

namespace SurgSim
{
namespace Physics
{

struct DeformableCollisionRepresentationTest : public ::testing::Test
{
	void SetUp()
	{
		m_filename = std::string("Geometry/wound_deformable.ply");
		m_applicationData = std::make_shared<SurgSim::Framework::ApplicationData>("config.txt");
		m_meshShape = std::make_shared<SurgSim::Math::MeshShape>();
		m_meshShape->setFileName(m_filename);
		m_deformableRepresentation = std::make_shared<MockDeformableRepresentation>("DeformableRepresentation");
		m_deformableCollisionRepresentation =
			std::make_shared<DeformableCollisionRepresentation>("DeformableCollisionRepresentation");
		m_runtime = std::make_shared<SurgSim::Framework::Runtime>("config.txt");
	}

	std::string m_filename;
	std::shared_ptr<SurgSim::Framework::ApplicationData> m_applicationData;
	std::shared_ptr<SurgSim::Math::MeshShape> m_meshShape;
	std::shared_ptr<SurgSim::Framework::Runtime> m_runtime;
	std::shared_ptr<SurgSim::Physics::DeformableRepresentation> m_deformableRepresentation;
	std::shared_ptr<SurgSim::Physics::DeformableCollisionRepresentation> m_deformableCollisionRepresentation;
};

TEST_F(DeformableCollisionRepresentationTest, InitTest)
{
	EXPECT_NO_THROW(DeformableCollisionRepresentation("TestDeformableCollisionRepresentation"));
}

TEST_F(DeformableCollisionRepresentationTest, SetGetDeformableRepresentationTest)
{
	ASSERT_NO_THROW(m_deformableCollisionRepresentation->setDeformableRepresentation(m_deformableRepresentation));
	EXPECT_EQ(m_deformableRepresentation, m_deformableCollisionRepresentation->getDeformableRepresentation());
}

TEST_F(DeformableCollisionRepresentationTest, ShapeTest)
{
	EXPECT_ANY_THROW(m_deformableCollisionRepresentation->getShapeType());
	m_deformableCollisionRepresentation->setShape(m_meshShape);
	EXPECT_EQ(SurgSim::Math::SHAPE_TYPE_MESH, m_deformableCollisionRepresentation->getShapeType());

	auto meshShape =
		std::dynamic_pointer_cast<SurgSim::Math::MeshShape>(m_deformableCollisionRepresentation->getShape());
	EXPECT_NEAR(m_meshShape->getVolume(), meshShape->getVolume(), epsilon);
	EXPECT_TRUE(m_meshShape->getCenter().isApprox(meshShape->getCenter()));
	EXPECT_TRUE(m_meshShape->getSecondMomentOfVolume().isApprox(meshShape->getSecondMomentOfVolume()));
}

TEST_F(DeformableCollisionRepresentationTest, MeshTest)
{
	m_meshShape->initialize(m_applicationData);

	m_deformableCollisionRepresentation->setMesh(m_meshShape->getMesh());
	EXPECT_EQ(m_meshShape->getMesh()->getNumVertices(),
		m_deformableCollisionRepresentation->getMesh()->getNumVertices());
	EXPECT_EQ(m_meshShape->getMesh()->getNumEdges(),
		m_deformableCollisionRepresentation->getMesh()->getNumEdges());
	EXPECT_EQ(m_meshShape->getMesh()->getNumTriangles(),
		m_deformableCollisionRepresentation->getMesh()->getNumTriangles());
}

TEST_F(DeformableCollisionRepresentationTest, SerializationTest)
{
	auto shape = std::dynamic_pointer_cast<SurgSim::Math::Shape>(m_meshShape);
	m_deformableCollisionRepresentation->setValue("Shape", shape);

	YAML::Node node;
	ASSERT_NO_THROW(node = YAML::convert<SurgSim::Framework::Component>::encode(*m_deformableCollisionRepresentation));

	std::shared_ptr<SurgSim::Physics::DeformableCollisionRepresentation> newDeformableCollisionRepresentation;
	ASSERT_NO_THROW(newDeformableCollisionRepresentation =
		std::dynamic_pointer_cast<SurgSim::Physics::DeformableCollisionRepresentation>
			(node.as<std::shared_ptr<SurgSim::Framework::Component>>())
		);

	auto fem3DRepresentation = std::make_shared<SurgSim::Physics::Fem3DRepresentation>("Fem3DRepresentation");
	fem3DRepresentation->setCollisionRepresentation(newDeformableCollisionRepresentation);
	newDeformableCollisionRepresentation->initialize(m_runtime);

	auto mesh = std::dynamic_pointer_cast<SurgSim::Math::MeshShape>(newDeformableCollisionRepresentation->getShape());
	m_meshShape->initialize(m_applicationData);
	EXPECT_NEAR(m_meshShape->getVolume(), mesh->getVolume(), epsilon);
	EXPECT_TRUE(m_meshShape->getCenter().isApprox(mesh->getCenter()));
	EXPECT_TRUE(m_meshShape->getSecondMomentOfVolume().isApprox(mesh->getSecondMomentOfVolume()));

	EXPECT_EQ(m_meshShape->getMesh()->getNumVertices(), mesh->getMesh()->getNumVertices());
	EXPECT_EQ(m_meshShape->getMesh()->getNumEdges(), mesh->getMesh()->getNumEdges());
	EXPECT_EQ(m_meshShape->getMesh()->getNumTriangles(), mesh->getMesh()->getNumTriangles());
}

TEST_F(DeformableCollisionRepresentationTest, UpdateAndInitializationTest)
{
	EXPECT_ANY_THROW(m_deformableCollisionRepresentation->update(0.0));

	auto fem3DRepresentation = std::make_shared<SurgSim::Physics::Fem3DRepresentation>("Fem3DRepresentation");
	fem3DRepresentation->setFilename(m_filename);

	// Member data 'odeState' will be created while loading.
	ASSERT_TRUE(fem3DRepresentation->initialize(m_runtime));

	// Connect Physics representation with Collision representation.
	fem3DRepresentation->setCollisionRepresentation(m_deformableCollisionRepresentation);

	// Set the shape used by Collision representation.
	m_deformableCollisionRepresentation->setShape(m_meshShape);
	EXPECT_NO_THROW(m_deformableCollisionRepresentation->initialize(m_runtime));
	EXPECT_NO_THROW(m_deformableCollisionRepresentation->update(0.0));
}

} // namespace Physics
} // namespace SurgSim<commit_msg>Fix UnitTest failure of DeformableCollisionRepresentation on Linux<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <memory>

#include <gtest/gtest.h>

#include "SurgSim/Framework/ApplicationData.h"
#include "SurgSim/Framework/FrameworkConvert.h"
#include "SurgSim/Framework/Runtime.h"
#include "SurgSim/Math/MeshShape.h"
#include "SurgSim/Math/OdeSolver.h"
#include "SurgSim/Math/Vector.h"
#include "SurgSim/Physics/DeformableCollisionRepresentation.h"
#include "SurgSim/Physics/DeformableRepresentation.h"
#include "SurgSim/Physics/Fem3DRepresentation.h"
#include "SurgSim/Physics/UnitTests/MockObjects.h"

namespace
{
const double epsilon = 1e-10;
}

namespace SurgSim
{
namespace Physics
{

struct DeformableCollisionRepresentationTest : public ::testing::Test
{
	void SetUp()
	{
		m_filename = std::string("Geometry/wound_deformable.ply");
		m_applicationData = std::make_shared<SurgSim::Framework::ApplicationData>("config.txt");
		m_meshShape = std::make_shared<SurgSim::Math::MeshShape>();
		m_meshShape->setFileName(m_filename);
		m_deformableRepresentation = std::make_shared<MockDeformableRepresentation>("DeformableRepresentation");
		m_deformableCollisionRepresentation =
			std::make_shared<DeformableCollisionRepresentation>("DeformableCollisionRepresentation");
		m_runtime = std::make_shared<SurgSim::Framework::Runtime>("config.txt");
	}

	std::string m_filename;
	std::shared_ptr<SurgSim::Framework::ApplicationData> m_applicationData;
	std::shared_ptr<SurgSim::Math::MeshShape> m_meshShape;
	std::shared_ptr<SurgSim::Framework::Runtime> m_runtime;
	std::shared_ptr<SurgSim::Physics::DeformableRepresentation> m_deformableRepresentation;
	std::shared_ptr<SurgSim::Physics::DeformableCollisionRepresentation> m_deformableCollisionRepresentation;
};

TEST_F(DeformableCollisionRepresentationTest, InitTest)
{
	EXPECT_NO_THROW(DeformableCollisionRepresentation("TestDeformableCollisionRepresentation"));
}

TEST_F(DeformableCollisionRepresentationTest, SetGetDeformableRepresentationTest)
{
	ASSERT_NO_THROW(m_deformableCollisionRepresentation->setDeformableRepresentation(m_deformableRepresentation));
	EXPECT_EQ(m_deformableRepresentation, m_deformableCollisionRepresentation->getDeformableRepresentation());
}

TEST_F(DeformableCollisionRepresentationTest, ShapeTest)
{
	EXPECT_ANY_THROW(m_deformableCollisionRepresentation->getShapeType());
	m_meshShape->initialize(m_applicationData);
	m_deformableCollisionRepresentation->setShape(m_meshShape);
	EXPECT_EQ(SurgSim::Math::SHAPE_TYPE_MESH, m_deformableCollisionRepresentation->getShapeType());

	auto meshShape =
		std::dynamic_pointer_cast<SurgSim::Math::MeshShape>(m_deformableCollisionRepresentation->getShape());
	EXPECT_NEAR(m_meshShape->getVolume(), meshShape->getVolume(), epsilon);
	EXPECT_TRUE(m_meshShape->getCenter().isApprox(meshShape->getCenter()));
	EXPECT_TRUE(m_meshShape->getSecondMomentOfVolume().isApprox(meshShape->getSecondMomentOfVolume()));
}

TEST_F(DeformableCollisionRepresentationTest, MeshTest)
{
	m_meshShape->initialize(m_applicationData);

	m_deformableCollisionRepresentation->setMesh(m_meshShape->getMesh());
	EXPECT_EQ(m_meshShape->getMesh()->getNumVertices(),
		m_deformableCollisionRepresentation->getMesh()->getNumVertices());
	EXPECT_EQ(m_meshShape->getMesh()->getNumEdges(),
		m_deformableCollisionRepresentation->getMesh()->getNumEdges());
	EXPECT_EQ(m_meshShape->getMesh()->getNumTriangles(),
		m_deformableCollisionRepresentation->getMesh()->getNumTriangles());
}

TEST_F(DeformableCollisionRepresentationTest, SerializationTest)
{
	auto shape = std::dynamic_pointer_cast<SurgSim::Math::Shape>(m_meshShape);
	m_deformableCollisionRepresentation->setValue("Shape", shape);

	YAML::Node node;
	ASSERT_NO_THROW(node = YAML::convert<SurgSim::Framework::Component>::encode(*m_deformableCollisionRepresentation));

	std::shared_ptr<SurgSim::Physics::DeformableCollisionRepresentation> newDeformableCollisionRepresentation;
	ASSERT_NO_THROW(newDeformableCollisionRepresentation =
		std::dynamic_pointer_cast<SurgSim::Physics::DeformableCollisionRepresentation>
			(node.as<std::shared_ptr<SurgSim::Framework::Component>>())
		);

	auto fem3DRepresentation = std::make_shared<SurgSim::Physics::Fem3DRepresentation>("Fem3DRepresentation");
	fem3DRepresentation->setCollisionRepresentation(newDeformableCollisionRepresentation);
	newDeformableCollisionRepresentation->initialize(m_runtime);

	auto mesh = std::dynamic_pointer_cast<SurgSim::Math::MeshShape>(newDeformableCollisionRepresentation->getShape());
	m_meshShape->initialize(m_applicationData);
	EXPECT_NEAR(m_meshShape->getVolume(), mesh->getVolume(), epsilon);
	EXPECT_TRUE(m_meshShape->getCenter().isApprox(mesh->getCenter()));
	EXPECT_TRUE(m_meshShape->getSecondMomentOfVolume().isApprox(mesh->getSecondMomentOfVolume()));

	EXPECT_EQ(m_meshShape->getMesh()->getNumVertices(), mesh->getMesh()->getNumVertices());
	EXPECT_EQ(m_meshShape->getMesh()->getNumEdges(), mesh->getMesh()->getNumEdges());
	EXPECT_EQ(m_meshShape->getMesh()->getNumTriangles(), mesh->getMesh()->getNumTriangles());
}

TEST_F(DeformableCollisionRepresentationTest, UpdateAndInitializationTest)
{
	EXPECT_ANY_THROW(m_deformableCollisionRepresentation->update(0.0));

	auto fem3DRepresentation = std::make_shared<SurgSim::Physics::Fem3DRepresentation>("Fem3DRepresentation");
	fem3DRepresentation->setFilename(m_filename);

	// Member data 'odeState' will be created while loading.
	ASSERT_TRUE(fem3DRepresentation->initialize(m_runtime));

	// Connect Physics representation with Collision representation.
	fem3DRepresentation->setCollisionRepresentation(m_deformableCollisionRepresentation);

	// Set the shape used by Collision representation.
	m_deformableCollisionRepresentation->setShape(m_meshShape);
	EXPECT_NO_THROW(m_deformableCollisionRepresentation->initialize(m_runtime));
	EXPECT_NO_THROW(m_deformableCollisionRepresentation->update(0.0));
}

} // namespace Physics
} // namespace SurgSim<|endoftext|>


<commit_before>/*
   Copyright (C) 2014-2017 Alexandr Akulich <akulichalexander@gmail.com>

   This file is a part of TelegramQt library.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

 */
#ifndef GENERATOR_HPP
#define GENERATOR_HPP

#include <QtGlobal>

#include <QString>
#include <QList>
#include <QStringList>
#include <QMap>
#include <QVariantHash>
#include <QVector>
#include <functional>

QT_FORWARD_DECLARE_CLASS(QJsonDocument)

struct TLParam {
    TLParam() { }
    TLParam(const QString &newName, const QString &newType, qint8 newFlagBit = -1) :
        flagBit(newFlagBit), m_name(newName) { setType(newType); }

    qint8 flagBit = -1;
    QString flagMember;

    QString type() const { return m_type; }
    QString bareType() const { return m_bareType; }
    void setType(const QString &newType);

    bool isVector() const { return m_isVector; }

    bool accessByPointer() const { return m_accessByPointer; }
    void setAccessByPointer(bool accessByPointer) { m_accessByPointer = accessByPointer; }

    QString getAlias() const { return !m_alias.isEmpty() ? m_alias : m_name; }
    void setAlias(const QString &newAlias) { m_alias = newAlias; }

    QString getName() const { return m_name; }
    void setName(const QString &newName) { m_name = newName; }
    bool dependOnFlag() const { return flagBit >= 0; }

protected:
    QString m_type;
    QString m_bareType;
    QString m_alias;
    QString m_name;
    bool m_isVector = false;
    bool m_accessByPointer = false;
};

struct TLSubType {
    QString name;
    quint32 id;
    QList<TLParam> members;
    QString source; // The source from the spec
};

struct TLType {
    QString name;
    QList<TLSubType> subTypes;

    bool isSelfReferenced() const { return m_selfReferenced; }
    void setSelfReferenced(const bool referenced) { m_selfReferenced = referenced; }

protected:
    bool m_selfReferenced = false;
};

struct TLMethod {
    QString nameFirstCapital() const {
        if (name.isEmpty()) {
            return QString();
        }
        QString capital = name;
        capital[0] = capital.at(0).toUpper();
        return capital;
    }
    QString name;
    quint32 id;
    QString type;
    QString source; // The source from the spec
    QList< TLParam > params;
};

class Generator
{
public:
    struct LineParseResult {
        bool isValid() const { return predicateId && !predicateName.isEmpty() && !typeName.isEmpty(); }
        QString predicateName;
        QString typeName;
        QList<TLParam> params;
        quint32 predicateId = 0;
    };

    enum class FirstLetterCase {
        Any, // Keep same
        Upper,
        Lower,
    };

    Generator();
    bool loadFromJson(const QByteArray &data);
    bool loadFromText(const QByteArray &data);
    bool resolveTypes();
    void setExistsRpcProcessDefinitions(const QString &code);
    void generate();

    static QString getTypeOrVectorType(const QString &str, bool *isVectorPtr = nullptr);
    static qint8 flagBitForMember(const QStringRef &type, QString *flagMember);

    static QMap<QString, TLType> readTypesJson(const QJsonDocument &document);
    static QMap<QString, TLMethod> readFunctionsJson(const QJsonDocument &document);

    static QString removeSeparators(QString name);
    static QString formatName(const QString &name, FirstLetterCase firstCase = FirstLetterCase::Any) { return formatName(QStringList({name}), firstCase); }
    static QString formatName(const QStringList &nameParts, FirstLetterCase firstCase = FirstLetterCase::Any);
    static QString formatType(QString type);
    static QString formatMember(QString name, const QVariantHash &context = {});
    static QString formatMethodParam(const TLParam &param);
    static QString formatMethodParams(const TLMethod &method);
    static QByteArray getPredicateForCrc32(const QByteArray &sourceLine);
    static quint32 getCrc32(const QByteArray &bytes);
    static LineParseResult parseLine(const QString &line);

    QMap<QString, TLType> types() const { return m_types; }
    QList<TLType> solvedTypes() const { return m_solvedTypes; }
    QMap<QString, TLMethod> functions() const { return m_functions; }
    QVector<QStringList> groups() const { return m_groups; }

    void setAddSpecSources(bool addSources);

    static QString removeWord(QString input, QString word);
    static QString generateTLValuesDefinition(const TLType &type);
    static QString generateTLValuesDefinition(const TLMethod &method);
    static QString generateTLTypeDefinition(const TLType &type, bool addSpecSources = false);
    static QStringList generateTLTypeMemberGetters(const TLType &type);
    static QStringList generateTLTypeMembers(const TLType &type);

    static QString streamReadImplementationHead(const QString &argName, const QString &typeName);
    static QString streamReadImplementationEnd(const QString &argName);
    static QString streamReadPerTypeImplementation(const QString &argName, const TLSubType &subType);

    static QString streamWriteImplementationHead(const QString &argName, const QString &typeName);
    static QString streamWriteImplementationEnd(const QString &argName);
    static QString streamWritePerTypeImplementation(const QString &argName, const TLSubType &subType);

    static QString generateStreamOperatorDefinition(const TLType &type,
                                                    std::function<QString(const QString &argName, const QString &typeName)> head,
                                                    std::function<QString(const QString &argName, const TLSubType &subType)> generateSubtypeCode,
                                                    std::function<QString(const QString &argName)> end
                                                    );
    static QString generateStreamReadOperatorDeclaration(const TLType &type);
    static QString generateStreamReadOperatorDefinition(const TLType &type);
    static QString generateStreamReadVectorTemplate(const QString &type);
    static QString generateStreamWriteOperatorDeclaration(const TLType &type);
    static QString generateStreamWriteOperatorDefinition(const TLType &type);
    static QString generateStreamWriteVectorTemplate(const QString &type);

    static QString generateDebugWriteOperatorDeclaration(const TLType &type);
    static QString debugOperatorImplementationHead(const QString &argName, const QString &typeName);
    static QString debugOperatorImplementationEnd(const QString &argName);
    static QString debugOperatorPerTypeImplementation(const QString &argName, const TLSubType &subType);
    static QString generateDebugWriteOperatorDefinition(const TLType &type);

    static QString generateConnectionMethodDeclaration(const TLMethod &method);
    static QString generateConnectionMethodDefinition(const TLMethod &method, QStringList &usedTypes);
    static QString generateRpcProcessDeclaration(const TLMethod &method);
    static QString generateRpcProcessSampleDefinition(const TLMethod &method);
    static QString generateRpcProcessSwitchCase(const TLMethod &method);

    static QString generateDebugRpcParse(const TLMethod &method);

    static QStringList reorderLinesAsExist(QStringList newLines, QStringList existLines);

    static QList<TLType> solveTypes(QMap<QString, TLType> types, QMap<QString, TLType> *unresolved = nullptr);

    void getUsedAndVectorTypes(QStringList &usedTypes, QStringList &vectors) const;

    QString codeOfTLValues;
    QString codeOfTLTypes;
    QString codeStreamReadDeclarations;
    QString codeStreamReadDefinitions;
    QString codeStreamReadTemplateInstancing;
    QString codeStreamWriteDeclarations;
    QString codeStreamWriteDefinitions;
    QString codeStreamWriteTemplateInstancing;
    QString codeConnectionDeclarations;
    QString codeConnectionDefinitions;
    QString codeRpcProcessDeclarations;
    QString codeRpcProcessDefinitions;
    QString codeRpcProcessSwitchCases;
    QString codeRpcProcessSwitchUpdatesCases;
    QString existsStreamReadTemplateInstancing;
    QString existsStreamWriteTemplateInstancing;
    QString existsCodeRpcProcessDefinitions;
    QString codeDebugWriteDeclarations;
    QString codeDebugWriteDefinitions;
    QString codeDebugRpcParse;

private:
    QMap<QString, TLType> m_types;
    QList<TLType> m_solvedTypes;
    QMap<QString, TLMethod> m_functions;
    QVector<QStringList> m_groups;
    bool m_addSpecSources;
};

#endif // GENERATORNG_HPP
<commit_msg>Generator: Extract a base type with Name feature<commit_after>/*
   Copyright (C) 2014-2017 Alexandr Akulich <akulichalexander@gmail.com>

   This file is a part of TelegramQt library.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

 */
#ifndef GENERATOR_HPP
#define GENERATOR_HPP

#include <QtGlobal>

#include <QString>
#include <QList>
#include <QStringList>
#include <QMap>
#include <QVariantHash>
#include <QVector>
#include <functional>

QT_FORWARD_DECLARE_CLASS(QJsonDocument)

struct Name {
    QString name;
};

struct TLParam {
    TLParam() { }
    TLParam(const QString &newName, const QString &newType, qint8 newFlagBit = -1) :
        flagBit(newFlagBit), m_name(newName) { setType(newType); }

    qint8 flagBit = -1;
    QString flagMember;

    QString type() const { return m_type; }
    QString bareType() const { return m_bareType; }
    void setType(const QString &newType);

    bool isVector() const { return m_isVector; }

    bool accessByPointer() const { return m_accessByPointer; }
    void setAccessByPointer(bool accessByPointer) { m_accessByPointer = accessByPointer; }

    QString getAlias() const { return !m_alias.isEmpty() ? m_alias : m_name; }
    void setAlias(const QString &newAlias) { m_alias = newAlias; }

    QString getName() const { return m_name; }
    void setName(const QString &newName) { m_name = newName; }
    bool dependOnFlag() const { return flagBit >= 0; }

protected:
    QString m_type;
    QString m_bareType;
    QString m_alias;
    QString m_name;
    bool m_isVector = false;
    bool m_accessByPointer = false;
};

struct TLSubType : public Name {
    quint32 id;
    QList<TLParam> members;
    QString source; // The source from the spec
};

struct TLType : public Name {
    QList<TLSubType> subTypes;

    bool isSelfReferenced() const { return m_selfReferenced; }
    void setSelfReferenced(const bool referenced) { m_selfReferenced = referenced; }

protected:
    bool m_selfReferenced = false;
};

struct TLMethod : public Name {
    QString nameFirstCapital() const {
        if (name.isEmpty()) {
            return QString();
        }
        QString capital = name;
        capital[0] = capital.at(0).toUpper();
        return capital;
    }
    quint32 id;
    QString type;
    QString source; // The source from the spec
    QList< TLParam > params;
};

class Generator
{
public:
    struct LineParseResult {
        bool isValid() const { return predicateId && !predicateName.isEmpty() && !typeName.isEmpty(); }
        QString predicateName;
        QString typeName;
        QList<TLParam> params;
        quint32 predicateId = 0;
    };

    enum class FirstLetterCase {
        Any, // Keep same
        Upper,
        Lower,
    };

    Generator();
    bool loadFromJson(const QByteArray &data);
    bool loadFromText(const QByteArray &data);
    bool resolveTypes();
    void setExistsRpcProcessDefinitions(const QString &code);
    void generate();

    static QString getTypeOrVectorType(const QString &str, bool *isVectorPtr = nullptr);
    static qint8 flagBitForMember(const QStringRef &type, QString *flagMember);

    static QMap<QString, TLType> readTypesJson(const QJsonDocument &document);
    static QMap<QString, TLMethod> readFunctionsJson(const QJsonDocument &document);

    static QString removeSeparators(QString name);
    static QString formatName(const QString &name, FirstLetterCase firstCase = FirstLetterCase::Any) { return formatName(QStringList({name}), firstCase); }
    static QString formatName(const QStringList &nameParts, FirstLetterCase firstCase = FirstLetterCase::Any);
    static QString formatType(QString type);
    static QString formatMember(QString name, const QVariantHash &context = {});
    static QString formatMethodParam(const TLParam &param);
    static QString formatMethodParams(const TLMethod &method);
    static QByteArray getPredicateForCrc32(const QByteArray &sourceLine);
    static quint32 getCrc32(const QByteArray &bytes);
    static LineParseResult parseLine(const QString &line);

    QMap<QString, TLType> types() const { return m_types; }
    QList<TLType> solvedTypes() const { return m_solvedTypes; }
    QMap<QString, TLMethod> functions() const { return m_functions; }
    QVector<QStringList> groups() const { return m_groups; }

    void setAddSpecSources(bool addSources);

    static QString removeWord(QString input, QString word);
    static QString generateTLValuesDefinition(const TLType &type);
    static QString generateTLValuesDefinition(const TLMethod &method);
    static QString generateTLTypeDefinition(const TLType &type, bool addSpecSources = false);
    static QStringList generateTLTypeMemberGetters(const TLType &type);
    static QStringList generateTLTypeMembers(const TLType &type);

    static QString streamReadImplementationHead(const QString &argName, const QString &typeName);
    static QString streamReadImplementationEnd(const QString &argName);
    static QString streamReadPerTypeImplementation(const QString &argName, const TLSubType &subType);

    static QString streamWriteImplementationHead(const QString &argName, const QString &typeName);
    static QString streamWriteImplementationEnd(const QString &argName);
    static QString streamWritePerTypeImplementation(const QString &argName, const TLSubType &subType);

    static QString generateStreamOperatorDefinition(const TLType &type,
                                                    std::function<QString(const QString &argName, const QString &typeName)> head,
                                                    std::function<QString(const QString &argName, const TLSubType &subType)> generateSubtypeCode,
                                                    std::function<QString(const QString &argName)> end
                                                    );
    static QString generateStreamReadOperatorDeclaration(const TLType &type);
    static QString generateStreamReadOperatorDefinition(const TLType &type);
    static QString generateStreamReadVectorTemplate(const QString &type);
    static QString generateStreamWriteOperatorDeclaration(const TLType &type);
    static QString generateStreamWriteOperatorDefinition(const TLType &type);
    static QString generateStreamWriteVectorTemplate(const QString &type);

    static QString generateDebugWriteOperatorDeclaration(const TLType &type);
    static QString debugOperatorImplementationHead(const QString &argName, const QString &typeName);
    static QString debugOperatorImplementationEnd(const QString &argName);
    static QString debugOperatorPerTypeImplementation(const QString &argName, const TLSubType &subType);
    static QString generateDebugWriteOperatorDefinition(const TLType &type);

    static QString generateConnectionMethodDeclaration(const TLMethod &method);
    static QString generateConnectionMethodDefinition(const TLMethod &method, QStringList &usedTypes);
    static QString generateRpcProcessDeclaration(const TLMethod &method);
    static QString generateRpcProcessSampleDefinition(const TLMethod &method);
    static QString generateRpcProcessSwitchCase(const TLMethod &method);

    static QString generateDebugRpcParse(const TLMethod &method);

    static QStringList reorderLinesAsExist(QStringList newLines, QStringList existLines);

    static QList<TLType> solveTypes(QMap<QString, TLType> types, QMap<QString, TLType> *unresolved = nullptr);

    void getUsedAndVectorTypes(QStringList &usedTypes, QStringList &vectors) const;

    QString codeOfTLValues;
    QString codeOfTLTypes;
    QString codeStreamReadDeclarations;
    QString codeStreamReadDefinitions;
    QString codeStreamReadTemplateInstancing;
    QString codeStreamWriteDeclarations;
    QString codeStreamWriteDefinitions;
    QString codeStreamWriteTemplateInstancing;
    QString codeConnectionDeclarations;
    QString codeConnectionDefinitions;
    QString codeRpcProcessDeclarations;
    QString codeRpcProcessDefinitions;
    QString codeRpcProcessSwitchCases;
    QString codeRpcProcessSwitchUpdatesCases;
    QString existsStreamReadTemplateInstancing;
    QString existsStreamWriteTemplateInstancing;
    QString existsCodeRpcProcessDefinitions;
    QString codeDebugWriteDeclarations;
    QString codeDebugWriteDefinitions;
    QString codeDebugRpcParse;

private:
    QMap<QString, TLType> m_types;
    QList<TLType> m_solvedTypes;
    QMap<QString, TLMethod> m_functions;
    QVector<QStringList> m_groups;
    bool m_addSpecSources;
};

#endif // GENERATORNG_HPP
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkFixedCenterOfRotationAffineTransformTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include <iostream>

#include "itkFixedCenterOfRotationAffineTransform.h"
#include "itkImage.h"
#include "vnl/vnl_vector_fixed.h"

int itkFixedCenterOfRotationAffineTransformTest(int, char *[])
{
  typedef itk::FixedCenterOfRotationAffineTransform<double,2> FCoRAffine2DType;
  typedef itk::AffineTransform<double,2>    FAffine2DType;
  FCoRAffine2DType::MatrixType              matrix2;
  FAffine2DType::Pointer                    inverse2;
  FCoRAffine2DType::InputVectorType         vector2;
  FCoRAffine2DType::InputPointType          point2;

  FCoRAffine2DType::Pointer id2 = FCoRAffine2DType::New();
  matrix2 = id2->GetMatrixComponent();
  vector2 = id2->GetOffsetComponent();
  point2 = id2->GetCenterOfRotationComponent();

  std::cout << "Instantiation of an identity Transform: ";

  bool fail = false;
  for(unsigned int i=0;i<2;i++)
  {
    for(unsigned int j=0;j<2;j++)
    {
      if( (i!=j) && (matrix2.GetVnlMatrix().get(i,j) != 0.0))
      {
        fail = true;
      }
      else if((i==j) && (matrix2.GetVnlMatrix().get(i,j) != 1.0))
      {
        fail = true;
      }
    }
    if((vector2[i] != 0.0) || (point2[i] != 0.0))
    {
      fail = true;
    }
  }

  if(fail)
  {
    std::cout << "[FAILURE]" << std::endl;
    return EXIT_FAILURE;
  }
  else
  {
    std::cout << "[SUCCESS]" << std::endl;
  }

  /* Create and show a simple 2D transform from given parameters */
  matrix2[0][0] = 1;
  matrix2[0][1] = 2;
  matrix2[1][0] = 3;
  matrix2[1][1] = 4;
  vector2[0] = 5;
  vector2[1] = 6;
  point2[0] = 1;
  point2[1] = 1;

  FCoRAffine2DType::Pointer aff2 = FCoRAffine2DType::New();
  aff2->SetMatrixComponent( matrix2 );
  aff2->SetOffsetComponent( vector2 );
  aff2->SetCenterOfRotationComponent( point2 );

  std::cout << "Instantiation of a given 2D transform: ";

  matrix2 = aff2->GetMatrixComponent();
  vector2 = aff2->GetOffsetComponent();
  point2 = aff2->GetCenterOfRotationComponent();

  if(
    matrix2[0][0] != 1 ||
    matrix2[0][1] != 2 ||
    matrix2[1][0] != 3 ||
    matrix2[1][1] != 4 ||
    vector2[0] != 5 ||
    vector2[1] != 6 ||
    point2[0] != 1 ||
    point2[1] != 1
    )
  {
    std::cout << "[FAILURE]" << std::endl;
    return EXIT_FAILURE;
  }
  else
  {
    std::cout << "[SUCCESS]" << std::endl;
  }

  /** Test set matrix after setting components */
  double scale[2];
  scale[0]=2;
  scale[1]=4;

  aff2->SetScaleComponent(scale);
  aff2->SetMatrix(matrix2);

  matrix2 = aff2->GetMatrixComponent();
  vector2 = aff2->GetOffsetComponent();
  const double* resultingScale = aff2->GetScaleComponent();

  std::cout << "Modify the affine matrix: ";

  if(
    matrix2[0][0] != 1 ||
    matrix2[0][1] != 2 ||
    matrix2[1][0] != 3 ||
    matrix2[1][1] != 4 ||
    vector2[0] != 5 ||
    vector2[1] != 6 ||
    point2[0] != 1 ||
    point2[1] != 1 ||
    resultingScale[0] !=1 ||
    resultingScale[1] !=1
    )
  {
    std::cout << "[FAILURE]" << std::endl;
    return EXIT_FAILURE;
  }
  else
  {
    std::cout << "[SUCCESS]" << std::endl;
  }

  /** Try scaling */
  std::cout << "Testing scaling: ";
  aff2->SetIdentity();
  aff2->SetScaleComponent(scale);

  matrix2 = aff2->GetMatrix();

  if(
      matrix2[0][0] != 2 ||
      matrix2[0][1] != 0 ||
      matrix2[1][0] != 0 ||
      matrix2[1][1] != 4
    )
  {
    std::cout << "[FAILURE]" << std::endl;
    return EXIT_FAILURE;
  }
  else
  {
    std::cout << "[SUCCESS]" << std::endl;
  }

  /** Test the parameters */
  std::cout << "Setting/Getting parameters: ";

  FCoRAffine2DType::ParametersType parameters(6);
  parameters.Fill(0);

  point2[0] = 1;
  point2[1] = 2;

  aff2->SetCenterOfRotationComponent(point2);

  // Set the identity matrix
  parameters[0]=1;
  parameters[1]=2;
  parameters[2]=3;
  parameters[3]=4;

  // Set the offset
  parameters[4]=3;
  parameters[5]=4;

  aff2->SetParameters(parameters);
  FCoRAffine2DType::ParametersType parameters2;
  parameters2 = aff2->GetParameters();

  if(
      parameters2[0] != 1 ||
      parameters2[1] != 2 ||
      parameters2[2] != 3 ||
      parameters2[3] != 4 ||
      parameters2[4] != 3 ||
      parameters2[5] != 4
    )
  {
    std::cout << "[FAILURE]" << std::endl;
    return EXIT_FAILURE;
  }
  else
  {
    std::cout << "[SUCCESS]" << std::endl;
  }

  /** Testing point transformation */
  std::cout << "Transforming Point: ";

  FCoRAffine2DType::InputPointType point;
  point[0] = 1;
  point[1] = 2;

  FCoRAffine2DType::InputPointType transformedPoint = aff2->TransformPoint(point);

  FCoRAffine2DType::InputPointType expectedPoint;
  FCoRAffine2DType::MatrixType matrix;
  matrix[0][0] = 1;
  matrix[0][1] = 2;
  matrix[1][0] = 3;
  matrix[1][1] = 4;
  FCoRAffine2DType::OffsetType offset;
  offset[0] = 3;
  offset[1] = 4;
  FCoRAffine2DType::InputVectorType v = matrix*(point-point2);

  for(unsigned int i=0;i<2;i++)
  {
    expectedPoint[i] = v[i]+point2[i]+offset[i];
  }

  if(transformedPoint != expectedPoint)
  {
    std::cout << "[FAILURE]" << std::endl;
    return EXIT_FAILURE;
  }
  else
  {
    std::cout << "[SUCCESS]" << std::endl;
  }

  std::cout << "Done!" << std::endl;

  return EXIT_SUCCESS;
}
<commit_msg>BUG: You must set a center before translation - setting center updates translation to maintain a consistent offset.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkFixedCenterOfRotationAffineTransformTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include <iostream>

#include "itkFixedCenterOfRotationAffineTransform.h"
#include "itkImage.h"
#include "vnl/vnl_vector_fixed.h"

int itkFixedCenterOfRotationAffineTransformTest(int, char *[])
{
  typedef itk::FixedCenterOfRotationAffineTransform<double,2> FCoRAffine2DType;
  typedef itk::AffineTransform<double,2>    FAffine2DType;
  FCoRAffine2DType::MatrixType              matrix2;
  FAffine2DType::Pointer                    inverse2;
  FCoRAffine2DType::InputVectorType         vector2;
  FCoRAffine2DType::InputPointType          point2;

  FCoRAffine2DType::Pointer id2 = FCoRAffine2DType::New();
  matrix2 = id2->GetMatrixComponent();
  vector2 = id2->GetOffsetComponent();
  point2 = id2->GetCenterOfRotationComponent();

  std::cout << "Instantiation of an identity Transform: ";

  bool fail = false;
  for(unsigned int i=0;i<2;i++)
  {
    for(unsigned int j=0;j<2;j++)
    {
      if( (i!=j) && (matrix2.GetVnlMatrix().get(i,j) != 0.0))
      {
        fail = true;
      }
      else if((i==j) && (matrix2.GetVnlMatrix().get(i,j) != 1.0))
      {
        fail = true;
      }
    }
    if((vector2[i] != 0.0) || (point2[i] != 0.0))
    {
      fail = true;
    }
  }

  if(fail)
  {
    std::cout << "[FAILURE]" << std::endl;
    return EXIT_FAILURE;
  }
  else
  {
    std::cout << "[SUCCESS]" << std::endl;
  }

  /* Create and show a simple 2D transform from given parameters */
  matrix2[0][0] = 1;
  matrix2[0][1] = 2;
  matrix2[1][0] = 3;
  matrix2[1][1] = 4;
  vector2[0] = 5;
  vector2[1] = 6;
  point2[0] = 1;
  point2[1] = 1;

  FCoRAffine2DType::Pointer aff2 = FCoRAffine2DType::New();
  aff2->SetCenterOfRotationComponent( point2 );
  aff2->SetMatrixComponent( matrix2 );
  aff2->SetOffsetComponent( vector2 );

  std::cout << "Instantiation of a given 2D transform: ";

  matrix2 = aff2->GetMatrixComponent();
  vector2 = aff2->GetOffsetComponent();
  point2 = aff2->GetCenterOfRotationComponent();

  if(
    matrix2[0][0] != 1 ||
    matrix2[0][1] != 2 ||
    matrix2[1][0] != 3 ||
    matrix2[1][1] != 4 ||
    vector2[0] != 5 ||
    vector2[1] != 6 ||
    point2[0] != 1 ||
    point2[1] != 1
    )
  {
    std::cout << "[FAILURE]" << std::endl;
    return EXIT_FAILURE;
  }
  else
  {
    std::cout << "[SUCCESS]" << std::endl;
  }

  /** Test set matrix after setting components */
  double scale[2];
  scale[0]=2;
  scale[1]=4;

  aff2->SetScaleComponent(scale);
  aff2->SetMatrix(matrix2);

  matrix2 = aff2->GetMatrixComponent();
  vector2 = aff2->GetOffsetComponent();
  const double* resultingScale = aff2->GetScaleComponent();

  std::cout << "Modify the affine matrix: ";

  if(
    matrix2[0][0] != 1 ||
    matrix2[0][1] != 2 ||
    matrix2[1][0] != 3 ||
    matrix2[1][1] != 4 ||
    vector2[0] != 5 ||
    vector2[1] != 6 ||
    point2[0] != 1 ||
    point2[1] != 1 ||
    resultingScale[0] !=1 ||
    resultingScale[1] !=1
    )
  {
    std::cout << "[FAILURE]" << std::endl;
    return EXIT_FAILURE;
  }
  else
  {
    std::cout << "[SUCCESS]" << std::endl;
  }

  /** Try scaling */
  std::cout << "Testing scaling: ";
  aff2->SetIdentity();
  aff2->SetScaleComponent(scale);

  matrix2 = aff2->GetMatrix();

  if(
      matrix2[0][0] != 2 ||
      matrix2[0][1] != 0 ||
      matrix2[1][0] != 0 ||
      matrix2[1][1] != 4
    )
  {
    std::cout << "[FAILURE]" << std::endl;
    return EXIT_FAILURE;
  }
  else
  {
    std::cout << "[SUCCESS]" << std::endl;
  }

  /** Test the parameters */
  std::cout << "Setting/Getting parameters: ";

  FCoRAffine2DType::ParametersType parameters(6);
  parameters.Fill(0);

  point2[0] = 1;
  point2[1] = 2;

  aff2->SetCenterOfRotationComponent(point2);

  // Set the identity matrix
  parameters[0]=1;
  parameters[1]=2;
  parameters[2]=3;
  parameters[3]=4;

  // Set the offset
  parameters[4]=3;
  parameters[5]=4;

  aff2->SetParameters(parameters);
  FCoRAffine2DType::ParametersType parameters2;
  parameters2 = aff2->GetParameters();

  if(
      parameters2[0] != 1 ||
      parameters2[1] != 2 ||
      parameters2[2] != 3 ||
      parameters2[3] != 4 ||
      parameters2[4] != 3 ||
      parameters2[5] != 4
    )
  {
    std::cout << "[FAILURE]" << std::endl;
    return EXIT_FAILURE;
  }
  else
  {
    std::cout << "[SUCCESS]" << std::endl;
  }

  /** Testing point transformation */
  std::cout << "Transforming Point: ";

  FCoRAffine2DType::InputPointType point;
  point[0] = 1;
  point[1] = 2;

  FCoRAffine2DType::InputPointType transformedPoint = aff2->TransformPoint(point);

  FCoRAffine2DType::InputPointType expectedPoint;
  FCoRAffine2DType::MatrixType matrix;
  matrix[0][0] = 1;
  matrix[0][1] = 2;
  matrix[1][0] = 3;
  matrix[1][1] = 4;
  FCoRAffine2DType::OffsetType offset;
  offset[0] = 3;
  offset[1] = 4;
  FCoRAffine2DType::InputVectorType v = matrix*(point-point2);

  for(unsigned int i=0;i<2;i++)
  {
    expectedPoint[i] = v[i]+point2[i]+offset[i];
  }

  if(transformedPoint != expectedPoint)
  {
    std::cout << "[FAILURE]" << std::endl;
    return EXIT_FAILURE;
  }
  else
  {
    std::cout << "[SUCCESS]" << std::endl;
  }

  std::cout << "Done!" << std::endl;

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include "test.hpp"

#include "conv_test.hpp"

//Note: The results of the tests have been validated with one of (octave/matlab/matlab)

// conv_2d_valid_multi

TEMPLATE_TEST_CASE_2("conv_2d_valid_multi/1", "[conv] [conv2]", Z, double, float) {
    etl::fast_matrix<Z, 3, 3> I    = {1.0, 2.0, 3.0, 0.0, 1.0, 1.0, 3.0, 2.0, 1.0};
    etl::fast_matrix<Z, 2, 2, 2> K = {2.0, 0.0, 0.5, 0.5, 2.0, 0.0, 0.5, 0.5};

    etl::fast_matrix<Z, 2, 2, 2> c_1;
    etl::fast_matrix<Z, 2, 2, 2> c_2;

    c_1(0) = conv_2d_valid(I, K(0));
    c_1(1) = conv_2d_valid(I, K(1));

    conv_2d_valid_multi(I, K, c_2);

    for (std::size_t i = 0; i < etl::size(c_1); ++i) {
        REQUIRE(c_1[i] == Approx(c_2[i]));
    }
}

TEMPLATE_TEST_CASE_2("conv_2d_valid_multi/2", "[conv] [conv2]", Z, double, float) {
    etl::fast_matrix<Z, 3, 3> I    = {1.0, 2.0, 3.0, 0.0, 1.0, 1.0, 3.0, 2.0, 1.0};
    etl::fast_matrix<Z, 2, 2, 2> K = {2.0, 0.0, 0.5, 0.5, 1.0, 0.5, 0.7, 0.1};

    etl::fast_matrix<Z, 2, 2, 2> c_1;
    etl::fast_matrix<Z, 2, 2, 2> c_2;

    c_1(0) = conv_2d_valid(I, K(0));
    c_1(1) = conv_2d_valid(I, K(1));

    conv_2d_valid_multi(I, K, c_2);

    for (std::size_t i = 0; i < etl::size(c_1); ++i) {
        REQUIRE(c_1[i] == Approx(c_2[i]));
    }
}

TEMPLATE_TEST_CASE_2("conv_2d_valid_multi/3", "[conv] [conv2]", Z, double, float) {
    etl::fast_matrix<Z, 3, 3> I    = {1.0, 2.0, 3.0, 0.0, 1.0, 1.0, 3.0, 2.0, 1.0};
    etl::fast_matrix<Z, 3, 2, 2> K = {2.0, 0.0, 0.5, 0.5, 1.0, 0.5, 0.7, 0.1, 0.0, -1.0, 1.0, 1.0};

    etl::fast_matrix<Z, 3, 2, 2> c_1;
    etl::fast_matrix<Z, 3, 2, 2> c_2;

    c_1(0) = conv_2d_valid(I, K(0));
    c_1(1) = conv_2d_valid(I, K(1));
    c_1(2) = conv_2d_valid(I, K(2));

    conv_2d_valid_multi(I, K, c_2);

    for (std::size_t i = 0; i < etl::size(c_1); ++i) {
        REQUIRE(c_1[i] == Approx(c_2[i]));
    }
}

TEMPLATE_TEST_CASE_2("conv_2d_valid_multi/4", "[conv] [conv2]", Z, double, float) {
    etl::fast_matrix<Z, 5, 5> I(etl::magic<Z>(5));
    etl::fast_matrix<Z, 3, 2, 2> K = {2.0, 0.0, 0.5, 0.5, 1.0, 0.5, 0.7, 0.1, 0.0, -1.0, 1.0, 1.0};

    etl::fast_matrix<Z, 3, 4, 4> c_1;
    etl::fast_matrix<Z, 3, 4, 4> c_2;

    c_1(0) = conv_2d_valid(I, K(0));
    c_1(1) = conv_2d_valid(I, K(1));
    c_1(2) = conv_2d_valid(I, K(2));

    conv_2d_valid_multi(I, K, c_2);

    for (std::size_t i = 0; i < etl::size(c_1); ++i) {
        REQUIRE(c_1[i] == Approx(c_2[i]));
    }
}

TEMPLATE_TEST_CASE_2("conv_2d_valid_multi/5", "[conv] [conv2]", Z, double, float) {
    etl::fast_matrix<Z, 5, 5> I(etl::magic<Z>(5));
    etl::fast_matrix<Z, 3, 3, 3> K;

    K(0) = etl::magic<Z>(3);
    K(1) = etl::magic<Z>(3) * 2.0;
    K(2) = etl::magic<Z>(3) * etl::magic<Z>(3);

    etl::fast_matrix<Z, 3, 3, 3> c_1;
    etl::fast_matrix<Z, 3, 3, 3> c_2;

    c_1(0) = conv_2d_valid(I, K(0));
    c_1(1) = conv_2d_valid(I, K(1));
    c_1(2) = conv_2d_valid(I, K(2));

    conv_2d_valid_multi(I, K, c_2);

    for (std::size_t i = 0; i < etl::size(c_1); ++i) {
        REQUIRE(c_1[i] == Approx(c_2[i]));
    }
}

TEMPLATE_TEST_CASE_2("conv_2d_valid_multi/6", "[conv] [conv2]", Z, double, float) {
    etl::fast_matrix<Z, 7, 7> I(etl::magic<Z>(7));
    etl::fast_matrix<Z, 3, 5, 3> K;

    K(0) = 1.5 * etl::sequence_generator(10);
    K(1) = -2.5 * etl::sequence_generator(5);
    K(2) = 1.3 * etl::sequence_generator(12);

    etl::fast_matrix<Z, 3, 3, 5> c_1;
    etl::fast_matrix<Z, 3, 3, 5> c_2;

    c_1(0) = conv_2d_valid(I, K(0));
    c_1(1) = conv_2d_valid(I, K(1));
    c_1(2) = conv_2d_valid(I, K(2));

    conv_2d_valid_multi(I, K, c_2);

    for (std::size_t i = 0; i < etl::size(c_1); ++i) {
        REQUIRE(c_1[i] == Approx(c_2[i]));
    }
}

TEMPLATE_TEST_CASE_2("conv_2d_valid_multi/7", "[conv] [conv2]", Z, double, float) {
    etl::fast_matrix<Z, 9, 7> I(0.5 * etl::sequence_generator(42));
    etl::fast_matrix<Z, 3, 5, 5> K;

    K(0) = 1.5 * etl::sequence_generator(10);
    K(1) = -2.5 * etl::sequence_generator(5);
    K(2) = 1.3 * etl::sequence_generator(12);

    etl::fast_matrix<Z, 3, 5, 3> c_1;
    etl::fast_matrix<Z, 3, 5, 3> c_2;

    c_1(0) = conv_2d_valid(I, K(0));
    c_1(1) = conv_2d_valid(I, K(1));
    c_1(2) = conv_2d_valid(I, K(2));

    conv_2d_valid_multi(I, K, c_2);

    for (std::size_t i = 0; i < etl::size(c_1); ++i) {
        REQUIRE(c_1[i] == Approx(c_2[i]));
    }
}

TEMPLATE_TEST_CASE_2("conv_2d_valid_multi/8", "[conv] [conv2]", Z, double, float) {
    etl::fast_matrix<Z, 9, 7> I(0.5 * etl::sequence_generator(42));
    etl::fast_matrix<Z, 3, 3, 5> K;

    K(0) = 1.5 * etl::sequence_generator(10);
    K(1) = -1.5 * etl::sequence_generator(5);
    K(2) = 1.3 * etl::sequence_generator(12);

    etl::fast_matrix<Z, 3, 7, 3> c_1;
    etl::fast_matrix<Z, 3, 7, 3> c_2;

    c_1(0) = conv_2d_valid(I, K(0));
    c_1(1) = conv_2d_valid(I, K(1));
    c_1(2) = conv_2d_valid(I, K(2));

    conv_2d_valid_multi(I, K, c_2);

    for (std::size_t i = 0; i < etl::size(c_1); ++i) {
        REQUIRE(c_1[i] == Approx(c_2[i]));
    }
}
<commit_msg>Fix the tests<commit_after>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include "test.hpp"

#include "conv_test.hpp"

//Note: The results of the tests have been validated with one of (octave/matlab/matlab)

// conv_2d_valid_multi

TEMPLATE_TEST_CASE_2("conv_2d_valid_multi/1", "[conv] [conv2]", Z, double, float) {
    etl::fast_matrix<Z, 3, 3> I    = {1.0, 2.0, 3.0, 0.0, 1.0, 1.0, 3.0, 2.0, 1.0};
    etl::fast_matrix<Z, 2, 2, 2> K = {2.0, 0.0, 0.5, 0.5, 2.0, 0.0, 0.5, 0.5};

    etl::fast_matrix<Z, 2, 2, 2> c_1;
    etl::fast_matrix<Z, 2, 2, 2> c_2;

    c_1(0) = conv_2d_valid(I, K(0));
    c_1(1) = conv_2d_valid(I, K(1));

    conv_2d_valid_multi(I, K, c_2);

    for (std::size_t i = 0; i < etl::size(c_1); ++i) {
        REQUIRE(c_1[i] == Approx(c_2[i]));
    }
}

TEMPLATE_TEST_CASE_2("conv_2d_valid_multi/2", "[conv] [conv2]", Z, double, float) {
    etl::fast_matrix<Z, 3, 3> I    = {1.0, 2.0, 3.0, 0.0, 1.0, 1.0, 3.0, 2.0, 1.0};
    etl::fast_matrix<Z, 2, 2, 2> K = {2.0, 0.0, 0.5, 0.5, 1.0, 0.5, 0.7, 0.1};

    etl::fast_matrix<Z, 2, 2, 2> c_1;
    etl::fast_matrix<Z, 2, 2, 2> c_2;

    c_1(0) = conv_2d_valid(I, K(0));
    c_1(1) = conv_2d_valid(I, K(1));

    conv_2d_valid_multi(I, K, c_2);

    for (std::size_t i = 0; i < etl::size(c_1); ++i) {
        REQUIRE(c_1[i] == Approx(c_2[i]));
    }
}

TEMPLATE_TEST_CASE_2("conv_2d_valid_multi/3", "[conv] [conv2]", Z, double, float) {
    etl::fast_matrix<Z, 3, 3> I    = {1.0, 2.0, 3.0, 0.0, 1.0, 1.0, 3.0, 2.0, 1.0};
    etl::fast_matrix<Z, 3, 2, 2> K = {2.0, 0.0, 0.5, 0.5, 1.0, 0.5, 0.7, 0.1, 0.0, -1.0, 1.0, 1.0};

    etl::fast_matrix<Z, 3, 2, 2> c_1;
    etl::fast_matrix<Z, 3, 2, 2> c_2;

    c_1(0) = conv_2d_valid(I, K(0));
    c_1(1) = conv_2d_valid(I, K(1));
    c_1(2) = conv_2d_valid(I, K(2));

    conv_2d_valid_multi(I, K, c_2);

    for (std::size_t i = 0; i < etl::size(c_1); ++i) {
        REQUIRE(c_1[i] == Approx(c_2[i]));
    }
}

TEMPLATE_TEST_CASE_2("conv_2d_valid_multi/4", "[conv] [conv2]", Z, double, float) {
    etl::fast_matrix<Z, 5, 5> I(etl::magic<Z>(5));
    etl::fast_matrix<Z, 3, 2, 2> K = {2.0, 0.0, 0.5, 0.5, 1.0, 0.5, 0.7, 0.1, 0.0, -1.0, 1.0, 1.0};

    etl::fast_matrix<Z, 3, 4, 4> c_1;
    etl::fast_matrix<Z, 3, 4, 4> c_2;

    c_1(0) = conv_2d_valid(I, K(0));
    c_1(1) = conv_2d_valid(I, K(1));
    c_1(2) = conv_2d_valid(I, K(2));

    conv_2d_valid_multi(I, K, c_2);

    for (std::size_t i = 0; i < etl::size(c_1); ++i) {
        REQUIRE(c_1[i] == Approx(c_2[i]));
    }
}

TEMPLATE_TEST_CASE_2("conv_2d_valid_multi/5", "[conv] [conv2]", Z, double, float) {
    etl::fast_matrix<Z, 5, 5> I(etl::magic<Z>(5));
    etl::fast_matrix<Z, 3, 3, 3> K;

    K(0) = etl::magic<Z>(3);
    K(1) = etl::magic<Z>(3) * 2.0;
    K(2) = etl::magic<Z>(3) * etl::magic<Z>(3);

    etl::fast_matrix<Z, 3, 3, 3> c_1;
    etl::fast_matrix<Z, 3, 3, 3> c_2;

    c_1(0) = conv_2d_valid(I, K(0));
    c_1(1) = conv_2d_valid(I, K(1));
    c_1(2) = conv_2d_valid(I, K(2));

    conv_2d_valid_multi(I, K, c_2);

    for (std::size_t i = 0; i < etl::size(c_1); ++i) {
        REQUIRE(c_1[i] == Approx(c_2[i]));
    }
}

TEMPLATE_TEST_CASE_2("conv_2d_valid_multi/6", "[conv] [conv2]", Z, double, float) {
    etl::fast_matrix<Z, 7, 7> I(etl::magic<Z>(7));
    etl::fast_matrix<Z, 3, 5, 3> K;

    K(0) = 1.5 * etl::sequence_generator(10.0);
    K(1) = -2.5 * etl::sequence_generator(5.0);
    K(2) = 1.3 * etl::sequence_generator(12.0);

    etl::fast_matrix<Z, 3, 3, 5> c_1;
    etl::fast_matrix<Z, 3, 3, 5> c_2;

    c_1(0) = conv_2d_valid(I, K(0));
    c_1(1) = conv_2d_valid(I, K(1));
    c_1(2) = conv_2d_valid(I, K(2));

    conv_2d_valid_multi(I, K, c_2);

    for (std::size_t i = 0; i < etl::size(c_1); ++i) {
        REQUIRE(c_1[i] == Approx(c_2[i]));
    }
}

TEMPLATE_TEST_CASE_2("conv_2d_valid_multi/7", "[conv] [conv2]", Z, double, float) {
    etl::fast_matrix<Z, 9, 7> I(0.5 * etl::sequence_generator(42.0));
    etl::fast_matrix<Z, 3, 5, 5> K;

    K(0) = 1.5 * etl::sequence_generator(10.0);
    K(1) = -2.5 * etl::sequence_generator(5.0);
    K(2) = 1.3 * etl::sequence_generator(12.0);

    etl::fast_matrix<Z, 3, 5, 3> c_1;
    etl::fast_matrix<Z, 3, 5, 3> c_2;

    c_1(0) = conv_2d_valid(I, K(0));
    c_1(1) = conv_2d_valid(I, K(1));
    c_1(2) = conv_2d_valid(I, K(2));

    conv_2d_valid_multi(I, K, c_2);

    for (std::size_t i = 0; i < etl::size(c_1); ++i) {
        REQUIRE(c_1[i] == Approx(c_2[i]));
    }
}

TEMPLATE_TEST_CASE_2("conv_2d_valid_multi/8", "[conv] [conv2]", Z, double, float) {
    etl::fast_matrix<Z, 9, 7> I(0.5 * etl::sequence_generator(42.0));
    etl::fast_matrix<Z, 3, 3, 5> K;

    K(0) = 1.5 * etl::sequence_generator(10.0);
    K(1) = -1.5 * etl::sequence_generator(5.0);
    K(2) = 1.3 * etl::sequence_generator(12.0);

    etl::fast_matrix<Z, 3, 7, 3> c_1;
    etl::fast_matrix<Z, 3, 7, 3> c_2;

    c_1(0) = conv_2d_valid(I, K(0));
    c_1(1) = conv_2d_valid(I, K(1));
    c_1(2) = conv_2d_valid(I, K(2));

    conv_2d_valid_multi(I, K, c_2);

    for (std::size_t i = 0; i < etl::size(c_1); ++i) {
        REQUIRE(c_1[i] == Approx(c_2[i]));
    }
}
<|endoftext|>


<commit_before>#include "DeviceRegistry.h"
#include "register.h"

namespace ZPUino {

    int DeviceRegistry::registerDevice(int slot) {
        if (slot>=MAX_SLOTS)
            return -2;
        if (m_sDeviceRegistry & (1<<slot))
            return -1;
        m_sDeviceRegistry |= (1<<slot);
        return 0;
    }

    uint8_t DeviceRegistry::scanDevice(unsigned vendor, unsigned product, int instance) {
        int i;
        for (i=0;i!=16;i++) {
            unsigned val = REGISTER(SYSCTLBASE,16+i);
            if (val!=0) {
                if (vendor!=VENDOR_ANY) {
                    if (vendor != ((val>>8)&0xff))
                        continue; /* No match */
                }
                if (product!=PRODUCT_ANY) {
                    if (product != (val&0xff))
                        continue; /* No match */
                }
                if (isRegistered(i))
                {
                    --instance;
                    continue;
                }

                if ((instance==0xff) || (--instance)==0)
                    return i;
            }
        }
        return NO_DEVICE;
    }

    int DeviceRegistry::getPPSInputPin(int masterslot, int offset)
    {
        return getPPSPin(masterslot,offset,16);
    }

    int DeviceRegistry::getPPSOutputPin(int masterslot, int offset)
    {
        return getPPSPin(masterslot,offset,0);
    }

    int DeviceRegistry::getPPSPin(int masterslot, int offset, int shift)
    {
        unsigned count = REGISTER(SYSCTLBASE, 32+shift);
        unsigned start = -1;
        register_t startreg = &REGISTER(SYSCTLBASE, 64);

        while(count--) {
            start++;
            unsigned val = *startreg++;
            unsigned char dev = (val>>shift)&0xff;
            if (dev!=masterslot) {
                continue;
            } else {
                int pin = (val>>(8+shift))&0xff;
                if (offset==0)
                    return start;
                offset--;
            }
        }
        return -1;
    }

    uint32_t DeviceRegistry::m_sDeviceRegistry = 0;
};
<commit_msg>Code cleanup, remove unused variable (???)<commit_after>#include "DeviceRegistry.h"
#include "register.h"

namespace ZPUino {

    int DeviceRegistry::registerDevice(int slot) {
        if (slot>=MAX_SLOTS)
            return -2;
        if (m_sDeviceRegistry & (1<<slot))
            return -1;
        m_sDeviceRegistry |= (1<<slot);
        return 0;
    }

    uint8_t DeviceRegistry::scanDevice(unsigned vendor, unsigned product, int instance) {
        int i;
        for (i=0;i!=16;i++) {
            unsigned val = REGISTER(SYSCTLBASE,16+i);
            if (val!=0) {
                if (vendor!=VENDOR_ANY) {
                    if (vendor != ((val>>8)&0xff))
                        continue; /* No match */
                }
                if (product!=PRODUCT_ANY) {
                    if (product != (val&0xff))
                        continue; /* No match */
                }
                if (isRegistered(i))
                {
                    --instance;
                    continue;
                }

                if ((instance==0xff) || (--instance)==0)
                    return i;
            }
        }
        return NO_DEVICE;
    }

    int DeviceRegistry::getPPSInputPin(int masterslot, int offset)
    {
        return getPPSPin(masterslot,offset,16);
    }

    int DeviceRegistry::getPPSOutputPin(int masterslot, int offset)
    {
        return getPPSPin(masterslot,offset,0);
    }

    int DeviceRegistry::getPPSPin(int masterslot, int offset, int shift)
    {
        unsigned count = REGISTER(SYSCTLBASE, 32+shift);
        unsigned start = (unsigned)-1;
        register_t startreg = &REGISTER(SYSCTLBASE, 64);

        while(count--) {
            start++;
            unsigned val = *startreg++;
            unsigned char dev = (val>>shift)&0xff;
            if (dev!=masterslot) {
                continue;
            } else {
                //int pin = (val>>(8+shift))&0xff;
                if (offset==0)
                    return start;
                offset--;
            }
        }
        return -1;
    }

    uint32_t DeviceRegistry::m_sDeviceRegistry = 0;
};
<|endoftext|>


<commit_before>/*
 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
 *           (C) 2004-2005 Allan Sandfeld Jensen (kde@carewolf.com)
 * Copyright (C) 2006, 2007 Nicholas Shanks (webkit@nickshanks.com)
 * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
 * Copyright (C) 2007 Alexey Proskuryakov <ap@webkit.org>
 * Copyright (C) 2007, 2008 Eric Seidel <eric@webkit.org>
 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
 * Copyright (c) 2011, Code Aurora Forum. All rights reserved.
 * Copyright (C) Research In Motion Limited 2011. All rights reserved.
 * Copyright (C) 2012 Google Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; 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 "config.h"
#include "core/css/CSSDefaultStyleSheets.h"

#include "UserAgentStyleSheets.h"
#include "core/css/MediaQueryEvaluator.h"
#include "core/css/RuleSet.h"
#include "core/css/StyleSheetContents.h"
#include "core/dom/FullscreenElementStack.h"
#include "core/html/HTMLAnchorElement.h"
#include "core/html/HTMLHtmlElement.h"
#include "core/html/HTMLVideoElement.h"
#include "core/rendering/RenderTheme.h"

namespace WebCore {

using namespace HTMLNames;

RuleSet* CSSDefaultStyleSheets::defaultStyle;
RuleSet* CSSDefaultStyleSheets::defaultQuirksStyle;
RuleSet* CSSDefaultStyleSheets::defaultPrintStyle;
RuleSet* CSSDefaultStyleSheets::defaultViewSourceStyle;
RuleSet* CSSDefaultStyleSheets::defaultXHTMLMobileProfileStyle;

StyleSheetContents* CSSDefaultStyleSheets::simpleDefaultStyleSheet;
StyleSheetContents* CSSDefaultStyleSheets::defaultStyleSheet;
StyleSheetContents* CSSDefaultStyleSheets::quirksStyleSheet;
StyleSheetContents* CSSDefaultStyleSheets::svgStyleSheet;
StyleSheetContents* CSSDefaultStyleSheets::mediaControlsStyleSheet;
StyleSheetContents* CSSDefaultStyleSheets::fullscreenStyleSheet;

// FIXME: It would be nice to use some mechanism that guarantees this is in sync with the real UA stylesheet.
static const char* simpleUserAgentStyleSheet = "html,body,div{display:block}head{display:none}body{margin:8px}div:focus,span:focus,a:focus{outline:auto 5px -webkit-focus-ring-color}a:-webkit-any-link{color:-webkit-link;text-decoration:underline}a:-webkit-any-link:active{color:-webkit-activelink}body:-webkit-seamless-document{margin:0}body:-webkit-full-page-media{background-color:black}@viewport{min-width:980px}";

static inline bool elementCanUseSimpleDefaultStyle(Element* e)
{
    return isHTMLHtmlElement(e) || e->hasTagName(headTag) || e->hasTagName(bodyTag) || e->hasTagName(divTag) || e->hasTagName(spanTag) || e->hasTagName(brTag) || isHTMLAnchorElement(e);
}

static const MediaQueryEvaluator& screenEval()
{
    DEFINE_STATIC_LOCAL(const MediaQueryEvaluator, staticScreenEval, ("screen"));
    return staticScreenEval;
}

static const MediaQueryEvaluator& printEval()
{
    DEFINE_STATIC_LOCAL(const MediaQueryEvaluator, staticPrintEval, ("print"));
    return staticPrintEval;
}

static StyleSheetContents* parseUASheet(const String& str)
{
    StyleSheetContents* sheet = StyleSheetContents::create(CSSParserContext(UASheetMode)).leakRef(); // leak the sheet on purpose
    sheet->parseString(str);
    return sheet;
}

static StyleSheetContents* parseUASheet(const char* characters, unsigned size)
{
    return parseUASheet(String(characters, size));
}

void CSSDefaultStyleSheets::initDefaultStyle(Element* root)
{
    if (!defaultStyle) {
        if (!root || elementCanUseSimpleDefaultStyle(root))
            loadSimpleDefaultStyle();
        else
            loadFullDefaultStyle();
    }
}

void CSSDefaultStyleSheets::loadFullDefaultStyle()
{
    if (simpleDefaultStyleSheet) {
        ASSERT(defaultStyle);
        ASSERT(defaultPrintStyle == defaultStyle);
        delete defaultStyle;
        simpleDefaultStyleSheet->deref();
        defaultStyle = RuleSet::create().leakPtr();
        defaultPrintStyle = RuleSet::create().leakPtr();
        simpleDefaultStyleSheet = 0;
    } else {
        ASSERT(!defaultStyle);
        defaultStyle = RuleSet::create().leakPtr();
        defaultPrintStyle = RuleSet::create().leakPtr();
        defaultQuirksStyle = RuleSet::create().leakPtr();
    }

    // Strict-mode rules.
    String defaultRules = String(htmlUserAgentStyleSheet, sizeof(htmlUserAgentStyleSheet)) + RenderTheme::theme().extraDefaultStyleSheet();
    defaultStyleSheet = parseUASheet(defaultRules);
    defaultStyle->addRulesFromSheet(defaultStyleSheet, screenEval());
    defaultPrintStyle->addRulesFromSheet(defaultStyleSheet, printEval());

    // Quirks-mode rules.
    String quirksRules = String(quirksUserAgentStyleSheet, sizeof(quirksUserAgentStyleSheet)) + RenderTheme::theme().extraQuirksStyleSheet();
    quirksStyleSheet = parseUASheet(quirksRules);
    defaultQuirksStyle->addRulesFromSheet(quirksStyleSheet, screenEval());
}

void CSSDefaultStyleSheets::loadSimpleDefaultStyle()
{
    ASSERT(!defaultStyle);
    ASSERT(!simpleDefaultStyleSheet);

    defaultStyle = RuleSet::create().leakPtr();
    // There are no media-specific rules in the simple default style.
    defaultPrintStyle = defaultStyle;
    defaultQuirksStyle = RuleSet::create().leakPtr();

    simpleDefaultStyleSheet = parseUASheet(simpleUserAgentStyleSheet, strlen(simpleUserAgentStyleSheet));
    defaultStyle->addRulesFromSheet(simpleDefaultStyleSheet, screenEval());

    // No need to initialize quirks sheet yet as there are no quirk rules for elements allowed in simple default style.
}

RuleSet* CSSDefaultStyleSheets::viewSourceStyle()
{
    if (!defaultViewSourceStyle) {
        defaultViewSourceStyle = RuleSet::create().leakPtr();
        defaultViewSourceStyle->addRulesFromSheet(parseUASheet(sourceUserAgentStyleSheet, sizeof(sourceUserAgentStyleSheet)), screenEval());
    }
    return defaultViewSourceStyle;
}

RuleSet* CSSDefaultStyleSheets::xhtmlMobileProfileStyle()
{
    if (!defaultXHTMLMobileProfileStyle) {
        defaultXHTMLMobileProfileStyle = RuleSet::create().leakPtr();
        defaultXHTMLMobileProfileStyle->addRulesFromSheet(parseUASheet(xhtmlmpUserAgentStyleSheet, sizeof(xhtmlmpUserAgentStyleSheet)), screenEval());
    }
    return defaultXHTMLMobileProfileStyle;
}

void CSSDefaultStyleSheets::ensureDefaultStyleSheetsForElement(Element* element, bool& changedDefaultStyle)
{
    if (simpleDefaultStyleSheet && !elementCanUseSimpleDefaultStyle(element)) {
        loadFullDefaultStyle();
        changedDefaultStyle = true;
    }

    // FIXME: We should assert that the sheet only styles SVG elements.
    if (element->isSVGElement() && !svgStyleSheet) {
        svgStyleSheet = parseUASheet(svgUserAgentStyleSheet, sizeof(svgUserAgentStyleSheet));
        defaultStyle->addRulesFromSheet(svgStyleSheet, screenEval());
        defaultPrintStyle->addRulesFromSheet(svgStyleSheet, printEval());
        changedDefaultStyle = true;
    }

    // FIXME: We should assert that this sheet only contains rules for <video> and <audio>.
    if (!mediaControlsStyleSheet && (isHTMLVideoElement(element) || element->hasTagName(audioTag))) {
        String mediaRules = String(mediaControlsUserAgentStyleSheet, sizeof(mediaControlsUserAgentStyleSheet)) + RenderTheme::theme().extraMediaControlsStyleSheet();
        mediaControlsStyleSheet = parseUASheet(mediaRules);
        defaultStyle->addRulesFromSheet(mediaControlsStyleSheet, screenEval());
        defaultPrintStyle->addRulesFromSheet(mediaControlsStyleSheet, printEval());
        changedDefaultStyle = true;
    }

    // FIXME: This only works because we Force recalc the entire document so the new sheet
    // is loaded for <html> and the correct styles apply to everyone.
    if (!fullscreenStyleSheet && FullscreenElementStack::isFullScreen(&element->document())) {
        String fullscreenRules = String(fullscreenUserAgentStyleSheet, sizeof(fullscreenUserAgentStyleSheet)) + RenderTheme::theme().extraFullScreenStyleSheet();
        fullscreenStyleSheet = parseUASheet(fullscreenRules);
        defaultStyle->addRulesFromSheet(fullscreenStyleSheet, screenEval());
        defaultQuirksStyle->addRulesFromSheet(fullscreenStyleSheet, screenEval());
        changedDefaultStyle = true;
    }

    ASSERT(defaultStyle->features().idsInRules.isEmpty());
    ASSERT(defaultStyle->features().siblingRules.isEmpty());
}

} // namespace WebCore
<commit_msg>@page rule missing from simpleUserAgentStyleSheet.<commit_after>/*
 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
 *           (C) 2004-2005 Allan Sandfeld Jensen (kde@carewolf.com)
 * Copyright (C) 2006, 2007 Nicholas Shanks (webkit@nickshanks.com)
 * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
 * Copyright (C) 2007 Alexey Proskuryakov <ap@webkit.org>
 * Copyright (C) 2007, 2008 Eric Seidel <eric@webkit.org>
 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
 * Copyright (c) 2011, Code Aurora Forum. All rights reserved.
 * Copyright (C) Research In Motion Limited 2011. All rights reserved.
 * Copyright (C) 2012 Google Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; 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 "config.h"
#include "core/css/CSSDefaultStyleSheets.h"

#include "UserAgentStyleSheets.h"
#include "core/css/MediaQueryEvaluator.h"
#include "core/css/RuleSet.h"
#include "core/css/StyleSheetContents.h"
#include "core/dom/FullscreenElementStack.h"
#include "core/html/HTMLAnchorElement.h"
#include "core/html/HTMLHtmlElement.h"
#include "core/html/HTMLVideoElement.h"
#include "core/rendering/RenderTheme.h"

namespace WebCore {

using namespace HTMLNames;

RuleSet* CSSDefaultStyleSheets::defaultStyle;
RuleSet* CSSDefaultStyleSheets::defaultQuirksStyle;
RuleSet* CSSDefaultStyleSheets::defaultPrintStyle;
RuleSet* CSSDefaultStyleSheets::defaultViewSourceStyle;
RuleSet* CSSDefaultStyleSheets::defaultXHTMLMobileProfileStyle;

StyleSheetContents* CSSDefaultStyleSheets::simpleDefaultStyleSheet;
StyleSheetContents* CSSDefaultStyleSheets::defaultStyleSheet;
StyleSheetContents* CSSDefaultStyleSheets::quirksStyleSheet;
StyleSheetContents* CSSDefaultStyleSheets::svgStyleSheet;
StyleSheetContents* CSSDefaultStyleSheets::mediaControlsStyleSheet;
StyleSheetContents* CSSDefaultStyleSheets::fullscreenStyleSheet;

// FIXME: It would be nice to use some mechanism that guarantees this is in sync with the real UA stylesheet.
static const char* simpleUserAgentStyleSheet = "html,body,div{display:block}head{display:none}body{margin:8px}div:focus,span:focus,a:focus{outline:auto 5px -webkit-focus-ring-color}a:-webkit-any-link{color:-webkit-link;text-decoration:underline}a:-webkit-any-link:active{color:-webkit-activelink}body:-webkit-seamless-document{margin:0}body:-webkit-full-page-media{background-color:black}@viewport{min-width:980px}@page{size:auto;margin:auto;padding:0;border-width:0}";

static inline bool elementCanUseSimpleDefaultStyle(Element* e)
{
    return isHTMLHtmlElement(e) || e->hasTagName(headTag) || e->hasTagName(bodyTag) || e->hasTagName(divTag) || e->hasTagName(spanTag) || e->hasTagName(brTag) || isHTMLAnchorElement(e);
}

static const MediaQueryEvaluator& screenEval()
{
    DEFINE_STATIC_LOCAL(const MediaQueryEvaluator, staticScreenEval, ("screen"));
    return staticScreenEval;
}

static const MediaQueryEvaluator& printEval()
{
    DEFINE_STATIC_LOCAL(const MediaQueryEvaluator, staticPrintEval, ("print"));
    return staticPrintEval;
}

static StyleSheetContents* parseUASheet(const String& str)
{
    StyleSheetContents* sheet = StyleSheetContents::create(CSSParserContext(UASheetMode)).leakRef(); // leak the sheet on purpose
    sheet->parseString(str);
    return sheet;
}

static StyleSheetContents* parseUASheet(const char* characters, unsigned size)
{
    return parseUASheet(String(characters, size));
}

void CSSDefaultStyleSheets::initDefaultStyle(Element* root)
{
    if (!defaultStyle) {
        if (!root || elementCanUseSimpleDefaultStyle(root))
            loadSimpleDefaultStyle();
        else
            loadFullDefaultStyle();
    }
}

void CSSDefaultStyleSheets::loadFullDefaultStyle()
{
    if (simpleDefaultStyleSheet) {
        ASSERT(defaultStyle);
        ASSERT(defaultPrintStyle == defaultStyle);
        delete defaultStyle;
        simpleDefaultStyleSheet->deref();
        defaultStyle = RuleSet::create().leakPtr();
        defaultPrintStyle = RuleSet::create().leakPtr();
        simpleDefaultStyleSheet = 0;
    } else {
        ASSERT(!defaultStyle);
        defaultStyle = RuleSet::create().leakPtr();
        defaultPrintStyle = RuleSet::create().leakPtr();
        defaultQuirksStyle = RuleSet::create().leakPtr();
    }

    // Strict-mode rules.
    String defaultRules = String(htmlUserAgentStyleSheet, sizeof(htmlUserAgentStyleSheet)) + RenderTheme::theme().extraDefaultStyleSheet();
    defaultStyleSheet = parseUASheet(defaultRules);
    defaultStyle->addRulesFromSheet(defaultStyleSheet, screenEval());
    defaultPrintStyle->addRulesFromSheet(defaultStyleSheet, printEval());

    // Quirks-mode rules.
    String quirksRules = String(quirksUserAgentStyleSheet, sizeof(quirksUserAgentStyleSheet)) + RenderTheme::theme().extraQuirksStyleSheet();
    quirksStyleSheet = parseUASheet(quirksRules);
    defaultQuirksStyle->addRulesFromSheet(quirksStyleSheet, screenEval());
}

void CSSDefaultStyleSheets::loadSimpleDefaultStyle()
{
    ASSERT(!defaultStyle);
    ASSERT(!simpleDefaultStyleSheet);

    defaultStyle = RuleSet::create().leakPtr();
    // There are no media-specific rules in the simple default style.
    defaultPrintStyle = defaultStyle;
    defaultQuirksStyle = RuleSet::create().leakPtr();

    simpleDefaultStyleSheet = parseUASheet(simpleUserAgentStyleSheet, strlen(simpleUserAgentStyleSheet));
    defaultStyle->addRulesFromSheet(simpleDefaultStyleSheet, screenEval());

    // No need to initialize quirks sheet yet as there are no quirk rules for elements allowed in simple default style.
}

RuleSet* CSSDefaultStyleSheets::viewSourceStyle()
{
    if (!defaultViewSourceStyle) {
        defaultViewSourceStyle = RuleSet::create().leakPtr();
        defaultViewSourceStyle->addRulesFromSheet(parseUASheet(sourceUserAgentStyleSheet, sizeof(sourceUserAgentStyleSheet)), screenEval());
    }
    return defaultViewSourceStyle;
}

RuleSet* CSSDefaultStyleSheets::xhtmlMobileProfileStyle()
{
    if (!defaultXHTMLMobileProfileStyle) {
        defaultXHTMLMobileProfileStyle = RuleSet::create().leakPtr();
        defaultXHTMLMobileProfileStyle->addRulesFromSheet(parseUASheet(xhtmlmpUserAgentStyleSheet, sizeof(xhtmlmpUserAgentStyleSheet)), screenEval());
    }
    return defaultXHTMLMobileProfileStyle;
}

void CSSDefaultStyleSheets::ensureDefaultStyleSheetsForElement(Element* element, bool& changedDefaultStyle)
{
    if (simpleDefaultStyleSheet && !elementCanUseSimpleDefaultStyle(element)) {
        loadFullDefaultStyle();
        changedDefaultStyle = true;
    }

    // FIXME: We should assert that the sheet only styles SVG elements.
    if (element->isSVGElement() && !svgStyleSheet) {
        svgStyleSheet = parseUASheet(svgUserAgentStyleSheet, sizeof(svgUserAgentStyleSheet));
        defaultStyle->addRulesFromSheet(svgStyleSheet, screenEval());
        defaultPrintStyle->addRulesFromSheet(svgStyleSheet, printEval());
        changedDefaultStyle = true;
    }

    // FIXME: We should assert that this sheet only contains rules for <video> and <audio>.
    if (!mediaControlsStyleSheet && (isHTMLVideoElement(element) || element->hasTagName(audioTag))) {
        String mediaRules = String(mediaControlsUserAgentStyleSheet, sizeof(mediaControlsUserAgentStyleSheet)) + RenderTheme::theme().extraMediaControlsStyleSheet();
        mediaControlsStyleSheet = parseUASheet(mediaRules);
        defaultStyle->addRulesFromSheet(mediaControlsStyleSheet, screenEval());
        defaultPrintStyle->addRulesFromSheet(mediaControlsStyleSheet, printEval());
        changedDefaultStyle = true;
    }

    // FIXME: This only works because we Force recalc the entire document so the new sheet
    // is loaded for <html> and the correct styles apply to everyone.
    if (!fullscreenStyleSheet && FullscreenElementStack::isFullScreen(&element->document())) {
        String fullscreenRules = String(fullscreenUserAgentStyleSheet, sizeof(fullscreenUserAgentStyleSheet)) + RenderTheme::theme().extraFullScreenStyleSheet();
        fullscreenStyleSheet = parseUASheet(fullscreenRules);
        defaultStyle->addRulesFromSheet(fullscreenStyleSheet, screenEval());
        defaultQuirksStyle->addRulesFromSheet(fullscreenStyleSheet, screenEval());
        changedDefaultStyle = true;
    }

    ASSERT(defaultStyle->features().idsInRules.isEmpty());
    ASSERT(defaultStyle->features().siblingRules.isEmpty());
}

} // namespace WebCore
<|endoftext|>


<commit_before>/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include <algorithm>
#include <unordered_set>

#include "paddle/fluid/framework/ir/graph_viz_pass.h"
#include "paddle/fluid/inference/analysis/dot.h"
#include "paddle/fluid/framework/op_proto_maker.h"
#include "paddle/fluid/string/printf.h"

namespace paddle {
namespace framework {
namespace ir {
using inference::analysis::Dot;
namespace {
const char kGraphVizPath[] = "graph_viz_path";

std::string FormatName(const Node* op) {
  if (!op->Op() ||
      !op->Op()->HasAttr(OpProtoAndCheckerMaker::OpNamescopeAttrName())) {
    return op->Name();
  }
  const std::string full_scope = boost::get<std::string>(
      op->Op()->GetAttr(OpProtoAndCheckerMaker::OpNamescopeAttrName()));
  return string::Sprintf("%s%s", full_scope.c_str(), op->Name().c_str());
}
}  // namespace

std::unique_ptr<ir::Graph> GraphVizPass::ApplyImpl(
    std::unique_ptr<ir::Graph> graph) const {
  const std::string graph_viz_path = Get<std::string>(kGraphVizPath);
  VLOG(3) << "draw IR graph viz to " << graph_viz_path;
  std::unique_ptr<std::ostream> fout(new std::ofstream(graph_viz_path));
  PADDLE_ENFORCE(fout->good());
  std::ostream& sout = *fout;

  std::unordered_map<const ir::Node*, std::string> node2dot;

  Dot dot;

  std::vector<Dot::Attr> op_attrs({Dot::Attr("style", "filled"),
                                   Dot::Attr("shape", "box"),
                                   Dot::Attr("fillcolor", "red")});
  std::vector<Dot::Attr> var_attrs({Dot::Attr("style", "filled,rounded"),
                                    // Dot::Attr("shape", "diamond"),
                                    Dot::Attr("fillcolor", "yellow")});

  std::vector<Dot::Attr> marked_op_attrs({Dot::Attr("style", "filled"),
                                          Dot::Attr("shape", "box"),
                                          Dot::Attr("fillcolor", "lightgray")});
  std::vector<Dot::Attr> marked_var_attrs(
      {Dot::Attr("style", "filled,rounded"),
       // Dot::Attr("shape", "diamond"),
       Dot::Attr("fillcolor", "lightgray")});

  auto marked_nodes = ConsumeMarkedNodes(graph.get());
  // Create nodes
  for (const Node* n : graph->Nodes()) {
    std::string node_id = FormatName(n) + "(" + std::to_string(n->id()) + ")";
    if (n->IsOp()) {
      decltype(op_attrs) attr =
          marked_nodes.count(n) ? marked_op_attrs : op_attrs;
      dot.AddNode(node_id, attr, node_id);
    } else if (n->IsVar()) {
      decltype(op_attrs) attr =
          marked_nodes.count(n) ? marked_var_attrs : var_attrs;
      dot.AddNode(node_id, attr, node_id);
    }
    node2dot[n] = node_id;
  }
  // Create edges
  for (const Node* n : graph->Nodes()) {
    const auto& src_id = node2dot.at(n);
    for (auto* out : n->outputs) {
      const auto& trg_id = node2dot.at(out);
      dot.AddEdge(src_id, trg_id, {});
    }
  }

  sout << dot.Build();

  return graph;
}

GraphVizPass::marked_nodes_t GraphVizPass::ConsumeMarkedNodes(
    Graph* graph) const {
  marked_nodes_t res;
  if (graph->Has(kGraphvizMarkedNodeAttr)) {
    auto& attr = graph->Get<marked_nodes_t>(kGraphvizMarkedNodeAttr);
    res = attr;
    attr.clear();
  }
  return res;
}

}  // namespace ir
}  // namespace framework
}  // namespace paddle

REGISTER_PASS(graph_viz_pass, paddle::framework::ir::GraphVizPass)
    .RequirePassAttr(paddle::framework::ir::kGraphVizPath);
<commit_msg>fix style<commit_after>/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include <algorithm>
#include <unordered_set>

#include "paddle/fluid/framework/ir/graph_viz_pass.h"
#include "paddle/fluid/framework/op_proto_maker.h"
#include "paddle/fluid/inference/analysis/dot.h"
#include "paddle/fluid/string/printf.h"

namespace paddle {
namespace framework {
namespace ir {
using inference::analysis::Dot;
namespace {
const char kGraphVizPath[] = "graph_viz_path";

std::string FormatName(const Node* op) {
  if (!op->Op() ||
      !op->Op()->HasAttr(OpProtoAndCheckerMaker::OpNamescopeAttrName())) {
    return op->Name();
  }
  const std::string full_scope = boost::get<std::string>(
      op->Op()->GetAttr(OpProtoAndCheckerMaker::OpNamescopeAttrName()));
  return string::Sprintf("%s%s", full_scope.c_str(), op->Name().c_str());
}
}  // namespace

std::unique_ptr<ir::Graph> GraphVizPass::ApplyImpl(
    std::unique_ptr<ir::Graph> graph) const {
  const std::string graph_viz_path = Get<std::string>(kGraphVizPath);
  VLOG(3) << "draw IR graph viz to " << graph_viz_path;
  std::unique_ptr<std::ostream> fout(new std::ofstream(graph_viz_path));
  PADDLE_ENFORCE(fout->good());
  std::ostream& sout = *fout;

  std::unordered_map<const ir::Node*, std::string> node2dot;

  Dot dot;

  std::vector<Dot::Attr> op_attrs({Dot::Attr("style", "filled"),
                                   Dot::Attr("shape", "box"),
                                   Dot::Attr("fillcolor", "red")});
  std::vector<Dot::Attr> var_attrs({Dot::Attr("style", "filled,rounded"),
                                    // Dot::Attr("shape", "diamond"),
                                    Dot::Attr("fillcolor", "yellow")});

  std::vector<Dot::Attr> marked_op_attrs({Dot::Attr("style", "filled"),
                                          Dot::Attr("shape", "box"),
                                          Dot::Attr("fillcolor", "lightgray")});
  std::vector<Dot::Attr> marked_var_attrs(
      {Dot::Attr("style", "filled,rounded"),
       // Dot::Attr("shape", "diamond"),
       Dot::Attr("fillcolor", "lightgray")});

  auto marked_nodes = ConsumeMarkedNodes(graph.get());
  // Create nodes
  for (const Node* n : graph->Nodes()) {
    std::string node_id = FormatName(n) + "(" + std::to_string(n->id()) + ")";
    if (n->IsOp()) {
      decltype(op_attrs) attr =
          marked_nodes.count(n) ? marked_op_attrs : op_attrs;
      dot.AddNode(node_id, attr, node_id);
    } else if (n->IsVar()) {
      decltype(op_attrs) attr =
          marked_nodes.count(n) ? marked_var_attrs : var_attrs;
      dot.AddNode(node_id, attr, node_id);
    }
    node2dot[n] = node_id;
  }
  // Create edges
  for (const Node* n : graph->Nodes()) {
    const auto& src_id = node2dot.at(n);
    for (auto* out : n->outputs) {
      const auto& trg_id = node2dot.at(out);
      dot.AddEdge(src_id, trg_id, {});
    }
  }

  sout << dot.Build();

  return graph;
}

GraphVizPass::marked_nodes_t GraphVizPass::ConsumeMarkedNodes(
    Graph* graph) const {
  marked_nodes_t res;
  if (graph->Has(kGraphvizMarkedNodeAttr)) {
    auto& attr = graph->Get<marked_nodes_t>(kGraphvizMarkedNodeAttr);
    res = attr;
    attr.clear();
  }
  return res;
}

}  // namespace ir
}  // namespace framework
}  // namespace paddle

REGISTER_PASS(graph_viz_pass, paddle::framework::ir::GraphVizPass)
    .RequirePassAttr(paddle::framework::ir::kGraphVizPath);
<|endoftext|>