<commit_before>#include "spectests.h"

namespace Test {
	namespace Spec {
		// 2.1
		TEST SeqScalars()
        {
            return "  not written yet";
        }

		// 2.2
		TEST MappingScalarsToScalars()
        {
            return "  not written yet";
        }

		// 2.3
		TEST MappingScalarsToSequences()
        {
            return "  not written yet";
        }

		// 2.4
		TEST SequenceOfMappings()
        {
            return "  not written yet";
        }

		// 2.5
		TEST SequenceOfSequences()
        {
            return "  not written yet";
        }

		// 2.6
		TEST MappingOfMappings()
        {
            return "  not written yet";
        }

		// 2.7
		TEST TwoDocumentsInAStream()
        {
            return "  not written yet";
        }

		// 2.8
		TEST PlayByPlayFeed()
        {
            return "  not written yet";
        }

		// 2.9
		TEST SingleDocumentWithTwoComments()
        {
            return "  not written yet";
        }

		// 2.10
		TEST SimpleAnchor()
        {
            return "  not written yet";
        }

		// 2.11
		TEST MappingBetweenSequences()
        {
            return "  not written yet";
        }

		// 2.12
		TEST CompactNestedMapping()
        {
            return "  not written yet";
        }

		// 2.13
		TEST InLiteralsNewlinesArePreserved()
        {
            return "  not written yet";
        }

		// 2.14
		TEST InFoldedScalarsNewlinesBecomeSpaces()
        {
            return "  not written yet";
        }

		// 2.15
		TEST FoldedNewlinesArePreservedForMoreIndentedAndBlankLines()
        {
            return "  not written yet";
        }

		// 2.16
		TEST IndentationDeterminesScope()
        {
            return "  not written yet";
        }

		// 2.17
		TEST QuotedScalars()
        {
            return "  not written yet";
        }

		// 2.18
		TEST MultiLineFlowScalars()
        {
            return "  not written yet";
        }

		// TODO: 2.19 - 2.22 schema tags

		// 2.23
		TEST VariousExplicitTags()
        {
            return "  not written yet";
        }

		// 2.24
		TEST GlobalTags()
        {
            return "  not written yet";
        }

		// 2.25
		TEST UnorderedSets()
        {
            return "  not written yet";
        }

		// 2.26
		TEST OrderedMappings()
        {
            return "  not written yet";
        }

		// 2.27
		TEST Invoice()
        {
            return "  not written yet";
        }

		// 2.28
		TEST LogFile()
        {
            return "  not written yet";
        }

		// TODO: 5.1 - 5.2 BOM

		// 5.3
		TEST BlockStructureIndicators()
        {
            return "  not written yet";
        }

		// 5.4
		TEST FlowStructureIndicators()
        {
            return "  not written yet";
        }

		// 5.5
		TEST CommentIndicator()
        {
            return "  not written yet";
        }

		// 5.6
		TEST NodePropertyIndicators()
        {
            return "  not written yet";
        }

		// 5.7
		TEST BlockScalarIndicators()
        {
            return "  not written yet";
        }

		// 5.8
		TEST QuotedScalarIndicators()
        {
            return "  not written yet";
        }

		// TODO: 5.9 directive
		// TODO: 5.10 reserved indicator

		// 5.11
		TEST LineBreakCharacters()
        {
            return "  not written yet";
        }

		// 5.12
		TEST TabsAndSpaces()
        {
            return "  not written yet";
        }

		// 5.13
		TEST EscapedCharacters()
        {
            return "  not written yet";
        }

		// 5.14
		TEST InvalidEscapedCharacters()
        {
            return "  not written yet";
        }

		// 6.1
		TEST IndentationSpaces()
        {
            return "  not written yet";
        }

		// 6.2
		TEST IndentationIndicators()
        {
            return "  not written yet";
        }

		// 6.3
		TEST SeparationSpaces()
        {
            return "  not written yet";
        }

		// 6.4
		TEST LinePrefixes()
        {
            return "  not written yet";
        }

		// 6.5
		TEST EmptyLines()
        {
            return "  not written yet";
        }

		// 6.6
		TEST LineFolding()
        {
            return "  not written yet";
        }

		// 6.7
		TEST BlockFolding()
        {
            return "  not written yet";
        }

		// 6.8
		TEST FlowFolding()
        {
            return "  not written yet";
        }

		// 6.9
		TEST SeparatedComment()
        {
            return "  not written yet";
        }

		// 6.10
		TEST CommentLines()
        {
            return "  not written yet";
        }

		// 6.11
		TEST MultiLineComments()
        {
            return "  not written yet";
        }

		// 6.12
		TEST SeparationSpacesII()
        {
            return "  not written yet";
        }

		// 6.13
		TEST ReservedDirectives()
        {
            return "  not written yet";
        }

		// 6.14
		TEST YAMLDirective()
        {
            return "  not written yet";
        }

		// 6.15
		TEST InvalidRepeatedYAMLDirective()
        {
            return "  not written yet";
        }

		// 6.16
		TEST TagDirective()
        {
            return "  not written yet";
        }

		// 6.17
		TEST InvalidRepeatedTagDirective()
        {
            return "  not written yet";
        }

		// 6.18
		TEST PrimaryTagHandle()
        {
            return "  not written yet";
        }

		// 6.19
		TEST SecondaryTagHandle()
        {
            return "  not written yet";
        }

		// 6.20
		TEST TagHandles()
        {
            return "  not written yet";
        }

		// 6.21
		TEST LocalTagPrefix()
        {
            return "  not written yet";
        }

		// 6.22
		TEST GlobalTagPrefix()
        {
            return "  not written yet";
        }

		// 6.23
		TEST NodeProperties()
        {
            return "  not written yet";
        }

		// 6.24
		TEST VerbatimTags()
        {
            return "  not written yet";
        }

		// 6.25
		TEST InvalidVerbatimTags()
        {
            return "  not written yet";
        }

		// 6.26
		TEST TagShorthands()
        {
            return "  not written yet";
        }

		// 6.27
		TEST InvalidTagShorthands()
        {
            return "  not written yet";
        }

		// 6.28
		TEST NonSpecificTags()
        {
            return "  not written yet";
        }

		// 6.29
		TEST NodeAnchors()
        {
            return "  not written yet";
        }

		// 7.1
		TEST AliasNodes()
        {
            return "  not written yet";
        }

		// 7.2
		TEST EmptyNodes()
        {
            return "  not written yet";
        }

		// 7.3
		TEST CompletelyEmptyNodes()
        {
            return "  not written yet";
        }

		// 7.4
		TEST DoubleQuotedImplicitKeys()
        {
            return "  not written yet";
        }

		// 7.5
		TEST DoubleQuotedLineBreaks()
        {
            return "  not written yet";
        }

		// 7.6
		TEST DoubleQuotedLines()
        {
            return "  not written yet";
        }

		// 7.7
		TEST SingleQuotedCharacters()
        {
            return "  not written yet";
        }

		// 7.8
		TEST SingleQuotedImplicitKeys()
        {
            return "  not written yet";
        }

		// 7.9
		TEST SingleQuotedLines()
        {
            return "  not written yet";
        }

		// 7.10
		TEST PlainCharacters()
        {
            return "  not written yet";
        }

		// 7.11
		TEST PlainImplicitKeys()
        {
            return "  not written yet";
        }

		// 7.12
		TEST PlainLines()
        {
            return "  not written yet";
        }

		// 7.13
		TEST FlowSequence()
        {
            return "  not written yet";
        }

		// 7.14
		TEST FlowSequenceEntries()
        {
            return "  not written yet";
        }

		// 7.15
		TEST FlowMappings()
        {
            return "  not written yet";
        }

		// 7.16
		TEST FlowMappingEntries()
        {
            return "  not written yet";
        }

		// 7.17
		TEST FlowMappingSeparateValues()
        {
            return "  not written yet";
        }

		// 7.18
		TEST FlowMappingAdjacentValues()
        {
            return "  not written yet";
        }

		// 7.19
		TEST SinglePairFlowMappings()
        {
            return "  not written yet";
        }

		// 7.20
		TEST SinglePairExplicitEntry()
        {
            return "  not written yet";
        }

		// 7.21
		TEST SinglePairImplicitEntries()
        {
            return "  not written yet";
        }

		// 7.22
		TEST InvalidImplicitKeys()
        {
            return "  not written yet";
        }

		// 7.23
		TEST FlowContent()
        {
            return "  not written yet";
        }

		// 7.24
		TEST FlowNodes()
        {
            return "  not written yet";
        }

		// 8.1
		TEST BlockScalarHeader()
        {
            return "  not written yet";
        }

		// 8.2
		TEST BlockIndentationHeader()
        {
            return "  not written yet";
        }

		// 8.3
		TEST InvalidBlockScalarIndentationIndicators()
        {
            return "  not written yet";
        }

		// 8.4
		TEST ChompingFinalLineBreak()
        {
            return "  not written yet";
        }

		// 8.5
		TEST ChompingTrailingLines()
        {
            return "  not written yet";
        }

		// 8.6
		TEST EmptyScalarChomping()
        {
            return "  not written yet";
        }

		// 8.7
		TEST LiteralScalar()
        {
            return "  not written yet";
        }

		// 8.8
		TEST LiteralContent()
        {
            return "  not written yet";
        }

		// 8.9
		TEST FoldedScalar()
        {
            return "  not written yet";
        }

		// 8.10
		TEST FoldedLines()
        {
            return "  not written yet";
        }

		// 8.11
		TEST MoreIndentedLines()
        {
            return "  not written yet";
        }

		// 8.12
		TEST EmptySeparationLines()
        {
            return "  not written yet";
        }

		// 8.13
		TEST FinalEmptyLines()
        {
            return "  not written yet";
        }

		// 8.14
		TEST BlockSequence()
        {
            return "  not written yet";
        }

		// 8.15
		TEST BlockSequenceEntryTypes()
        {
            return "  not written yet";
        }

		// 8.16
		TEST BlockMappings()
        {
            return "  not written yet";
        }

		// 8.17
		TEST ExplicitBlockMappingEntries()
        {
            return "  not written yet";
        }

		// 8.18
		TEST ImplicitBlockMappingEntries()
        {
            return "  not written yet";
        }

		// 8.19
		TEST CompactBlockMappings()
        {
            return "  not written yet";
        }

		// 8.20
		TEST BlockNodeTypes()
        {
            return "  not written yet";
        }

		// 8.21
		TEST BlockScalarNodes()
        {
            return "  not written yet";
        }

		// 8.22
		TEST BlockCollectionNodes()
        {
            return "  not written yet";
        }
	}
}
<commit_msg>Added framework for spectests with event handling<commit_after>#include "spectests.h"
#include "specexamples.h"
#include "yaml-cpp/yaml.h"
#include "yaml-cpp/eventhandler.h"
#include <cassert>

namespace Test {
    struct Event {
        enum Type { DocStart, DocEnd, Null, Alias, Scalar, SeqStart, SeqEnd, MapStart, MapEnd };

        typedef YAML::Mark Mark;
        typedef YAML::anchor_t anchor_t;

        Event(Type type_, const std::string& tag_, anchor_t anchor_, const std::string& scalar_): type(type_), tag(tag_), anchor(anchor_), scalar(scalar_) {}

        Type type;
        std::string tag;
        anchor_t anchor;
        std::string scalar;

        std::ostream& write(std::ostream& out) const {
            switch(type) {
                case DocStart:
                    return out << "DocStart";
                case DocEnd:
                    return out << "DocEnd";
                case Null:
                    return out << "Null(" << anchor << ")";
                case Alias:
                    return out << "Alias(" << anchor << ")";
                case Scalar:
                    return out << "Scalar(" << tag << ", " << anchor << ", " << scalar << ")";
                case SeqStart:
                    return out << "SeqStart(" << tag << ", " << anchor << ")";
                case SeqEnd:
                    return out << "SeqEnd";
                case MapStart:
                    return out << "MapStart(" << tag << ", " << anchor << ")";
                case MapEnd:
                    return out << "MapEnd";
            }
            assert(false);
            return out;
        }
    };

    std::ostream& operator << (std::ostream& out, const Event& event) {
        return event.write(out);
    }

    bool operator == (const Event& a, const Event& b) {
        return a.type == b.type && a.tag == b.tag && a.anchor == b.anchor && a.scalar == b.scalar;
    }

    bool operator != (const Event& a, const Event& b) {
        return !(a == b);
    }

	class MockEventHandler: public YAML::EventHandler
	{
	public:
        typedef YAML::Mark Mark;
        typedef YAML::anchor_t anchor_t;

        MockEventHandler() {}

		virtual void OnDocumentStart(const Mark&) {
            m_actualEvents.push_back(Event(Event::DocStart, "", 0, ""));
        }

		virtual void OnDocumentEnd() {
            m_actualEvents.push_back(Event(Event::DocEnd, "", 0, ""));
        }

		virtual void OnNull(const Mark&, anchor_t anchor) {
            m_actualEvents.push_back(Event(Event::Null, "", anchor, ""));
        }

		virtual void OnAlias(const Mark&, anchor_t anchor) {
            m_actualEvents.push_back(Event(Event::Alias, "", anchor, ""));
        }

		virtual void OnScalar(const Mark&, const std::string& tag, anchor_t anchor, const std::string& value) {
            m_actualEvents.push_back(Event(Event::Scalar, tag, anchor, value));
        }

		virtual void OnSequenceStart(const Mark&, const std::string& tag, anchor_t anchor) {
            m_actualEvents.push_back(Event(Event::SeqStart, tag, anchor, ""));
        }

		virtual void OnSequenceEnd() {
            m_actualEvents.push_back(Event(Event::SeqEnd, "", 0, ""));
        }

		virtual void OnMapStart(const Mark&, const std::string& tag, anchor_t anchor) {
            m_actualEvents.push_back(Event(Event::MapStart, tag, anchor, ""));
        }

		virtual void OnMapEnd() {
            m_actualEvents.push_back(Event(Event::MapEnd, "", 0, ""));
        }

        void Expect(const Event& event) { m_expectedEvents.push_back(event); }

        Test::TEST Check() const {
            std::size_t N = std::max(m_expectedEvents.size(), m_actualEvents.size());
            for(std::size_t i=0;i<N;i++) {
                if(i >= m_expectedEvents.size()) {
                    std::stringstream out;
                    for(std::size_t j=0;j<i;j++) {
                        out << m_expectedEvents[j] << "\n";
                    }
                    out << "EXPECTED: (no event expected)\n";
                    out << "ACTUAL  : " << m_actualEvents[i] << "\n";
                    return out.str().c_str();
                }

                if(i >= m_actualEvents.size()) {
                    std::stringstream out;
                    for(std::size_t j=0;j<i;j++) {
                        out << m_expectedEvents[j] << "\n";
                    }
                    out << "EXPECTED: " << m_expectedEvents[i] << "\n";
                    out << "ACTUAL  : (no event recorded)\n";
                    return out.str().c_str();
                }

                if(m_expectedEvents[i] != m_actualEvents[i]) {
                    std::stringstream out;
                    for(std::size_t j=0;j<i;j++) {
                        out << m_expectedEvents[j] << "\n";
                    }
                    out << "EXPECTED: " << m_expectedEvents[i] << "\n";
                    out << "ACTUAL  : " << m_actualEvents[i] << "\n";
                    return out.str().c_str();
                }
            }

            return true;
        }

        std::vector<Event> m_expectedEvents;
        std::vector<Event> m_actualEvents;
	};

#define HANDLE(ex)\
    MockEventHandler handler;\
    std::stringstream stream(ex);\
    YAML::Parser parser(stream);\
    parser.HandleNextDocument(handler)

#define HANDLE_NEXT(ex)\
    parser.HandleNextDocument(handler)

#define EXPECT_DOC_START()\
    do {\
        handler.Expect(Event(Event::DocStart, "", 0, ""));\
    } while(false)

#define EXPECT_DOC_END()\
    do {\
        handler.Expect(Event(Event::DocEnd, "", 0, ""));\
    } while(false)

#define EXPECT_NULL(anchor)\
    do {\
        handler.Expect(Event(Event::Null, "", anchor, ""));\
    } while(false)

#define EXPECT_ALIAS(anchor)\
    do {\
        handler.Expect(Event(Event::Alias, "", anchor, ""));\
    } while(false)

#define EXPECT_SCALAR(tag, anchor, value)\
    do {\
        handler.Expect(Event(Event::Scalar, tag, anchor, value));\
    } while(false)

#define EXPECT_SEQ_START(tag, anchor)\
    do {\
        handler.Expect(Event(Event::SeqStart, tag, anchor, ""));\
    } while(false)

#define EXPECT_SEQ_END()\
    do {\
        handler.Expect(Event(Event::SeqEnd, "", 0, ""));\
    } while(false)

#define EXPECT_MAP_START(tag, anchor)\
    do {\
        handler.Expect(Event(Event::MapStart, tag, anchor, ""));\
    } while(false)

#define EXPECT_MAP_END()\
    do {\
        handler.Expect(Event(Event::MapEnd, "", 0, ""));\
    } while(false)

#define DONE()\
    do {\
        return handler.Check();\
    } while(false)

	namespace Spec {
		// 2.1
		TEST SeqScalars()
        {
            HANDLE(ex2_1);
            EXPECT_DOC_START();
            EXPECT_SEQ_START("?", 0);
            EXPECT_SCALAR("?", 0, "Mark McGwire");
            EXPECT_SCALAR("?", 0, "Sammy Sosa");
            EXPECT_SCALAR("?", 0, "Ken Griffey");
            EXPECT_SEQ_END();
            EXPECT_DOC_END();
            DONE();
        }

		// 2.2
		TEST MappingScalarsToScalars()
        {
            return "  not written yet";
        }

		// 2.3
		TEST MappingScalarsToSequences()
        {
            return "  not written yet";
        }

		// 2.4
		TEST SequenceOfMappings()
        {
            return "  not written yet";
        }

		// 2.5
		TEST SequenceOfSequences()
        {
            return "  not written yet";
        }

		// 2.6
		TEST MappingOfMappings()
        {
            return "  not written yet";
        }

		// 2.7
		TEST TwoDocumentsInAStream()
        {
            return "  not written yet";
        }

		// 2.8
		TEST PlayByPlayFeed()
        {
            return "  not written yet";
        }

		// 2.9
		TEST SingleDocumentWithTwoComments()
        {
            return "  not written yet";
        }

		// 2.10
		TEST SimpleAnchor()
        {
            return "  not written yet";
        }

		// 2.11
		TEST MappingBetweenSequences()
        {
            return "  not written yet";
        }

		// 2.12
		TEST CompactNestedMapping()
        {
            return "  not written yet";
        }

		// 2.13
		TEST InLiteralsNewlinesArePreserved()
        {
            return "  not written yet";
        }

		// 2.14
		TEST InFoldedScalarsNewlinesBecomeSpaces()
        {
            return "  not written yet";
        }

		// 2.15
		TEST FoldedNewlinesArePreservedForMoreIndentedAndBlankLines()
        {
            return "  not written yet";
        }

		// 2.16
		TEST IndentationDeterminesScope()
        {
            return "  not written yet";
        }

		// 2.17
		TEST QuotedScalars()
        {
            return "  not written yet";
        }

		// 2.18
		TEST MultiLineFlowScalars()
        {
            return "  not written yet";
        }

		// TODO: 2.19 - 2.22 schema tags

		// 2.23
		TEST VariousExplicitTags()
        {
            return "  not written yet";
        }

		// 2.24
		TEST GlobalTags()
        {
            return "  not written yet";
        }

		// 2.25
		TEST UnorderedSets()
        {
            return "  not written yet";
        }

		// 2.26
		TEST OrderedMappings()
        {
            return "  not written yet";
        }

		// 2.27
		TEST Invoice()
        {
            return "  not written yet";
        }

		// 2.28
		TEST LogFile()
        {
            return "  not written yet";
        }

		// TODO: 5.1 - 5.2 BOM

		// 5.3
		TEST BlockStructureIndicators()
        {
            return "  not written yet";
        }

		// 5.4
		TEST FlowStructureIndicators()
        {
            return "  not written yet";
        }

		// 5.5
		TEST CommentIndicator()
        {
            return "  not written yet";
        }

		// 5.6
		TEST NodePropertyIndicators()
        {
            return "  not written yet";
        }

		// 5.7
		TEST BlockScalarIndicators()
        {
            return "  not written yet";
        }

		// 5.8
		TEST QuotedScalarIndicators()
        {
            return "  not written yet";
        }

		// TODO: 5.9 directive
		// TODO: 5.10 reserved indicator

		// 5.11
		TEST LineBreakCharacters()
        {
            return "  not written yet";
        }

		// 5.12
		TEST TabsAndSpaces()
        {
            return "  not written yet";
        }

		// 5.13
		TEST EscapedCharacters()
        {
            return "  not written yet";
        }

		// 5.14
		TEST InvalidEscapedCharacters()
        {
            return "  not written yet";
        }

		// 6.1
		TEST IndentationSpaces()
        {
            return "  not written yet";
        }

		// 6.2
		TEST IndentationIndicators()
        {
            return "  not written yet";
        }

		// 6.3
		TEST SeparationSpaces()
        {
            return "  not written yet";
        }

		// 6.4
		TEST LinePrefixes()
        {
            return "  not written yet";
        }

		// 6.5
		TEST EmptyLines()
        {
            return "  not written yet";
        }

		// 6.6
		TEST LineFolding()
        {
            return "  not written yet";
        }

		// 6.7
		TEST BlockFolding()
        {
            return "  not written yet";
        }

		// 6.8
		TEST FlowFolding()
        {
            return "  not written yet";
        }

		// 6.9
		TEST SeparatedComment()
        {
            return "  not written yet";
        }

		// 6.10
		TEST CommentLines()
        {
            return "  not written yet";
        }

		// 6.11
		TEST MultiLineComments()
        {
            return "  not written yet";
        }

		// 6.12
		TEST SeparationSpacesII()
        {
            return "  not written yet";
        }

		// 6.13
		TEST ReservedDirectives()
        {
            return "  not written yet";
        }

		// 6.14
		TEST YAMLDirective()
        {
            return "  not written yet";
        }

		// 6.15
		TEST InvalidRepeatedYAMLDirective()
        {
            return "  not written yet";
        }

		// 6.16
		TEST TagDirective()
        {
            return "  not written yet";
        }

		// 6.17
		TEST InvalidRepeatedTagDirective()
        {
            return "  not written yet";
        }

		// 6.18
		TEST PrimaryTagHandle()
        {
            return "  not written yet";
        }

		// 6.19
		TEST SecondaryTagHandle()
        {
            return "  not written yet";
        }

		// 6.20
		TEST TagHandles()
        {
            return "  not written yet";
        }

		// 6.21
		TEST LocalTagPrefix()
        {
            return "  not written yet";
        }

		// 6.22
		TEST GlobalTagPrefix()
        {
            return "  not written yet";
        }

		// 6.23
		TEST NodeProperties()
        {
            return "  not written yet";
        }

		// 6.24
		TEST VerbatimTags()
        {
            return "  not written yet";
        }

		// 6.25
		TEST InvalidVerbatimTags()
        {
            return "  not written yet";
        }

		// 6.26
		TEST TagShorthands()
        {
            return "  not written yet";
        }

		// 6.27
		TEST InvalidTagShorthands()
        {
            return "  not written yet";
        }

		// 6.28
		TEST NonSpecificTags()
        {
            return "  not written yet";
        }

		// 6.29
		TEST NodeAnchors()
        {
            return "  not written yet";
        }

		// 7.1
		TEST AliasNodes()
        {
            return "  not written yet";
        }

		// 7.2
		TEST EmptyNodes()
        {
            return "  not written yet";
        }

		// 7.3
		TEST CompletelyEmptyNodes()
        {
            return "  not written yet";
        }

		// 7.4
		TEST DoubleQuotedImplicitKeys()
        {
            return "  not written yet";
        }

		// 7.5
		TEST DoubleQuotedLineBreaks()
        {
            return "  not written yet";
        }

		// 7.6
		TEST DoubleQuotedLines()
        {
            return "  not written yet";
        }

		// 7.7
		TEST SingleQuotedCharacters()
        {
            return "  not written yet";
        }

		// 7.8
		TEST SingleQuotedImplicitKeys()
        {
            return "  not written yet";
        }

		// 7.9
		TEST SingleQuotedLines()
        {
            return "  not written yet";
        }

		// 7.10
		TEST PlainCharacters()
        {
            return "  not written yet";
        }

		// 7.11
		TEST PlainImplicitKeys()
        {
            return "  not written yet";
        }

		// 7.12
		TEST PlainLines()
        {
            return "  not written yet";
        }

		// 7.13
		TEST FlowSequence()
        {
            return "  not written yet";
        }

		// 7.14
		TEST FlowSequenceEntries()
        {
            return "  not written yet";
        }

		// 7.15
		TEST FlowMappings()
        {
            return "  not written yet";
        }

		// 7.16
		TEST FlowMappingEntries()
        {
            return "  not written yet";
        }

		// 7.17
		TEST FlowMappingSeparateValues()
        {
            return "  not written yet";
        }

		// 7.18
		TEST FlowMappingAdjacentValues()
        {
            return "  not written yet";
        }

		// 7.19
		TEST SinglePairFlowMappings()
        {
            return "  not written yet";
        }

		// 7.20
		TEST SinglePairExplicitEntry()
        {
            return "  not written yet";
        }

		// 7.21
		TEST SinglePairImplicitEntries()
        {
            return "  not written yet";
        }

		// 7.22
		TEST InvalidImplicitKeys()
        {
            return "  not written yet";
        }

		// 7.23
		TEST FlowContent()
        {
            return "  not written yet";
        }

		// 7.24
		TEST FlowNodes()
        {
            return "  not written yet";
        }

		// 8.1
		TEST BlockScalarHeader()
        {
            return "  not written yet";
        }

		// 8.2
		TEST BlockIndentationHeader()
        {
            return "  not written yet";
        }

		// 8.3
		TEST InvalidBlockScalarIndentationIndicators()
        {
            return "  not written yet";
        }

		// 8.4
		TEST ChompingFinalLineBreak()
        {
            return "  not written yet";
        }

		// 8.5
		TEST ChompingTrailingLines()
        {
            return "  not written yet";
        }

		// 8.6
		TEST EmptyScalarChomping()
        {
            return "  not written yet";
        }

		// 8.7
		TEST LiteralScalar()
        {
            return "  not written yet";
        }

		// 8.8
		TEST LiteralContent()
        {
            return "  not written yet";
        }

		// 8.9
		TEST FoldedScalar()
        {
            return "  not written yet";
        }

		// 8.10
		TEST FoldedLines()
        {
            return "  not written yet";
        }

		// 8.11
		TEST MoreIndentedLines()
        {
            return "  not written yet";
        }

		// 8.12
		TEST EmptySeparationLines()
        {
            return "  not written yet";
        }

		// 8.13
		TEST FinalEmptyLines()
        {
            return "  not written yet";
        }

		// 8.14
		TEST BlockSequence()
        {
            return "  not written yet";
        }

		// 8.15
		TEST BlockSequenceEntryTypes()
        {
            return "  not written yet";
        }

		// 8.16
		TEST BlockMappings()
        {
            return "  not written yet";
        }

		// 8.17
		TEST ExplicitBlockMappingEntries()
        {
            return "  not written yet";
        }

		// 8.18
		TEST ImplicitBlockMappingEntries()
        {
            return "  not written yet";
        }

		// 8.19
		TEST CompactBlockMappings()
        {
            return "  not written yet";
        }

		// 8.20
		TEST BlockNodeTypes()
        {
            return "  not written yet";
        }

		// 8.21
		TEST BlockScalarNodes()
        {
            return "  not written yet";
        }

		// 8.22
		TEST BlockCollectionNodes()
        {
            return "  not written yet";
        }
	}
}
<|endoftext|>


<commit_before><commit_msg>coverity#738778 Uninitialized scalar field<commit_after><|endoftext|>


<commit_before>//Copyright (c) 2018 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.

#include <google/protobuf/message.h>

#include "MockSocket.h" //To mock out the communication with the front-end.
#include "ArcusCommunicationTest.h"
#include "../src/FffProcessor.h"
#include "../src/communication/ArcusCommunicationPrivate.h" //To access the private fields of this communication class.
#include "../src/settings/types/LayerIndex.h"

namespace cura
{
    CPPUNIT_TEST_SUITE_REGISTRATION(ArcusCommunicationTest);

    void ArcusCommunicationTest::setUp()
    {
        ip = "0.0.0.0";
        port = 12345;
        socket = new MockSocket();
        ac = new ArcusCommunication();
        ac->setSocketMock(socket);

        // from: PolygonConnectorTest
        test_square.emplace_back(0, 0);
        test_square.emplace_back(1000, 0);
        test_square.emplace_back(1000, 1000);
        test_square.emplace_back(0, 1000);
        test_shapes.add(test_square);

        test_square2.emplace_back(1100, 1500);
        test_square2.emplace_back(2000, 1500);
        test_square2.emplace_back(2000, -500);
        test_square2.emplace_back(1100, -500);
        test_shapes.add(test_square2);

        test_triangle.emplace_back(0, 2100);
        test_triangle.emplace_back(500, 1100);
        test_triangle.emplace_back(1500, 2100);
        test_shapes.add(test_triangle);

        for (double a = 0; a < 1.0; a += .05)
        {
            test_circle.add(Point(2050, 2050) + Point(std::cos(a * 2 * M_PI)*500, std::sin(a * 2 * M_PI)*500));
        }
        test_shapes.add(test_circle);

        test_convex_shape.emplace_back(-300, 0);
        test_convex_shape.emplace_back(-100, 500);
        test_convex_shape.emplace_back(-100, 600);
        test_convex_shape.emplace_back(-200, 1000);
        test_convex_shape.emplace_back(-500, 1500);
        test_convex_shape.emplace_back(-1500, 1500);
        test_convex_shape.emplace_back(-1500, 1500);
        test_convex_shape.emplace_back(-1600, 1100);
        test_convex_shape.emplace_back(-700, 200);
        test_shapes.add(test_convex_shape);
    }

    void ArcusCommunicationTest::tearDown()
    {
        delete ac;
        ac = nullptr;
    }

    void ArcusCommunicationTest::flushGCodeTest()
    {
        //Before there is g-code, no messages should be sent if we were to flush.
        ac->flushGCode();
        CPPUNIT_ASSERT(socket->sent_messages.empty());

        //Input some 'g-code' to flush.
        const std::string test_gcode = "This Fibonacci joke is as bad as the last two you heard combined.\n"
                                       "It's pretty cool how the Chinese made a language entirely out of tattoos."; //Multi-line to see flushing behaviour.
        ac->private_data->gcode_output_stream.write(test_gcode.c_str(), test_gcode.size());

        //Call the function we're testing. This time it should give us a message.
        ac->flushGCode();

        CPPUNIT_ASSERT_EQUAL(size_t(1), socket->sent_messages.size());
        const proto::GCodeLayer* message = dynamic_cast<proto::GCodeLayer*>(socket->sent_messages.front().get());
        CPPUNIT_ASSERT_EQUAL(test_gcode, message->data());
    }

    void ArcusCommunicationTest::isSequentialTest()
    {
        CPPUNIT_ASSERT(ac->isSequential());
    }

    void ArcusCommunicationTest::hasSliceTest()
    {
        CPPUNIT_ASSERT(ac->hasSlice()); // TODO: Only possible when there's a slice send.
    }

    void ArcusCommunicationTest::sendCurrentPositionTest()
    {
//         ac->sendCurrentPosition(Point(1, 2));
// //        ac->flushGCode();
    }

    void ArcusCommunicationTest::sendGCodePrefixTest()
    {
        const std::string& prefix = "bladibla";

        ac->sendGCodePrefix(prefix);
        ac->flushGCode();
        CPPUNIT_ASSERT(socket->sent_messages.size() > 0);
        bool found_prefix = false;
        for (auto message : socket->sent_messages)
        {
            if (message->DebugString().find(prefix) != std::string::npos)
            {
                found_prefix = true;
                break;
            }
        }
        CPPUNIT_ASSERT(found_prefix);
    }

    void ArcusCommunicationTest::sendFinishedSlicingTest()
    {
        ac->sendFinishedSlicing();
        CPPUNIT_ASSERT(socket->sent_messages.size() > 0);
    }

    void ArcusCommunicationTest::sendLayerCompleteTest()
    {
        ac->sendLayerComplete(10, 20, 30);
        //CPPUNIT_ASSERT(socket->sent_messages.size() > 0);
    }

    void ArcusCommunicationTest::sendLineToTest()
    {
        const PrintFeatureType& type = PrintFeatureType::OuterWall;
        const Point& to = Point(100, 100);
        const coord_t& line_width = 400;
        const coord_t& line_thickness = 200;
        const Velocity& velocity = Velocity(10.0);

        ac->sendLineTo(type, to, line_width, line_thickness, velocity);
        ac->sendLayerComplete(10, 20, 30);
    }

    void ArcusCommunicationTest::sendOptimizedLayerDataTest()
    {
        ac->sendOptimizedLayerData();
    }

    void ArcusCommunicationTest::sendPolygonTest()
    {
        const PrintFeatureType& type = PrintFeatureType::OuterWall;
        const ConstPolygonRef& polygon_ref = test_circle;
        const coord_t& line_width = 400;
        const coord_t& line_thickness = 200;
        const Velocity& velocity = Velocity(10.0);

        ac->sendPolygon(type, polygon_ref, line_width, line_thickness, velocity);
    }

    void ArcusCommunicationTest::sendPolygonsTest()
    {
        const PrintFeatureType& type = PrintFeatureType::OuterWall;
        const Polygons& polygons = test_shapes;
        const coord_t& line_width = 400;
        const coord_t& line_thickness = 200;
        const Velocity& velocity = Velocity(10.0);

        ac->sendPolygons(type, polygons, line_width, line_thickness, velocity);
    }

    void ArcusCommunicationTest::sendPrintTimeMaterialEstimatesTest()
    {
        // Segfault
//        socket->setName("sendPrintTimeMaterialEstimatesTest");
//        std::cout << "sendPrintTimeMaterialEstimatesTest...\n";
//        ac->sendPrintTimeMaterialEstimates();
//        socket->printMessages();
    }

    void ArcusCommunicationTest::sendProgressTest()
    {
        ac->sendProgress(10);;
        ac->sendProgress(50);
    }

    void ArcusCommunicationTest::setLayerForSendTest()
    {
        ac->setLayerForSend(42);
    }

    void ArcusCommunicationTest::setExtruderForSendTest()
    {

    }

    void ArcusCommunicationTest::sliceNextTest()
    {
        ac->sliceNext();
    }
}

<commit_msg>Make hasSliceTest at least somewhat useful<commit_after>//Copyright (c) 2018 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.

#include <google/protobuf/message.h>

#include "MockSocket.h" //To mock out the communication with the front-end.
#include "ArcusCommunicationTest.h"
#include "../src/FffProcessor.h"
#include "../src/communication/ArcusCommunicationPrivate.h" //To access the private fields of this communication class.
#include "../src/settings/types/LayerIndex.h"

namespace cura
{
    CPPUNIT_TEST_SUITE_REGISTRATION(ArcusCommunicationTest);

    void ArcusCommunicationTest::setUp()
    {
        ip = "0.0.0.0";
        port = 12345;
        socket = new MockSocket();
        ac = new ArcusCommunication();
        ac->setSocketMock(socket);

        // from: PolygonConnectorTest
        test_square.emplace_back(0, 0);
        test_square.emplace_back(1000, 0);
        test_square.emplace_back(1000, 1000);
        test_square.emplace_back(0, 1000);
        test_shapes.add(test_square);

        test_square2.emplace_back(1100, 1500);
        test_square2.emplace_back(2000, 1500);
        test_square2.emplace_back(2000, -500);
        test_square2.emplace_back(1100, -500);
        test_shapes.add(test_square2);

        test_triangle.emplace_back(0, 2100);
        test_triangle.emplace_back(500, 1100);
        test_triangle.emplace_back(1500, 2100);
        test_shapes.add(test_triangle);

        for (double a = 0; a < 1.0; a += .05)
        {
            test_circle.add(Point(2050, 2050) + Point(std::cos(a * 2 * M_PI)*500, std::sin(a * 2 * M_PI)*500));
        }
        test_shapes.add(test_circle);

        test_convex_shape.emplace_back(-300, 0);
        test_convex_shape.emplace_back(-100, 500);
        test_convex_shape.emplace_back(-100, 600);
        test_convex_shape.emplace_back(-200, 1000);
        test_convex_shape.emplace_back(-500, 1500);
        test_convex_shape.emplace_back(-1500, 1500);
        test_convex_shape.emplace_back(-1500, 1500);
        test_convex_shape.emplace_back(-1600, 1100);
        test_convex_shape.emplace_back(-700, 200);
        test_shapes.add(test_convex_shape);
    }

    void ArcusCommunicationTest::tearDown()
    {
        delete ac;
        ac = nullptr;
    }

    void ArcusCommunicationTest::flushGCodeTest()
    {
        //Before there is g-code, no messages should be sent if we were to flush.
        ac->flushGCode();
        CPPUNIT_ASSERT(socket->sent_messages.empty());

        //Input some 'g-code' to flush.
        const std::string test_gcode = "This Fibonacci joke is as bad as the last two you heard combined.\n"
                                       "It's pretty cool how the Chinese made a language entirely out of tattoos."; //Multi-line to see flushing behaviour.
        ac->private_data->gcode_output_stream.write(test_gcode.c_str(), test_gcode.size());

        //Call the function we're testing. This time it should give us a message.
        ac->flushGCode();

        CPPUNIT_ASSERT_EQUAL(size_t(1), socket->sent_messages.size());
        const proto::GCodeLayer* message = dynamic_cast<proto::GCodeLayer*>(socket->sent_messages.front().get());
        CPPUNIT_ASSERT_EQUAL(test_gcode, message->data());
    }

    void ArcusCommunicationTest::isSequentialTest()
    {
        CPPUNIT_ASSERT(ac->isSequential());
    }

    void ArcusCommunicationTest::hasSliceTest()
    {
        CPPUNIT_ASSERT(ac->hasSlice());
        ac->private_data->slice_count = 1;
        CPPUNIT_ASSERT_MESSAGE("Can't slice more than once.", !ac->hasSlice());
    }

    void ArcusCommunicationTest::sendCurrentPositionTest()
    {
//         ac->sendCurrentPosition(Point(1, 2));
// //        ac->flushGCode();
    }

    void ArcusCommunicationTest::sendGCodePrefixTest()
    {
        const std::string& prefix = "bladibla";

        ac->sendGCodePrefix(prefix);
        ac->flushGCode();
        CPPUNIT_ASSERT(socket->sent_messages.size() > 0);
        bool found_prefix = false;
        for (auto message : socket->sent_messages)
        {
            if (message->DebugString().find(prefix) != std::string::npos)
            {
                found_prefix = true;
                break;
            }
        }
        CPPUNIT_ASSERT(found_prefix);
    }

    void ArcusCommunicationTest::sendFinishedSlicingTest()
    {
        ac->sendFinishedSlicing();
        CPPUNIT_ASSERT(socket->sent_messages.size() > 0);
    }

    void ArcusCommunicationTest::sendLayerCompleteTest()
    {
        ac->sendLayerComplete(10, 20, 30);
        //CPPUNIT_ASSERT(socket->sent_messages.size() > 0);
    }

    void ArcusCommunicationTest::sendLineToTest()
    {
        const PrintFeatureType& type = PrintFeatureType::OuterWall;
        const Point& to = Point(100, 100);
        const coord_t& line_width = 400;
        const coord_t& line_thickness = 200;
        const Velocity& velocity = Velocity(10.0);

        ac->sendLineTo(type, to, line_width, line_thickness, velocity);
        ac->sendLayerComplete(10, 20, 30);
    }

    void ArcusCommunicationTest::sendOptimizedLayerDataTest()
    {
        ac->sendOptimizedLayerData();
    }

    void ArcusCommunicationTest::sendPolygonTest()
    {
        const PrintFeatureType& type = PrintFeatureType::OuterWall;
        const ConstPolygonRef& polygon_ref = test_circle;
        const coord_t& line_width = 400;
        const coord_t& line_thickness = 200;
        const Velocity& velocity = Velocity(10.0);

        ac->sendPolygon(type, polygon_ref, line_width, line_thickness, velocity);
    }

    void ArcusCommunicationTest::sendPolygonsTest()
    {
        const PrintFeatureType& type = PrintFeatureType::OuterWall;
        const Polygons& polygons = test_shapes;
        const coord_t& line_width = 400;
        const coord_t& line_thickness = 200;
        const Velocity& velocity = Velocity(10.0);

        ac->sendPolygons(type, polygons, line_width, line_thickness, velocity);
    }

    void ArcusCommunicationTest::sendPrintTimeMaterialEstimatesTest()
    {
        // Segfault
//        socket->setName("sendPrintTimeMaterialEstimatesTest");
//        std::cout << "sendPrintTimeMaterialEstimatesTest...\n";
//        ac->sendPrintTimeMaterialEstimates();
//        socket->printMessages();
    }

    void ArcusCommunicationTest::sendProgressTest()
    {
        ac->sendProgress(10);;
        ac->sendProgress(50);
    }

    void ArcusCommunicationTest::setLayerForSendTest()
    {
        ac->setLayerForSend(42);
    }

    void ArcusCommunicationTest::setExtruderForSendTest()
    {

    }

    void ArcusCommunicationTest::sliceNextTest()
    {
        ac->sliceNext();
    }
}

<|endoftext|>


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

#include <gtk/gtk.h>
#include <X11/Xatom.h>
#include <X11/Xlib.h>
#undef Success  // Definition conflicts with cef_message_router.h

#include <string>

#include "cefclient/client_handler.h"
#include "include/cef_browser.h"
#include "include/cef_frame.h"

void ClientHandler::OnAddressChange(CefRefPtr<CefBrowser> browser,
                                    CefRefPtr<CefFrame> frame,
                                    const CefString& url) {
  REQUIRE_UI_THREAD();

  if (m_BrowserId == browser->GetIdentifier() && frame->IsMain()) {
      // Set the edit window text
    std::string urlStr(url);
    gtk_entry_set_text(GTK_ENTRY(m_EditHwnd), urlStr.c_str());
  }
}

void ClientHandler::OnTitleChange(CefRefPtr<CefBrowser> browser,
                                  const CefString& title) {
  REQUIRE_UI_THREAD();

  std::string titleStr(title);

  if (!browser->IsPopup()) {
    // Set the GTK parent window title.
    GtkWidget* window = gtk_widget_get_ancestor(m_MainHwnd,
        GTK_TYPE_WINDOW);
    gtk_window_set_title(GTK_WINDOW(window), titleStr.c_str());
  } else {
    // Retrieve the X11 display shared with Chromium.
    ::Display* display = cef_get_xdisplay();
    ASSERT(display);

    // Retrieve the X11 window handle for the browser.
    ::Window window = browser->GetHost()->GetWindowHandle();
    ASSERT(window != kNullWindowHandle);

    // Retrieve the atoms required by the below XChangeProperty call.
    const char* kAtoms[] = {
      "_NET_WM_NAME",
      "UTF8_STRING"
    };
    Atom atoms[2];
    int result = XInternAtoms(display, const_cast<char**>(kAtoms), 2, false,
                              atoms);
    ASSERT(result);

    // Set the window title.
    XChangeProperty(display,
                    window,
                    atoms[0],
                    atoms[1],
                    8,
                    PropModeReplace,
                    reinterpret_cast<const unsigned char*>(titleStr.c_str()),
                    titleStr.size());

    // TODO(erg): This is technically wrong. So XStoreName and friends expect
    // this in Host Portable Character Encoding instead of UTF-8, which I
    // believe is Compound Text. This shouldn't matter 90% of the time since
    // this is the fallback to the UTF8 property above.
    XStoreName(display, browser->GetHost()->GetWindowHandle(),
               titleStr.c_str());
  }
}

void ClientHandler::SendNotification(NotificationType type) {
  // TODO(port): Implement this method.
}

void ClientHandler::SetLoading(bool isLoading) {
  if (isLoading)
    gtk_widget_set_sensitive(GTK_WIDGET(m_StopHwnd), true);
  else
    gtk_widget_set_sensitive(GTK_WIDGET(m_StopHwnd), false);
}

void ClientHandler::SetNavState(bool canGoBack, bool canGoForward) {
  if (canGoBack)
    gtk_widget_set_sensitive(GTK_WIDGET(m_BackHwnd), true);
  else
    gtk_widget_set_sensitive(GTK_WIDGET(m_BackHwnd), false);

  if (canGoForward)
    gtk_widget_set_sensitive(GTK_WIDGET(m_ForwardHwnd), true);
  else
    gtk_widget_set_sensitive(GTK_WIDGET(m_ForwardHwnd), false);
}

std::string ClientHandler::GetDownloadPath(const std::string& file_name) {
  return std::string();
}

<commit_msg>Linux: Fix release build compile error (issue #1245).<commit_after>// Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.

#include <gtk/gtk.h>
#include <X11/Xatom.h>
#include <X11/Xlib.h>
#undef Success  // Definition conflicts with cef_message_router.h

#include <string>

#include "cefclient/client_handler.h"
#include "include/cef_browser.h"
#include "include/cef_frame.h"

void ClientHandler::OnAddressChange(CefRefPtr<CefBrowser> browser,
                                    CefRefPtr<CefFrame> frame,
                                    const CefString& url) {
  REQUIRE_UI_THREAD();

  if (m_BrowserId == browser->GetIdentifier() && frame->IsMain()) {
      // Set the edit window text
    std::string urlStr(url);
    gtk_entry_set_text(GTK_ENTRY(m_EditHwnd), urlStr.c_str());
  }
}

void ClientHandler::OnTitleChange(CefRefPtr<CefBrowser> browser,
                                  const CefString& title) {
  REQUIRE_UI_THREAD();

  std::string titleStr(title);

  if (!browser->IsPopup()) {
    // Set the GTK parent window title.
    GtkWidget* window = gtk_widget_get_ancestor(m_MainHwnd,
        GTK_TYPE_WINDOW);
    gtk_window_set_title(GTK_WINDOW(window), titleStr.c_str());
  } else {
    // Retrieve the X11 display shared with Chromium.
    ::Display* display = cef_get_xdisplay();
    ASSERT(display);

    // Retrieve the X11 window handle for the browser.
    ::Window window = browser->GetHost()->GetWindowHandle();
    ASSERT(window != kNullWindowHandle);

    // Retrieve the atoms required by the below XChangeProperty call.
    const char* kAtoms[] = {
      "_NET_WM_NAME",
      "UTF8_STRING"
    };
    Atom atoms[2];
    int result = XInternAtoms(display, const_cast<char**>(kAtoms), 2, false,
                              atoms);
    if (!result)
      ASSERT(false);

    // Set the window title.
    XChangeProperty(display,
                    window,
                    atoms[0],
                    atoms[1],
                    8,
                    PropModeReplace,
                    reinterpret_cast<const unsigned char*>(titleStr.c_str()),
                    titleStr.size());

    // TODO(erg): This is technically wrong. So XStoreName and friends expect
    // this in Host Portable Character Encoding instead of UTF-8, which I
    // believe is Compound Text. This shouldn't matter 90% of the time since
    // this is the fallback to the UTF8 property above.
    XStoreName(display, browser->GetHost()->GetWindowHandle(),
               titleStr.c_str());
  }
}

void ClientHandler::SendNotification(NotificationType type) {
  // TODO(port): Implement this method.
}

void ClientHandler::SetLoading(bool isLoading) {
  if (isLoading)
    gtk_widget_set_sensitive(GTK_WIDGET(m_StopHwnd), true);
  else
    gtk_widget_set_sensitive(GTK_WIDGET(m_StopHwnd), false);
}

void ClientHandler::SetNavState(bool canGoBack, bool canGoForward) {
  if (canGoBack)
    gtk_widget_set_sensitive(GTK_WIDGET(m_BackHwnd), true);
  else
    gtk_widget_set_sensitive(GTK_WIDGET(m_BackHwnd), false);

  if (canGoForward)
    gtk_widget_set_sensitive(GTK_WIDGET(m_ForwardHwnd), true);
  else
    gtk_widget_set_sensitive(GTK_WIDGET(m_ForwardHwnd), false);
}

std::string ClientHandler::GetDownloadPath(const std::string& file_name) {
  return std::string();
}

<|endoftext|>


<commit_before>/* Copyright (c) 2014 Quanta Research Cambridge, Inc
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */
#include <sys/mman.h>
#include <errno.h>
#include "dmaManager.h"
#include "MemwriteIndication.h"
#include "MemwriteRequest.h"

static void memdump(unsigned char *p, int len, const char *title)
{
int i;

    i = 0;
    while (len > 0) {
        if (!(i & 0xf)) {
            if (i > 0)
                printf("\n");
            printf("%s: ",title);
        }
        printf("%02x ", *p++);
        i++;
        len--;
    }
    printf("\n");
}

static sem_t done_sem;
class MemwriteIndication : public MemwriteIndicationWrapper
{
public:
  MemwriteIndication(int id) : MemwriteIndicationWrapper(id){}

  virtual void writeDone ( uint32_t srcGen ){
    fprintf(stderr, "Memwrite::writeDone (%08x)\n", srcGen);
    sem_post(&done_sem);
  }
  virtual void writeProgress ( uint32_t numtodo ){
    fprintf(stderr, "Memwrite::writeProgress (%08x)\n", numtodo);
  }
};

MemwriteIndication *deviceIndication;
int main(int argc, const char **argv)
{
    size_t alloc_sz = 4096; //1024*1024;
  MemwriteRequestProxy *device = new MemwriteRequestProxy(IfcNames_MemwriteRequestS2H);
  deviceIndication = new MemwriteIndication(IfcNames_MemwriteIndicationH2S);
  DmaManager *dma = platformInit();

  device->pint.busyType = BUSY_SPIN;   /* spin until request portal 'notFull' */
  //dmap->pint.busyType = BUSY_SPIN;   /* spin until request portal 'notFull' */

  sem_init(&done_sem, 1, 0);

  int iters = 64;

  int mismatchCount = 0;

  for (int iter = 0; iter < iters; iter++) {
      int dstAlloc = portalAlloc(alloc_sz, 1);
      unsigned int *dstBuffer = (unsigned int *)portalMmap(dstAlloc, alloc_sz);

      for (uint32_t i = 0; i < alloc_sz/sizeof(uint32_t); i++)
	  dstBuffer[i] = 0xDEADBEEF;

#ifndef USE_ACP
      fprintf(stderr, "flushing cache\n");
      portalCacheFlush(dstAlloc, dstBuffer, alloc_sz, 1);
#endif

      fprintf(stderr, "parent::starting write\n");
      mismatchCount = 0;
      unsigned int ref_dstAlloc = dma->reference(dstAlloc);
      fprintf(stderr, "dma->reference %d\n", ref_dstAlloc);
      int burstLenBytes = 16*sizeof(uint32_t);
      device->startWrite(ref_dstAlloc, alloc_sz, alloc_sz / burstLenBytes, burstLenBytes);

      sem_wait(&done_sem);
      memdump((unsigned char *)dstBuffer, 32, "MEM");
      for (uint32_t i = 0; i < alloc_sz/sizeof(uint32_t); i++) {
	  if (dstBuffer[i] != i)
	      mismatchCount++;
      }
      fprintf(stderr, "%s: done mismatchCount=%d\n", __FUNCTION__, mismatchCount);

      fprintf(stderr, "%s: calling munmap\n", __FUNCTION__);
      int unmapped = munmap(dstBuffer, alloc_sz);
      if (unmapped != 0)
	  fprintf(stderr, "Failed to unmap dstBuffer errno=%d:%s\n", errno, strerror(errno));

      fprintf(stderr, "%s: close\n", __FUNCTION__);
      close(dstAlloc);

      fprintf(stderr, "%s: calling dereference\n", __FUNCTION__);
      dma->dereference(ref_dstAlloc);
      fprintf(stderr, "%s: after dereference\n", __FUNCTION__);
  }

  return (mismatchCount == 0) ? 0 : 1;
}
<commit_msg>print platformStatistics in memserver_write test<commit_after>/* Copyright (c) 2014 Quanta Research Cambridge, Inc
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */
#include <sys/mman.h>
#include <errno.h>
#include "dmaManager.h"
#include "MemwriteIndication.h"
#include "MemwriteRequest.h"

static void memdump(unsigned char *p, int len, const char *title)
{
int i;

    i = 0;
    while (len > 0) {
        if (!(i & 0xf)) {
            if (i > 0)
                printf("\n");
            printf("%s: ",title);
        }
        printf("%02x ", *p++);
        i++;
        len--;
    }
    printf("\n");
}

static sem_t done_sem;
class MemwriteIndication : public MemwriteIndicationWrapper
{
public:
  MemwriteIndication(int id) : MemwriteIndicationWrapper(id){}

  virtual void writeDone ( uint32_t srcGen ){
    fprintf(stderr, "Memwrite::writeDone (%08x)\n", srcGen);
    sem_post(&done_sem);
  }
  virtual void writeProgress ( uint32_t numtodo ){
    fprintf(stderr, "Memwrite::writeProgress (%08x)\n", numtodo);
  }
};

MemwriteIndication *deviceIndication;
int main(int argc, const char **argv)
{
    size_t alloc_sz = 4096; //1024*1024;
  MemwriteRequestProxy *device = new MemwriteRequestProxy(IfcNames_MemwriteRequestS2H);
  deviceIndication = new MemwriteIndication(IfcNames_MemwriteIndicationH2S);
  DmaManager *dma = platformInit();

  device->pint.busyType = BUSY_SPIN;   /* spin until request portal 'notFull' */
  //dmap->pint.busyType = BUSY_SPIN;   /* spin until request portal 'notFull' */

  sem_init(&done_sem, 1, 0);

  int iters = 64;

  int mismatchCount = 0;

  for (int iter = 0; iter < iters; iter++) {
      int dstAlloc = portalAlloc(alloc_sz, 1);
      unsigned int *dstBuffer = (unsigned int *)portalMmap(dstAlloc, alloc_sz);

      for (uint32_t i = 0; i < alloc_sz/sizeof(uint32_t); i++)
	  dstBuffer[i] = 0xDEADBEEF;

#ifndef USE_ACP
      fprintf(stderr, "flushing cache\n");
      portalCacheFlush(dstAlloc, dstBuffer, alloc_sz, 1);
#endif

      fprintf(stderr, "parent::starting write\n");
      mismatchCount = 0;
      unsigned int ref_dstAlloc = dma->reference(dstAlloc);
      fprintf(stderr, "dma->reference %d\n", ref_dstAlloc);
      int burstLenBytes = 16*sizeof(uint32_t);
      device->startWrite(ref_dstAlloc, alloc_sz, alloc_sz / burstLenBytes, burstLenBytes);

      sem_wait(&done_sem);
      memdump((unsigned char *)dstBuffer, 32, "MEM");
      for (uint32_t i = 0; i < alloc_sz/sizeof(uint32_t); i++) {
	  if (dstBuffer[i] != i)
	      mismatchCount++;
      }
      fprintf(stderr, "%s: done mismatchCount=%d\n", __FUNCTION__, mismatchCount);
      platformStatistics();

      fprintf(stderr, "%s: calling munmap\n", __FUNCTION__);
      int unmapped = munmap(dstBuffer, alloc_sz);
      if (unmapped != 0)
	  fprintf(stderr, "Failed to unmap dstBuffer errno=%d:%s\n", errno, strerror(errno));

      fprintf(stderr, "%s: close\n", __FUNCTION__);
      close(dstAlloc);

      fprintf(stderr, "%s: calling dereference\n", __FUNCTION__);
      dma->dereference(ref_dstAlloc);
      fprintf(stderr, "%s: after dereference\n", __FUNCTION__);
  }

  return (mismatchCount == 0) ? 0 : 1;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: unomailmerge.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: vg $ $Date: 2005-03-08 13:42:15 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _UNOMAILMERGE_HXX_
#define _UNOMAILMERGE_HXX_

#ifndef _CPPUHELPER_IMPLBASE5_HXX_
#include <cppuhelper/implbase5.hxx> // WeakImplHelper4
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.hxx>    // OMultiTypeInterfaceContainerHelperVar
#endif
#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>  // !! needed for OMultiTypeInterfaceContainerHelperVar !!
#endif

#ifndef _COM_SUN_STAR_TASK_XJOB_HPP_
#include <com/sun/star/task/XJob.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYCHANGEEVENT_HPP_
#include <com/sun/star/beans/PropertyChangeEvent.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_XMAILMERGEBROADCASTER_HPP_
#include <com/sun/star/text/XMailMergeBroadcaster.hpp>
#endif

#ifndef _SFX_ITEMPROP_HXX
#include <svtools/itemprop.hxx>
#endif
#ifndef _SFX_OBJSH_HXX
#include <sfx2/objsh.hxx>   // SfxObjectShellRef
#endif

namespace com { namespace sun { namespace star {

    namespace sdbc {
        class XResultSet;
        class XConnection;
    }
    namespace frame {
        class XModel;
    }
    namespace lang {
        class XMultiServiceFactory;
    }
    namespace text {
        class XMailMergeListener;
        struct MailMergeEvent;
    }
    namespace beans{
        struct PropertyValue;
    }

}}}

namespace rtl {
    class OUString;
}

///////////////////////////////////////////////////////////////////////////

// uses templates from <cppuhelper/interfacecontainer.h>
// and <unotools/configitem.hxx>

// helper function call class
struct PropHashType_Impl
{
    size_t operator()(const INT32 &s) const { return s; }
};

typedef cppu::OMultiTypeInterfaceContainerHelperVar
    <
        INT32,
        PropHashType_Impl,
        std::equal_to< INT32 >
    > OPropertyListenerContainerHelper;

////////////////////////////////////////////////////////////

class SwXMailMerge :
    public cppu::WeakImplHelper5
    <
        com::sun::star::task::XJob,
        com::sun::star::beans::XPropertySet,
        com::sun::star::text::XMailMergeBroadcaster,
        com::sun::star::lang::XComponent,
        com::sun::star::lang::XServiceInfo
    >
{
    cppu::OInterfaceContainerHelper     aEvtListeners;
    cppu::OInterfaceContainerHelper     aMergeListeners;
    OPropertyListenerContainerHelper    aPropListeners;

    //SfxItemPropertySet          aPropSet;
    const SfxItemPropertyMap*   pMap;

    SfxObjectShellRef xDocSh;   // the document

    String          aTmpFileName;

    // properties of mail merge service
    com::sun::star::uno::Sequence< com::sun::star::uno::Any >           aSelection;
    com::sun::star::uno::Reference< com::sun::star::sdbc::XResultSet >  xResultSet;
    com::sun::star::uno::Reference< com::sun::star::sdbc::XConnection > xConnection;
    com::sun::star::uno::Reference< com::sun::star::frame::XModel >     xModel;
    rtl::OUString   aDataSourceName;
    rtl::OUString   aDataCommand;
    rtl::OUString   aFilter;
    rtl::OUString   aDocumentURL;
    rtl::OUString   aOutputURL;
    rtl::OUString   aFileNamePrefix;
    sal_Int32       nDataCommandType;
    sal_Int16       nOutputType;
    sal_Bool        bEscapeProcessing;
    sal_Bool        bSinglePrintJobs;
    sal_Bool        bFileNameFromColumn;

    ::rtl::OUString                                         sInServerPassword;
    ::rtl::OUString                                         sOutServerPassword;
    ::rtl::OUString                                         sSubject;
    ::rtl::OUString                                         sAddressFromColumn;
    ::rtl::OUString                                         sMailBody;
    ::rtl::OUString                                         sAttachmentName;
    ::rtl::OUString                                         sAttachmentFilter;
    com::sun::star::uno::Sequence< ::rtl::OUString >        aCopiesTo;
    com::sun::star::uno::Sequence< ::rtl::OUString >        aBlindCopiesTo;
    sal_Bool                                                bSendAsHTML;
    sal_Bool                                                bSendAsAttachment;

    com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aPrintSettings;

    sal_Bool                                                bSaveAsSingleFile;
    ::rtl::OUString                                         sSaveFilter;
    ::rtl::OUString                                         sSaveFilterOptions;
    com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aSaveFilterData;

    sal_Bool        bDisposing;

    void    launchEvent( const com::sun::star::beans::PropertyChangeEvent &rEvt ) const;

    // disallow use of copy-constructor and assignment-operator for now
    SwXMailMerge( const SwXMailMerge & );
    SwXMailMerge & operator = ( const SwXMailMerge & );
protected:
    virtual ~SwXMailMerge();
public:
    SwXMailMerge();

    void LaunchMailMergeEvent( const com::sun::star::text::MailMergeEvent &rData ) const;

    // XJob
    virtual ::com::sun::star::uno::Any SAL_CALL execute( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& Arguments ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);

    // XPropertySet
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    // XMailMergeBroadcaster
    virtual void SAL_CALL addMailMergeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::text::XMailMergeListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeMailMergeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::text::XMailMergeListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);

    // XComponent
    virtual void SAL_CALL dispose(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);

    // XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  ) throw (::com::sun::star::uno::RuntimeException);
};

extern com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL SwXMailMerge_getSupportedServiceNames() throw();
extern rtl::OUString SAL_CALL SwXMailMerge_getImplementationName() throw();
extern com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SAL_CALL SwXMailMerge_createInstance(const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > & rSMgr) throw( com::sun::star::uno::Exception );

////////////////////////////////////////////////////////////

#endif

<commit_msg>INTEGRATION: CWS ooo19126 (1.5.276); FILE MERGED 2005/09/05 13:36:54 rt 1.5.276.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: unomailmerge.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 02:26:34 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _UNOMAILMERGE_HXX_
#define _UNOMAILMERGE_HXX_

#ifndef _CPPUHELPER_IMPLBASE5_HXX_
#include <cppuhelper/implbase5.hxx> // WeakImplHelper4
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.hxx>    // OMultiTypeInterfaceContainerHelperVar
#endif
#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>  // !! needed for OMultiTypeInterfaceContainerHelperVar !!
#endif

#ifndef _COM_SUN_STAR_TASK_XJOB_HPP_
#include <com/sun/star/task/XJob.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYCHANGEEVENT_HPP_
#include <com/sun/star/beans/PropertyChangeEvent.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_XMAILMERGEBROADCASTER_HPP_
#include <com/sun/star/text/XMailMergeBroadcaster.hpp>
#endif

#ifndef _SFX_ITEMPROP_HXX
#include <svtools/itemprop.hxx>
#endif
#ifndef _SFX_OBJSH_HXX
#include <sfx2/objsh.hxx>   // SfxObjectShellRef
#endif

namespace com { namespace sun { namespace star {

    namespace sdbc {
        class XResultSet;
        class XConnection;
    }
    namespace frame {
        class XModel;
    }
    namespace lang {
        class XMultiServiceFactory;
    }
    namespace text {
        class XMailMergeListener;
        struct MailMergeEvent;
    }
    namespace beans{
        struct PropertyValue;
    }

}}}

namespace rtl {
    class OUString;
}

///////////////////////////////////////////////////////////////////////////

// uses templates from <cppuhelper/interfacecontainer.h>
// and <unotools/configitem.hxx>

// helper function call class
struct PropHashType_Impl
{
    size_t operator()(const INT32 &s) const { return s; }
};

typedef cppu::OMultiTypeInterfaceContainerHelperVar
    <
        INT32,
        PropHashType_Impl,
        std::equal_to< INT32 >
    > OPropertyListenerContainerHelper;

////////////////////////////////////////////////////////////

class SwXMailMerge :
    public cppu::WeakImplHelper5
    <
        com::sun::star::task::XJob,
        com::sun::star::beans::XPropertySet,
        com::sun::star::text::XMailMergeBroadcaster,
        com::sun::star::lang::XComponent,
        com::sun::star::lang::XServiceInfo
    >
{
    cppu::OInterfaceContainerHelper     aEvtListeners;
    cppu::OInterfaceContainerHelper     aMergeListeners;
    OPropertyListenerContainerHelper    aPropListeners;

    //SfxItemPropertySet          aPropSet;
    const SfxItemPropertyMap*   pMap;

    SfxObjectShellRef xDocSh;   // the document

    String          aTmpFileName;

    // properties of mail merge service
    com::sun::star::uno::Sequence< com::sun::star::uno::Any >           aSelection;
    com::sun::star::uno::Reference< com::sun::star::sdbc::XResultSet >  xResultSet;
    com::sun::star::uno::Reference< com::sun::star::sdbc::XConnection > xConnection;
    com::sun::star::uno::Reference< com::sun::star::frame::XModel >     xModel;
    rtl::OUString   aDataSourceName;
    rtl::OUString   aDataCommand;
    rtl::OUString   aFilter;
    rtl::OUString   aDocumentURL;
    rtl::OUString   aOutputURL;
    rtl::OUString   aFileNamePrefix;
    sal_Int32       nDataCommandType;
    sal_Int16       nOutputType;
    sal_Bool        bEscapeProcessing;
    sal_Bool        bSinglePrintJobs;
    sal_Bool        bFileNameFromColumn;

    ::rtl::OUString                                         sInServerPassword;
    ::rtl::OUString                                         sOutServerPassword;
    ::rtl::OUString                                         sSubject;
    ::rtl::OUString                                         sAddressFromColumn;
    ::rtl::OUString                                         sMailBody;
    ::rtl::OUString                                         sAttachmentName;
    ::rtl::OUString                                         sAttachmentFilter;
    com::sun::star::uno::Sequence< ::rtl::OUString >        aCopiesTo;
    com::sun::star::uno::Sequence< ::rtl::OUString >        aBlindCopiesTo;
    sal_Bool                                                bSendAsHTML;
    sal_Bool                                                bSendAsAttachment;

    com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aPrintSettings;

    sal_Bool                                                bSaveAsSingleFile;
    ::rtl::OUString                                         sSaveFilter;
    ::rtl::OUString                                         sSaveFilterOptions;
    com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aSaveFilterData;

    sal_Bool        bDisposing;

    void    launchEvent( const com::sun::star::beans::PropertyChangeEvent &rEvt ) const;

    // disallow use of copy-constructor and assignment-operator for now
    SwXMailMerge( const SwXMailMerge & );
    SwXMailMerge & operator = ( const SwXMailMerge & );
protected:
    virtual ~SwXMailMerge();
public:
    SwXMailMerge();

    void LaunchMailMergeEvent( const com::sun::star::text::MailMergeEvent &rData ) const;

    // XJob
    virtual ::com::sun::star::uno::Any SAL_CALL execute( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& Arguments ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);

    // XPropertySet
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    // XMailMergeBroadcaster
    virtual void SAL_CALL addMailMergeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::text::XMailMergeListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeMailMergeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::text::XMailMergeListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);

    // XComponent
    virtual void SAL_CALL dispose(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);

    // XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  ) throw (::com::sun::star::uno::RuntimeException);
};

extern com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL SwXMailMerge_getSupportedServiceNames() throw();
extern rtl::OUString SAL_CALL SwXMailMerge_getImplementationName() throw();
extern com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SAL_CALL SwXMailMerge_createInstance(const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > & rSMgr) throw( com::sun::star::uno::Exception );

////////////////////////////////////////////////////////////

#endif

<|endoftext|>


<commit_before>#include "sshtunneloutconnection.h"
#include "sshtunnelout.h"
#include "sshclient.h"

Q_LOGGING_CATEGORY(logsshtunneloutconnection, "ssh.tunnelout.connection")
Q_LOGGING_CATEGORY(logsshtunneloutconnectiontransfer, "ssh.tunnelout.connection.transfer")

#define DEBUGCH qCDebug(logsshtunneloutconnection) << m_name
#define DEBUGTX qCDebug(logsshtunneloutconnectiontransfer) << m_name

#define SOCKET_WRITE_ERROR (-1001)

SshTunnelOutConnection::SshTunnelOutConnection(const QString &name, SshClient *client)
    : SshChannel(name, client)
    , m_connector(client, name)
{
    QObject::connect(this, &SshTunnelOutConnection::sendEvent, this, &SshTunnelOutConnection::_eventLoop, Qt::QueuedConnection);
    QObject::connect(&m_connector, &SshTunnelDataConnector::sendEvent, this, &SshTunnelOutConnection::sendEvent);
    DEBUGCH << "Create SshTunnelOutConnection (constructor)";
    emit sendEvent();
}

void SshTunnelOutConnection::configure(QTcpServer *server, quint16 remotePort, QString target)
{
    m_server = server;
    m_port = remotePort;
    m_target = target;
}

SshTunnelOutConnection::~SshTunnelOutConnection()
{
    DEBUGCH << "Free SshTunnelOutConnection (destructor)";
    delete m_sock;
}

void SshTunnelOutConnection::close()
{
    DEBUGCH << "Close SshTunnelOutConnection asked";
    setChannelState(ChannelState::Close);
    emit sendEvent();
}

void SshTunnelOutConnection::sshDataReceived()
{
    DEBUGCH << "sshDataReceived: SSH data received";
    m_connector.sshDataReceived();
    emit sendEvent();
}

void SshTunnelOutConnection::_eventLoop()
{
    switch(channelState())
    {
        case Openning:
        {
            if ( ! m_sshClient->takeChannelCreationMutex(this) )
            {
                return;
            }
            m_sshChannel = libssh2_channel_direct_tcpip(m_sshClient->session(), qPrintable(m_target), m_port);
            m_sshClient->releaseChannelCreationMutex(this);
            if (m_sshChannel == nullptr)
            {
                char *emsg;
                int size;
                int ret = libssh2_session_last_error(m_sshClient->session(), &emsg, &size, 0);
                if(ret == LIBSSH2_ERROR_EAGAIN)
                {
                    return;
                }
                if(!m_error)
                {
                    qCDebug(logsshtunneloutconnection) << "Refuse client socket connection on " << m_server->serverPort() << QString(emsg);
                    m_error = true;
                    m_sock = m_server->nextPendingConnection();
                    if(m_sock)
                    {
                        m_sock->close();
                    }
                    m_server->close();
                }
                setChannelState(ChannelState::Error);
                qCWarning(logsshtunneloutconnection) << "Channel session open failed";
                return;
            }
            DEBUGCH << "Channel session opened";
            setChannelState(ChannelState::Exec);
        }

        FALLTHROUGH; case Exec:
        {
            m_sock = m_server->nextPendingConnection();
            if(!m_sock)
            {
                m_server->close();
                setChannelState(ChannelState::Error);
                qCWarning(logsshtunneloutconnection) << "Fail to get client socket";
                setChannelState(ChannelState::Close);
                return;
            }

            QObject::connect(m_sock, &QObject::destroyed, [this](){ DEBUGCH << "Client Socket destroyed";});
            m_name = QString(m_name + ":%1").arg(m_sock->localPort());
            DEBUGCH << "createConnection: " << m_sock << m_sock->localPort();
            m_connector.setChannel(m_sshChannel);
            m_connector.setSock(m_sock);
            setChannelState(ChannelState::Ready);
            /* OK, next step */
        }

        FALLTHROUGH; case Ready:
        {
            if(!m_connector.process())
            {
                setChannelState(ChannelState::Close);
            }
            return;
        }

        case Close:
        {
            DEBUGCH << "closeChannel";
            m_connector.close();
            setChannelState(ChannelState::WaitClose);
        }

        FALLTHROUGH; case WaitClose:
        {
            DEBUGCH << "Wait close channel";
            if(m_connector.isClosed())
            {
                setChannelState(ChannelState::Freeing);
            }
            else
            {
                m_connector.process();
                return;
            }
        }

        FALLTHROUGH; case Freeing:
        {
            DEBUGCH << "free Channel";

            int ret = libssh2_channel_free(m_sshChannel);
            if(ret == LIBSSH2_ERROR_EAGAIN)
            {
                return;
            }
            if(ret < 0)
            {
                if(!m_error)
                {
                    m_error = true;
                    qCWarning(logsshtunneloutconnection) << "Failed to free channel: " << sshErrorToString(ret);
                }
            }

            if(m_error)
            {
                setChannelState(ChannelState::Error);
            }
            else
            {
                setChannelState(ChannelState::Free);
            }
            m_sshChannel = nullptr;
            QObject::disconnect(m_sshClient, &SshClient::sshDataReceived, this, &SshTunnelOutConnection::sshDataReceived);
            return;
        }

        case Free:
        {
            qCDebug(logsshtunneloutconnection) << "Channel" << m_name << "is free";
            return;
        }

        case Error:
        {
            qCDebug(logsshtunneloutconnection) << "Channel" << m_name << "is in error state";
            return;
        }
    }
}

<commit_msg>tunneloutconnection: After error, need to be free<commit_after>#include "sshtunneloutconnection.h"
#include "sshtunnelout.h"
#include "sshclient.h"

Q_LOGGING_CATEGORY(logsshtunneloutconnection, "ssh.tunnelout.connection")
Q_LOGGING_CATEGORY(logsshtunneloutconnectiontransfer, "ssh.tunnelout.connection.transfer")

#define DEBUGCH qCDebug(logsshtunneloutconnection) << m_name
#define DEBUGTX qCDebug(logsshtunneloutconnectiontransfer) << m_name

#define SOCKET_WRITE_ERROR (-1001)

SshTunnelOutConnection::SshTunnelOutConnection(const QString &name, SshClient *client)
    : SshChannel(name, client)
    , m_connector(client, name)
{
    QObject::connect(this, &SshTunnelOutConnection::sendEvent, this, &SshTunnelOutConnection::_eventLoop, Qt::QueuedConnection);
    QObject::connect(&m_connector, &SshTunnelDataConnector::sendEvent, this, &SshTunnelOutConnection::sendEvent);
    DEBUGCH << "Create SshTunnelOutConnection (constructor)";
    emit sendEvent();
}

void SshTunnelOutConnection::configure(QTcpServer *server, quint16 remotePort, QString target)
{
    m_server = server;
    m_port = remotePort;
    m_target = target;
}

SshTunnelOutConnection::~SshTunnelOutConnection()
{
    DEBUGCH << "Free SshTunnelOutConnection (destructor)";
    delete m_sock;
}

void SshTunnelOutConnection::close()
{
    DEBUGCH << "Close SshTunnelOutConnection asked";
    setChannelState(ChannelState::Close);
    emit sendEvent();
}

void SshTunnelOutConnection::sshDataReceived()
{
    DEBUGCH << "sshDataReceived: SSH data received";
    m_connector.sshDataReceived();
    emit sendEvent();
}

void SshTunnelOutConnection::_eventLoop()
{
    switch(channelState())
    {
        case Openning:
        {
            if ( ! m_sshClient->takeChannelCreationMutex(this) )
            {
                return;
            }
            m_sshChannel = libssh2_channel_direct_tcpip(m_sshClient->session(), qPrintable(m_target), m_port);
            m_sshClient->releaseChannelCreationMutex(this);
            if (m_sshChannel == nullptr)
            {
                char *emsg;
                int size;
                int ret = libssh2_session_last_error(m_sshClient->session(), &emsg, &size, 0);
                if(ret == LIBSSH2_ERROR_EAGAIN)
                {
                    return;
                }
                if(!m_error)
                {
                    qCDebug(logsshtunneloutconnection) << "Refuse client socket connection on " << m_server->serverPort() << QString(emsg);
                    m_error = true;
                    m_sock = m_server->nextPendingConnection();
                    if(m_sock)
                    {
                        m_sock->close();
                    }
                    m_server->close();
                }
                setChannelState(ChannelState::Error);
                qCWarning(logsshtunneloutconnection) << "Channel session open failed";
                return;
            }
            DEBUGCH << "Channel session opened";
            setChannelState(ChannelState::Exec);
        }

        FALLTHROUGH; case Exec:
        {
            m_sock = m_server->nextPendingConnection();
            if(!m_sock)
            {
                m_server->close();
                setChannelState(ChannelState::Error);
                qCWarning(logsshtunneloutconnection) << "Fail to get client socket";
                setChannelState(ChannelState::Close);
                return;
            }

            QObject::connect(m_sock, &QObject::destroyed, [this](){ DEBUGCH << "Client Socket destroyed";});
            m_name = QString(m_name + ":%1").arg(m_sock->localPort());
            DEBUGCH << "createConnection: " << m_sock << m_sock->localPort();
            m_connector.setChannel(m_sshChannel);
            m_connector.setSock(m_sock);
            setChannelState(ChannelState::Ready);
            /* OK, next step */
        }

        FALLTHROUGH; case Ready:
        {
            if(!m_connector.process())
            {
                setChannelState(ChannelState::Close);
            }
            return;
        }

        case Close:
        {
            DEBUGCH << "closeChannel";
            m_connector.close();
            setChannelState(ChannelState::WaitClose);
        }

        FALLTHROUGH; case WaitClose:
        {
            DEBUGCH << "Wait close channel";
            if(m_connector.isClosed())
            {
                setChannelState(ChannelState::Freeing);
            }
            else
            {
                m_connector.process();
                return;
            }
        }

        FALLTHROUGH; case Freeing:
        {
            DEBUGCH << "free Channel";

            int ret = libssh2_channel_free(m_sshChannel);
            if(ret == LIBSSH2_ERROR_EAGAIN)
            {
                return;
            }
            if(ret < 0)
            {
                if(!m_error)
                {
                    m_error = true;
                    qCWarning(logsshtunneloutconnection) << "Failed to free channel: " << sshErrorToString(ret);
                }
            }

            if(m_error)
            {
                setChannelState(ChannelState::Error);
            }
            else
            {
                setChannelState(ChannelState::Free);
            }
            m_sshChannel = nullptr;
            QObject::disconnect(m_sshClient, &SshClient::sshDataReceived, this, &SshTunnelOutConnection::sshDataReceived);
            return;
        }

        case Free:
        {
            qCDebug(logsshtunneloutconnection) << "Channel" << m_name << "is free";
            return;
        }

        case Error:
        {
            qCDebug(logsshtunneloutconnection) << "Channel" << m_name << "is in error state";
            setChannelState(Free);
            return;
        }
    }
}

<|endoftext|>