<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "mlinearlayoutpolicy_p.h"

#include <QtGui/QGraphicsLinearLayout>
#include <QtGui/QGraphicsWidget>
#include <QtGui/QWidget>

#include "mwidgetcontroller.h"

#include "mlayout.h"
#include "mlayouthelper_p.h"
MLinearLayoutPolicyPrivate::MLinearLayoutPolicyPrivate(MLayout *layout, Qt::Orientation orientation) :
    MAbstractLayoutPolicyPrivate(layout),
    engineWidget(new QGraphicsWidget),
    engine(new QGraphicsLinearLayout(orientation, engineWidget)),
    notifyWidgetsOfLayoutPositionEnabled(false)
{
    rowCount = 0;
    engineWidget->setContentsMargins(0, 0, 0, 0);
    engineWidget->setMinimumSize(0, 0);
    engineWidget->setMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
}

MLinearLayoutPolicyPrivate::~MLinearLayoutPolicyPrivate()
{
    delete engineWidget; //This deletes the engine, which in turn deletes all of its children
}

void MLinearLayoutPolicyPrivate::fixIndex(int *index) const
{
    if (uint(*index) >= uint(rowCount))
        *index = rowCount;
}

void MLinearLayoutPolicyPrivate::refreshEngine()
{
    bool directionChanged = engineWidget->layoutDirection() != layout->layoutDirection();
    engineWidget->setLayoutDirection(layout->layoutDirection());   //Make sure that we have our RTL/LTR correct

    engine->invalidate();
    for (int i = engine->count() - 1; i >= 0; --i) {
        ProxyItem *item = static_cast<ProxyItem *>(engine->itemAt(i));
        item->refresh();
    }
    qreal left, top, right, bottom;
    layout->getContentsMargins(&left, &top, &right, &bottom);
    engine->setContentsMargins(left, top, right, bottom);

    engine->updateGeometry();

    //We need to make engine->geometry() equal the layout->geometry() so that the items are in the right place
    qreal topMargin = layout->geometry().top();
    qreal leftMargin = layout->geometry().left();
    qreal width = layout->geometry().right();
    qreal height = layout->geometry().bottom();
    engineWidget->setContentsMargins(leftMargin, topMargin, 0, 0);
    engineWidget->resize(width, height);

    //update layout positions here only if layout direction has changed
    if( directionChanged && notifyWidgetsOfLayoutPositionEnabled )
        notifyAllWidgetsOfLayoutPosition();
}

void MLinearLayoutPolicyPrivate::notifyWidgetOfLayoutPosition(int index, M::Position position)
{
    MWidgetController* widget = dynamic_cast<MWidgetController*>(static_cast<ProxyItem *>(engine->itemAt(index))->proxiedItem());
    if( widget ) {
        widget->setLayoutPosition(position);
    }
}

void MLinearLayoutPolicyPrivate::notifyAffectedWidgetsOfLayoutPosition(int index, bool add )
{
    if( !notifyWidgetsOfLayoutPositionEnabled )
        return;

    //setup first, last and center positions based on layout direction (LTR or RTL) and orientation (VERT or HORIZ)
    M::Position first, last;
    if( layout->layoutDirection() == Qt::LeftToRight ) {
        first = (engine->orientation() == Qt::Horizontal) ? M::HorizontalLeftPosition : M::VerticalTopPosition;
        last = (engine->orientation() == Qt::Horizontal) ? M::HorizontalRightPosition : M::VerticalBottomPosition;
    }
    else {
        first = (engine->orientation() == Qt::Horizontal) ? M::HorizontalRightPosition : M::VerticalTopPosition;
        last = (engine->orientation() == Qt::Horizontal) ? M::HorizontalLeftPosition : M::VerticalBottomPosition;
    }
    M::Position center = (engine->orientation() == Qt::Horizontal) ? M::HorizontalCenterPosition : M::VerticalCenterPosition;

    //added to index
    if( add ) {
        //no more than three items in the layout, reposition them all
        if( engine->count() <= 3 )
            notifyAllWidgetsOfLayoutPosition();
        else {
            //added as first
            if( index == 0 ) {
                notifyWidgetOfLayoutPosition(0, first);
                notifyWidgetOfLayoutPosition(1, center);
            }
            //added as last
            else if( index == engine->count() - 1 ) {
                notifyWidgetOfLayoutPosition(engine->count()-2, center);
                notifyWidgetOfLayoutPosition(engine->count()-1, last);
            }
            //added to middle
            else {
                notifyWidgetOfLayoutPosition(index, center);
            }
        }
    }
    //removing item from index
    else {
        //remove positioning from the removed item
        notifyWidgetOfLayoutPosition(index, M::DefaultPosition);

        //change positioning of an affected item if item is removed from first or last position
        if( engine->count()-1 > 0 ) {
            //only one item remains after removal
            if( engine->count()-1 == 1 ) {
                notifyWidgetOfLayoutPosition((index == 0) ? 1 : 0, M::DefaultPosition);
            }
            else {
                //item is removed from first position, mark second item as first
                if( index == 0 ) {
                    notifyWidgetOfLayoutPosition(1, first);
                }
                //item is removed from last position, mark second last item as last
                else if( index == engine->count()-1 ) {
                    notifyWidgetOfLayoutPosition(engine->count()-2, last);
                }
            }
        }
    }

}

void MLinearLayoutPolicyPrivate::notifyAllWidgetsOfLayoutPosition()
{
    if( notifyWidgetsOfLayoutPositionEnabled ) {
        //setup first, last and center positions based on layout direction (LTR or RTL) and orientation (VERT or HORIZ)
        M::Position first, last;
        if( layout->layoutDirection() == Qt::LeftToRight ) {
            first = (engine->orientation() == Qt::Horizontal) ? M::HorizontalLeftPosition : M::VerticalTopPosition;
            last = (engine->orientation() == Qt::Horizontal) ? M::HorizontalRightPosition : M::VerticalBottomPosition;
        }
        else {
            first = (engine->orientation() == Qt::Horizontal) ? M::HorizontalRightPosition : M::VerticalTopPosition;
            last = (engine->orientation() == Qt::Horizontal) ? M::HorizontalLeftPosition : M::VerticalBottomPosition;
        }
        M::Position center = (engine->orientation() == Qt::Horizontal) ? M::HorizontalCenterPosition : M::VerticalCenterPosition;;

        //only one item in the layout
        if( engine->count() == 1 ) {
            notifyWidgetOfLayoutPosition(0, M::DefaultPosition);
        //more than one item in the layout
        } else if( engine->count() > 1 ){
            notifyWidgetOfLayoutPosition(0, first);
            notifyWidgetOfLayoutPosition(engine->count()-1, last);
            for( int i = 1; i < engine->count()-1; ++i ) {
                notifyWidgetOfLayoutPosition(i, center);
            }
        }
    //remove positioning from all the items
    } else {
        for( int i = 0; i < engine->count(); ++i ) {
            notifyWidgetOfLayoutPosition(i, M::DefaultPosition);
        }
    }
}

<commit_msg>Fixes: NB#187570 Application crashes when adding buttons and stretch to MLinearLayoutPolicy when notifyAllWidgetsOfLayoutPosition is enabled<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "mlinearlayoutpolicy_p.h"

#include <QtGui/QGraphicsLinearLayout>
#include <QtGui/QGraphicsWidget>
#include <QtGui/QWidget>

#include "mwidgetcontroller.h"

#include "mlayout.h"
#include "mlayouthelper_p.h"
MLinearLayoutPolicyPrivate::MLinearLayoutPolicyPrivate(MLayout *layout, Qt::Orientation orientation) :
    MAbstractLayoutPolicyPrivate(layout),
    engineWidget(new QGraphicsWidget),
    engine(new QGraphicsLinearLayout(orientation, engineWidget)),
    notifyWidgetsOfLayoutPositionEnabled(false)
{
    rowCount = 0;
    engineWidget->setContentsMargins(0, 0, 0, 0);
    engineWidget->setMinimumSize(0, 0);
    engineWidget->setMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);
}

MLinearLayoutPolicyPrivate::~MLinearLayoutPolicyPrivate()
{
    delete engineWidget; //This deletes the engine, which in turn deletes all of its children
}

void MLinearLayoutPolicyPrivate::fixIndex(int *index) const
{
    if (uint(*index) >= uint(rowCount))
        *index = rowCount;
}

void MLinearLayoutPolicyPrivate::refreshEngine()
{
    bool directionChanged = engineWidget->layoutDirection() != layout->layoutDirection();
    engineWidget->setLayoutDirection(layout->layoutDirection());   //Make sure that we have our RTL/LTR correct

    engine->invalidate();
    for (int i = engine->count() - 1; i >= 0; --i) {
        ProxyItem *item = static_cast<ProxyItem *>(engine->itemAt(i));
        item->refresh();
    }
    qreal left, top, right, bottom;
    layout->getContentsMargins(&left, &top, &right, &bottom);
    engine->setContentsMargins(left, top, right, bottom);

    engine->updateGeometry();

    //We need to make engine->geometry() equal the layout->geometry() so that the items are in the right place
    qreal topMargin = layout->geometry().top();
    qreal leftMargin = layout->geometry().left();
    qreal width = layout->geometry().right();
    qreal height = layout->geometry().bottom();
    engineWidget->setContentsMargins(leftMargin, topMargin, 0, 0);
    engineWidget->resize(width, height);

    //update layout positions here only if layout direction has changed
    if( directionChanged && notifyWidgetsOfLayoutPositionEnabled )
        notifyAllWidgetsOfLayoutPosition();
}

void MLinearLayoutPolicyPrivate::notifyWidgetOfLayoutPosition(int index, M::Position position)
{
    MWidgetController* widget = dynamic_cast<MWidgetController*>(static_cast<ProxyItem *>(engine->itemAt(index))->proxiedItem());
    if( widget ) {
        widget->setLayoutPosition(position);
    }
}

void MLinearLayoutPolicyPrivate::notifyAffectedWidgetsOfLayoutPosition(int index, bool add )
{
    if( !notifyWidgetsOfLayoutPositionEnabled )
        return;

    //setup first, last and center positions based on layout direction (LTR or RTL) and orientation (VERT or HORIZ)
    M::Position first, last;
    if( layout->layoutDirection() == Qt::LeftToRight ) {
        first = (engine->orientation() == Qt::Horizontal) ? M::HorizontalLeftPosition : M::VerticalTopPosition;
        last = (engine->orientation() == Qt::Horizontal) ? M::HorizontalRightPosition : M::VerticalBottomPosition;
    }
    else {
        first = (engine->orientation() == Qt::Horizontal) ? M::HorizontalRightPosition : M::VerticalTopPosition;
        last = (engine->orientation() == Qt::Horizontal) ? M::HorizontalLeftPosition : M::VerticalBottomPosition;
    }
    M::Position center = (engine->orientation() == Qt::Horizontal) ? M::HorizontalCenterPosition : M::VerticalCenterPosition;

    //added to index
    if( add ) {
        //no more than three items in the layout, reposition them all
        if( engine->count() <= 3 )
            notifyAllWidgetsOfLayoutPosition();
        else {
            //added as first
            if( index == 0 ) {
                notifyWidgetOfLayoutPosition(0, first);
                notifyWidgetOfLayoutPosition(1, center);
            }
            //added as last
            else if( index >= engine->count() - 1 ) {
                notifyWidgetOfLayoutPosition(engine->count()-2, center);
                notifyWidgetOfLayoutPosition(engine->count()-1, last);
            }
            //added to middle
            else {
                notifyWidgetOfLayoutPosition(index, center);
            }
        }
    }
    //removing item from index
    else {
        //remove positioning from the removed item
        notifyWidgetOfLayoutPosition(index, M::DefaultPosition);

        //change positioning of an affected item if item is removed from first or last position
        if( engine->count()-1 > 0 ) {
            //only one item remains after removal
            if( engine->count()-1 == 1 ) {
                notifyWidgetOfLayoutPosition((index == 0) ? 1 : 0, M::DefaultPosition);
            }
            else {
                //item is removed from first position, mark second item as first
                if( index == 0 ) {
                    notifyWidgetOfLayoutPosition(1, first);
                }
                //item is removed from last position, mark second last item as last
                else if( index == engine->count()-1 ) {
                    notifyWidgetOfLayoutPosition(engine->count()-2, last);
                }
            }
        }
    }

}

void MLinearLayoutPolicyPrivate::notifyAllWidgetsOfLayoutPosition()
{
    if( notifyWidgetsOfLayoutPositionEnabled ) {
        //setup first, last and center positions based on layout direction (LTR or RTL) and orientation (VERT or HORIZ)
        M::Position first, last;
        if( layout->layoutDirection() == Qt::LeftToRight ) {
            first = (engine->orientation() == Qt::Horizontal) ? M::HorizontalLeftPosition : M::VerticalTopPosition;
            last = (engine->orientation() == Qt::Horizontal) ? M::HorizontalRightPosition : M::VerticalBottomPosition;
        }
        else {
            first = (engine->orientation() == Qt::Horizontal) ? M::HorizontalRightPosition : M::VerticalTopPosition;
            last = (engine->orientation() == Qt::Horizontal) ? M::HorizontalLeftPosition : M::VerticalBottomPosition;
        }
        M::Position center = (engine->orientation() == Qt::Horizontal) ? M::HorizontalCenterPosition : M::VerticalCenterPosition;;

        //only one item in the layout
        if( engine->count() == 1 ) {
            notifyWidgetOfLayoutPosition(0, M::DefaultPosition);
        //more than one item in the layout
        } else if( engine->count() > 1 ){
            notifyWidgetOfLayoutPosition(0, first);
            notifyWidgetOfLayoutPosition(engine->count()-1, last);
            for( int i = 1; i < engine->count()-1; ++i ) {
                notifyWidgetOfLayoutPosition(i, center);
            }
        }
    //remove positioning from all the items
    } else {
        for( int i = 0; i < engine->count(); ++i ) {
            notifyWidgetOfLayoutPosition(i, M::DefaultPosition);
        }
    }
}

<|endoftext|>


<commit_before>#include "download.h"

#include "test-helpers.h"

using namespace podboat;

TEST_CASE("Require-view-update callback gets called when download progress or status changes",
	"[Download]")
{
	GIVEN("A Download object") {
		bool got_called = false;
		std::function<void()> callback = [&got_called]() {
			got_called = true;
		};

		Download d(callback);

		REQUIRE(d.status() == DlStatus::QUEUED);

		WHEN("its progress is updated (increased)") {
			d.set_progress(1.0, 1.0);

			THEN("the require-view-update callback gets called") {
				REQUIRE(got_called);
			}
		}

		WHEN("its progress has not changed") {
			d.set_progress(0.0, 1.0);

			THEN("the require-view-update callback does not get called") {
				REQUIRE_FALSE(got_called);
			}
		}

		WHEN("its status is changed") {
			d.set_status(DlStatus::DOWNLOADING);

			THEN("the require-view-update callback gets called") {
				REQUIRE(got_called);
			}
		}

		WHEN("when its status is not changed") {
			d.set_status(DlStatus::QUEUED);

			THEN("the require-view-update callback does not get called") {
				REQUIRE_FALSE(got_called);
			}
		}
	}
}

TEST_CASE("filename() returns download's target filename", "[Download]")
{
	auto emptyCallback = []() {};

	Download d(emptyCallback);

	SECTION("filename returns empty string by default") {
		REQUIRE(d.filename().empty());
	}

	SECTION("filename returns same string which is set via set_filename") {
		d.set_filename("abc");
		REQUIRE(d.filename() == "abc");
	}

	SECTION("filename will return the latest configured filename") {
		d.set_filename("abc");
		d.set_filename("def");

		REQUIRE(d.filename() == "def");
	}
}

TEST_CASE("percents_finished() takes current progress into account",
	"[Download]")
{
	auto emptyCallback = []() {};

	Download d(emptyCallback);

	SECTION("percents_finished() returns 0 by default") {
		REQUIRE(d.percents_finished() == 0);
	}

	SECTION("percents_finished() updates according to set_progress's arguments") {
		double downloaded = 3.0;
		double total = 7.0;
		d.set_progress(downloaded, total);

		REQUIRE(d.percents_finished() == Approx(100.0 * (downloaded / total)));
	}

	SECTION("percents_finished() takes offset into account") {
		double offset = 5.0;
		double downloaded = 3.0;
		double total = 12.0;

		d.set_offset(offset);
		d.set_progress(downloaded, total);

		auto expected = Approx(100.0 * ((downloaded + offset) / (total + offset)));
		REQUIRE(d.percents_finished() == expected);
	}

	SECTION("percents_finished() returns 0 if total is unknown (0)") {
		double downloaded = 3.0;
		double total = 0.0;
		d.set_progress(downloaded, total);

		REQUIRE(d.percents_finished() == 0);
	}
}
<commit_msg>Add test for Download::basename()<commit_after>#include "download.h"

#include "test-helpers.h"

using namespace podboat;

TEST_CASE("Require-view-update callback gets called when download progress or status changes",
	"[Download]")
{
	GIVEN("A Download object") {
		bool got_called = false;
		std::function<void()> callback = [&got_called]() {
			got_called = true;
		};

		Download d(callback);

		REQUIRE(d.status() == DlStatus::QUEUED);

		WHEN("its progress is updated (increased)") {
			d.set_progress(1.0, 1.0);

			THEN("the require-view-update callback gets called") {
				REQUIRE(got_called);
			}
		}

		WHEN("its progress has not changed") {
			d.set_progress(0.0, 1.0);

			THEN("the require-view-update callback does not get called") {
				REQUIRE_FALSE(got_called);
			}
		}

		WHEN("its status is changed") {
			d.set_status(DlStatus::DOWNLOADING);

			THEN("the require-view-update callback gets called") {
				REQUIRE(got_called);
			}
		}

		WHEN("when its status is not changed") {
			d.set_status(DlStatus::QUEUED);

			THEN("the require-view-update callback does not get called") {
				REQUIRE_FALSE(got_called);
			}
		}
	}
}

TEST_CASE("filename() returns download's target filename", "[Download]")
{
	auto emptyCallback = []() {};

	Download d(emptyCallback);

	SECTION("filename returns empty string by default") {
		REQUIRE(d.filename().empty());
	}

	SECTION("filename returns same string which is set via set_filename") {
		d.set_filename("abc");
		REQUIRE(d.filename() == "abc");
	}

	SECTION("filename will return the latest configured filename") {
		d.set_filename("abc");
		d.set_filename("def");

		REQUIRE(d.filename() == "def");
	}
}

TEST_CASE("percents_finished() takes current progress into account",
	"[Download]")
{
	auto emptyCallback = []() {};

	Download d(emptyCallback);

	SECTION("percents_finished() returns 0 by default") {
		REQUIRE(d.percents_finished() == 0);
	}

	SECTION("percents_finished() updates according to set_progress's arguments") {
		double downloaded = 3.0;
		double total = 7.0;
		d.set_progress(downloaded, total);

		REQUIRE(d.percents_finished() == Approx(100.0 * (downloaded / total)));
	}

	SECTION("percents_finished() takes offset into account") {
		double offset = 5.0;
		double downloaded = 3.0;
		double total = 12.0;

		d.set_offset(offset);
		d.set_progress(downloaded, total);

		auto expected = Approx(100.0 * ((downloaded + offset) / (total + offset)));
		REQUIRE(d.percents_finished() == expected);
	}

	SECTION("percents_finished() returns 0 if total is unknown (0)") {
		double downloaded = 3.0;
		double total = 0.0;
		d.set_progress(downloaded, total);

		REQUIRE(d.percents_finished() == 0);
	}
}

TEST_CASE("basename() returns all text after last slash in the filename",
	"[Download]")
{
	auto emptyCallback = []() {};

	Download d(emptyCallback);

	SECTION("basename() returns empty string by default") {
		REQUIRE(d.basename().empty());
	}

	SECTION("basename() returns full filename if it does not contain slashes") {
		std::string filename = "lorem_ipsum.txt";
		d.set_filename(filename);

		REQUIRE(d.basename() == filename);
	}

	SECTION("basename() returns only text after the last slash in the filename") {
		std::string basename = "lorem_ipsum.txt";
		std::string path = "/test/path/";
		std::string filename = path + basename;
		d.set_filename(filename);

		REQUIRE(d.basename() == basename);
	}
}
<|endoftext|>


<commit_before>/** Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License */
#include <stdio.h>

#include "utils/logoutput.h"

#include "layerPart.h"
#include "settings.h"

/*
The layer-part creation step is the first step in creating actual useful data for 3D printing.
It takes the result of the Slice step, which is an unordered list of polygons, and makes groups of polygons,
each of these groups is called a "part", which sometimes are also known as "islands". These parts represent
isolated areas in the 2D layer with possible holes.

Creating "parts" is an important step, as all elements in a single part should be printed before going to another part.
And all every bit inside a single part can be printed without the nozzle leaving the boundery of this part.

It's also the first step that stores the result in the "data storage" so all other steps can access it.
*/

void createLayerWithParts(SliceLayer& storageLayer, SlicerLayer* layer, int unionAllType)
{
    if (unionAllType & FIX_HORRIBLE_UNION_ALL_TYPE_B)
    {
        for(unsigned int i=0; i<layer->polygonList.size(); i++)
        {
            if (layer->polygonList[i].orientation())
                layer->polygonList[i].reverse();
        }
    }

    vector<Polygons> result;
    if (unionAllType & FIX_HORRIBLE_UNION_ALL_TYPE_C)
        result = layer->polygonList.offset(1000).splitIntoParts(unionAllType);
    else
        result = layer->polygonList.splitIntoParts(unionAllType);
    for(unsigned int i=0; i<result.size(); i++)
    {
        storageLayer.parts.push_back(SliceLayerPart());
        if (unionAllType & FIX_HORRIBLE_UNION_ALL_TYPE_C)
        {
            storageLayer.parts[i].outline.add(result[i][0]);
            storageLayer.parts[i].outline = storageLayer.parts[i].outline.offset(-1000);
        }else
            storageLayer.parts[i].outline = result[i];
        storageLayer.parts[i].boundaryBox.calculate(storageLayer.parts[i].outline);
    }
}

void createLayerParts(SliceVolumeStorage& storage, Slicer* slicer, int unionAllType)
{
    for(unsigned int layerNr = 0; layerNr < slicer->layers.size(); layerNr++)
    {
        storage.layers.push_back(SliceLayer());
        storage.layers[layerNr].sliceZ = slicer->layers[layerNr].z;
        storage.layers[layerNr].printZ = slicer->layers[layerNr].z;
        createLayerWithParts(storage.layers[layerNr], &slicer->layers[layerNr], unionAllType);
    }
}

void dumpLayerparts(SliceDataStorage& storage, const char* filename)
{
    FILE* out = fopen(filename, "w");
    fprintf(out, "<!DOCTYPE html>");
    Point3 modelSize = storage.modelSize;
    Point3 modelMin = storage.modelMin;

    for(unsigned int volumeIdx=0; volumeIdx<storage.volumes.size(); volumeIdx++)
    {
        for(unsigned int layerNr=0;layerNr<storage.volumes[volumeIdx].layers.size(); layerNr++)
        {
            fprintf(out, "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" style=\"width: 500px; height:500px\">\n");
            SliceLayer* layer = &storage.volumes[volumeIdx].layers[layerNr];
            for(unsigned int i=0;i<layer->parts.size();i++)
            {
                SliceLayerPart* part = &layer->parts[i];
                for(unsigned int j=0;j<part->outline.size();j++)
                {
                    fprintf(out, "<polygon points=\"");
                    for(unsigned int k=0;k<part->outline[j].size();k++)
                        fprintf(out, "%f,%f ", float(part->outline[j][k].X - modelMin.x)/modelSize.x*500, float(part->outline[j][k].Y - modelMin.y)/modelSize.y*500);
                    if (j == 0)
                        fprintf(out, "\" style=\"fill:gray; stroke:black;stroke-width:1\" />\n");
                    else
                        fprintf(out, "\" style=\"fill:red; stroke:black;stroke-width:1\" />\n");
                }
            }
            fprintf(out, "</svg>\n");
        }
    }
    fprintf(out, "");
    fclose(out);
}
<commit_msg>Remove unused include.<commit_after>/** Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License */
#include <stdio.h>

#include "layerPart.h"
#include "settings.h"

/*
The layer-part creation step is the first step in creating actual useful data for 3D printing.
It takes the result of the Slice step, which is an unordered list of polygons, and makes groups of polygons,
each of these groups is called a "part", which sometimes are also known as "islands". These parts represent
isolated areas in the 2D layer with possible holes.

Creating "parts" is an important step, as all elements in a single part should be printed before going to another part.
And all every bit inside a single part can be printed without the nozzle leaving the boundery of this part.

It's also the first step that stores the result in the "data storage" so all other steps can access it.
*/

void createLayerWithParts(SliceLayer& storageLayer, SlicerLayer* layer, int unionAllType)
{
    if (unionAllType & FIX_HORRIBLE_UNION_ALL_TYPE_B)
    {
        for(unsigned int i=0; i<layer->polygonList.size(); i++)
        {
            if (layer->polygonList[i].orientation())
                layer->polygonList[i].reverse();
        }
    }

    vector<Polygons> result;
    if (unionAllType & FIX_HORRIBLE_UNION_ALL_TYPE_C)
        result = layer->polygonList.offset(1000).splitIntoParts(unionAllType);
    else
        result = layer->polygonList.splitIntoParts(unionAllType);
    for(unsigned int i=0; i<result.size(); i++)
    {
        storageLayer.parts.push_back(SliceLayerPart());
        if (unionAllType & FIX_HORRIBLE_UNION_ALL_TYPE_C)
        {
            storageLayer.parts[i].outline.add(result[i][0]);
            storageLayer.parts[i].outline = storageLayer.parts[i].outline.offset(-1000);
        }else
            storageLayer.parts[i].outline = result[i];
        storageLayer.parts[i].boundaryBox.calculate(storageLayer.parts[i].outline);
    }
}

void createLayerParts(SliceVolumeStorage& storage, Slicer* slicer, int unionAllType)
{
    for(unsigned int layerNr = 0; layerNr < slicer->layers.size(); layerNr++)
    {
        storage.layers.push_back(SliceLayer());
        storage.layers[layerNr].sliceZ = slicer->layers[layerNr].z;
        storage.layers[layerNr].printZ = slicer->layers[layerNr].z;
        createLayerWithParts(storage.layers[layerNr], &slicer->layers[layerNr], unionAllType);
    }
}

void dumpLayerparts(SliceDataStorage& storage, const char* filename)
{
    FILE* out = fopen(filename, "w");
    fprintf(out, "<!DOCTYPE html>");
    Point3 modelSize = storage.modelSize;
    Point3 modelMin = storage.modelMin;

    for(unsigned int volumeIdx=0; volumeIdx<storage.volumes.size(); volumeIdx++)
    {
        for(unsigned int layerNr=0;layerNr<storage.volumes[volumeIdx].layers.size(); layerNr++)
        {
            fprintf(out, "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" style=\"width: 500px; height:500px\">\n");
            SliceLayer* layer = &storage.volumes[volumeIdx].layers[layerNr];
            for(unsigned int i=0;i<layer->parts.size();i++)
            {
                SliceLayerPart* part = &layer->parts[i];
                for(unsigned int j=0;j<part->outline.size();j++)
                {
                    fprintf(out, "<polygon points=\"");
                    for(unsigned int k=0;k<part->outline[j].size();k++)
                        fprintf(out, "%f,%f ", float(part->outline[j][k].X - modelMin.x)/modelSize.x*500, float(part->outline[j][k].Y - modelMin.y)/modelSize.y*500);
                    if (j == 0)
                        fprintf(out, "\" style=\"fill:gray; stroke:black;stroke-width:1\" />\n");
                    else
                        fprintf(out, "\" style=\"fill:red; stroke:black;stroke-width:1\" />\n");
                }
            }
            fprintf(out, "</svg>\n");
        }
    }
    fprintf(out, "");
    fclose(out);
}
<|endoftext|>


<commit_before>#include "TileMap.hpp"

#include <sstream>
#include <fstream>

namespace swift
{
	TileMap::TileMap()
		:	tileSize({0, 0}),
			sizePixels({0, 0}),
			sizeTiles({0, 0}),
			textureFile(""),
			position({0, 0}),
			vertices(sf::Quads),
			texture(nullptr)
	{
	}

	TileMap::~TileMap()
	{
		texture = nullptr;
	}

	bool TileMap::init()
	{
		if(tileSize == sf::Vector2u(0, 0) || sizeTiles == sf::Vector2u(0, 0) || textureFile == "" || texture == nullptr)
			return false;

		sizePixels = {sizeTiles.x * tileSize.x, sizeTiles.y * tileSize.y};

		for(unsigned i = 0; i < texture->getSize().y; i += tileSize.y)
		{
			for(unsigned j = 0; j < texture->getSize().x; j += tileSize.x)
			{
				tileTypes.push_back(sf::Vector2u(j, i));
			}
		}

		for(unsigned i = 0; i < sizeTiles.y; i++)
		{
			for(unsigned j = 0; j < sizeTiles.x; j++)
			{
				tiles.push_back(0);
			}
		}

		if(!loadTexture(*texture))
			return false;

		return true;
	}

	bool TileMap::loadFile(const std::string& f)
	{
		std::ifstream fin;
		fin.open(f);

		if(fin.bad())
			return false;

		unsigned height = 0;

		std::string line = "";
		while(std::getline(fin, line))
		{
			if(line.find("texture") != std::string::npos)
			{
				textureFile = line.substr(line.find_first_of('\"') + 1, line.find_last_of('\"') - line.find_first_of('\"') - 1);
			}
			else if(line.find("size") != std::string::npos)
			{
				std::stringstream ss;
				ss << line.substr(line.find('=') + 1);
				ss >> tileSize.x >> tileSize.y;
			}
			else if(line.find('=') != std::string::npos)
			{
				std::stringstream ss;
				ss << line.substr(line.find('=') + 1);
				sf::Vector2u tilePos;
				ss >> tilePos.x >> tilePos.y;
				tileTypes.emplace_back(tilePos);
			}
			else
			{
				std::stringstream ss;
				ss << line;
				int tile = 0;

				height++;

				unsigned width = 0;
				while(ss >> tile)
				{
					tiles.push_back(tile);
					width++;
				}

				sizeTiles.x = width;
			}
		}

		sizeTiles.y = height;

		return true;
	}

	bool TileMap::loadTexture(const sf::Texture& tex)
	{
		texture = &tex;
		vertices.resize(sizeTiles.x * sizeTiles.y * 4);

		sf::Vector2f scale = {sizePixels.x / static_cast<float>(sizeTiles.x) / static_cast<float>(tileSize.x), sizePixels.y / static_cast<float>(sizeTiles.y) / static_cast<float>(tileSize.y)};

		for(unsigned i = 0; i < sizeTiles.x; i++)
		{
			for(unsigned j = 0; j < sizeTiles.y; j++)
			{
				if(i + j * sizeTiles.x >= tiles.size())
					return false;

				// current tile number
				int tileNum = tiles[i + j * sizeTiles.x];

				// pointer to quad
				sf::Vertex* quad = &vertices[(i + j * sizeTiles.x) * 4];

				// define 4 corners
				quad[0].position = {std::floor(i * static_cast<float>(tileSize.x) * scale.x), std::floor(j * static_cast<float>(tileSize.y) * scale.y)};
				quad[1].position = {std::floor((i + 1) * static_cast<float>(tileSize.x) * scale.x), std::floor(j * static_cast<float>(tileSize.y) * scale.y)};
				quad[2].position = {std::floor((i + 1) * static_cast<float>(tileSize.x) * scale.x), std::floor((j + 1) * static_cast<float>(tileSize.y) * scale.y)};
				quad[3].position = {std::floor(i * static_cast<float>(tileSize.x) * scale.x), std::floor((j + 1) * static_cast<float>(tileSize.y) * scale.y)};

				// define 4 tex coordinates
				quad[0].texCoords = {static_cast<float>(tileTypes[tileNum].pos.x), static_cast<float>(tileTypes[tileNum].pos.y)};
				quad[1].texCoords = {static_cast<float>(tileTypes[tileNum].pos.x + tileSize.x), static_cast<float>(tileTypes[tileNum].pos.y)};
				quad[2].texCoords = {static_cast<float>(tileTypes[tileNum].pos.x + tileSize.x), static_cast<float>(tileTypes[tileNum].pos.y + tileSize.y)};
				quad[3].texCoords = {static_cast<float>(tileTypes[tileNum].pos.x), static_cast<float>(tileTypes[tileNum].pos.y + tileSize.y)};
			}
		}

		return true;
	}

	bool TileMap::saveFile(const std::string& f)
	{
		std::ofstream fout;
		fout.open(f);

		if(fout.bad())
			return false;

		fout << "texture = \"" << textureFile << "\"\n";
		fout << "size = " << tileSize.x << ' ' << tileSize.y << '\n';

		for(auto t = 0u; t < tileTypes.size(); t++)
		{
			fout << t << " = " << tileTypes[t].pos.x << ' ' << tileTypes[t].pos.y << '\n';
		}

		for(auto i = 0u; i < sizeTiles.y; i++)
		{
			for(auto j = 0u; j < sizeTiles.x; j++)
			{
				fout << tiles[j + i * sizeTiles.x] << ' ';
			}

			fout << '\n';
		}

		return true;
	}

	void TileMap::setTileNum(unsigned t, int n)
	{
		if(t < tiles.size() && static_cast<unsigned>(n) < tileTypes.size())
		{
			tiles[t] = n;

			sf::Vertex* quad = &vertices[t * 4];
			quad[0].texCoords = {static_cast<float>(tileTypes[n].pos.x), static_cast<float>(tileTypes[n].pos.y)};
			quad[1].texCoords = {static_cast<float>(tileTypes[n].pos.x + tileSize.x), static_cast<float>(tileTypes[n].pos.y)};
			quad[2].texCoords = {static_cast<float>(tileTypes[n].pos.x + tileSize.x), static_cast<float>(tileTypes[n].pos.y + tileSize.y)};
			quad[3].texCoords = {static_cast<float>(tileTypes[n].pos.x), static_cast<float>(tileTypes[n].pos.y + tileSize.y)};
		}
	}

	void TileMap::setPosition(const sf::Vector2i& pos)
	{
		for(unsigned i = 0; i < sizeTiles.x; i++)
		{
			for(unsigned j = 0; j < sizeTiles.y; j++)
			{
				sf::Vertex* quad = &vertices[(i + j * sizeTiles.x) * 4];
				quad[0].position = static_cast<sf::Vector2f>(pos + static_cast<sf::Vector2i>(quad[0].position) - position);
				quad[1].position = static_cast<sf::Vector2f>(pos + static_cast<sf::Vector2i>(quad[1].position) - position);
				quad[2].position = static_cast<sf::Vector2f>(pos + static_cast<sf::Vector2i>(quad[2].position) - position);
				quad[3].position = static_cast<sf::Vector2f>(pos + static_cast<sf::Vector2i>(quad[3].position) - position);
			}
		}

		position = pos;
	}

	void TileMap::setTileSize(const sf::Vector2u& ts)
	{
		tileSize = ts;
	}

	void TileMap::setSize(const sf::Vector2u& s)
	{
		sizeTiles = s;
	}

	void TileMap::setTextureFile(const std::string& str)
	{
		textureFile = str;
	}

	int TileMap::getTileNum(unsigned t) const
	{
		if(t < tiles.size())
			return tiles[t];
		else
			return -1;
	}

	const sf::Vector2u& TileMap::getTileSize() const
	{
		return tileSize;
	}

	const sf::Vector2u& TileMap::getSize() const
	{
		return sizeTiles;
	}

	const std::string& TileMap::getTextureFile() const
	{
		return textureFile;
	}

	unsigned TileMap::getNumOfTileTypes() const
	{
		return tileTypes.size();
	}

	void TileMap::draw(sf::RenderTarget& target, sf::RenderStates states) const
	{
		states.texture = texture;
		target.draw(vertices, states);
	}
}
<commit_msg>Spacing fixes<commit_after>#include "TileMap.hpp"

#include <sstream>
#include <fstream>

namespace swift
{
	TileMap::TileMap()
		:	tileSize({0, 0}),
			sizePixels({0, 0}),
			sizeTiles({0, 0}),
			textureFile(""),
			position({0, 0}),
			vertices(sf::Quads),
			texture(nullptr)
	{
	}

	TileMap::~TileMap()
	{
		texture = nullptr;
	}

	bool TileMap::init()
	{
		if(tileSize == sf::Vector2u(0, 0) || sizeTiles == sf::Vector2u(0, 0) || textureFile == "" || texture == nullptr)
			return false;

		sizePixels = {sizeTiles.x * tileSize.x, sizeTiles.y * tileSize.y};

		for(unsigned i = 0; i < texture->getSize().y; i += tileSize.y)
		{
			for(unsigned j = 0; j < texture->getSize().x; j += tileSize.x)
			{
				tileTypes.push_back(sf::Vector2u(j, i));
			}
		}

		for(unsigned i = 0; i < sizeTiles.y; i++)
		{
			for(unsigned j = 0; j < sizeTiles.x; j++)
			{
				tiles.push_back(0);
			}
		}

		if(!loadTexture(*texture))
			return false;

		return true;
	}

	bool TileMap::loadFile(const std::string& f)
	{
		std::ifstream fin;
		fin.open(f);

		if(fin.bad())
			return false;

		unsigned height = 0;

		std::string line = "";
		while(std::getline(fin, line))
		{
			if(line.find("texture") != std::string::npos)
			{
				textureFile = line.substr(line.find_first_of('\"') + 1, line.find_last_of('\"') - line.find_first_of('\"') - 1);
			}
			else if(line.find("size") != std::string::npos)
			{
				std::stringstream ss;
				ss << line.substr(line.find('=') + 1);
				ss >> tileSize.x >> tileSize.y;
			}
			else if(line.find('=') != std::string::npos)
			{
				std::stringstream ss;
				ss << line.substr(line.find('=') + 1);
				sf::Vector2u tilePos;
				ss >> tilePos.x >> tilePos.y;
				tileTypes.emplace_back(tilePos);
			}
			else
			{
				std::stringstream ss;
				ss << line;
				int tile = 0;

				height++;

				unsigned width = 0;
				while(ss >> tile)
				{
					tiles.push_back(tile);
					width++;
				}

				sizeTiles.x = width;
			}
		}

		sizeTiles.y = height;

		return true;
	}

	bool TileMap::loadTexture(const sf::Texture& tex)
	{
		texture = &tex;
		if(!texture)
			return false;
		vertices.resize(sizeTiles.x * sizeTiles.y * 4);

		sf::Vector2f scale = {sizePixels.x / static_cast<float>(sizeTiles.x) / static_cast<float>(tileSize.x), sizePixels.y / static_cast<float>(sizeTiles.y) / static_cast<float>(tileSize.y)};

		for(unsigned i = 0; i < sizeTiles.x; i++)
		{
			for(unsigned j = 0; j < sizeTiles.y; j++)
			{
				if(i + j * sizeTiles.x >= tiles.size())
					return false;

				// current tile number
				int tileNum = tiles[i + j * sizeTiles.x];

				// pointer to quad
				sf::Vertex* quad = &vertices[(i + j * sizeTiles.x) * 4];

				// define 4 corners
				quad[0].position = {std::floor(i * static_cast<float>(tileSize.x) * scale.x), std::floor(j * static_cast<float>(tileSize.y) * scale.y)};
				quad[1].position = {std::floor((i + 1) * static_cast<float>(tileSize.x) * scale.x), std::floor(j * static_cast<float>(tileSize.y) * scale.y)};
				quad[2].position = {std::floor((i + 1) * static_cast<float>(tileSize.x) * scale.x), std::floor((j + 1) * static_cast<float>(tileSize.y) * scale.y)};
				quad[3].position = {std::floor(i * static_cast<float>(tileSize.x) * scale.x), std::floor((j + 1) * static_cast<float>(tileSize.y) * scale.y)};

				// define 4 tex coordinates
				quad[0].texCoords = {static_cast<float>(tileTypes[tileNum].pos.x), static_cast<float>(tileTypes[tileNum].pos.y)};
				quad[1].texCoords = {static_cast<float>(tileTypes[tileNum].pos.x + tileSize.x), static_cast<float>(tileTypes[tileNum].pos.y)};
				quad[2].texCoords = {static_cast<float>(tileTypes[tileNum].pos.x + tileSize.x), static_cast<float>(tileTypes[tileNum].pos.y + tileSize.y)};
				quad[3].texCoords = {static_cast<float>(tileTypes[tileNum].pos.x), static_cast<float>(tileTypes[tileNum].pos.y + tileSize.y)};
			}
		}

		return true;
	}

	bool TileMap::saveFile(const std::string& f)
	{
		std::ofstream fout;
		fout.open(f);

		if(fout.bad())
			return false;

		fout << "texture = \"" << textureFile << "\"\n";
		fout << "size = " << tileSize.x << ' ' << tileSize.y << '\n';

		for(auto t = 0u; t < tileTypes.size(); t++)
		{
			fout << t << " = " << tileTypes[t].pos.x << ' ' << tileTypes[t].pos.y << '\n';
		}

		for(auto i = 0u; i < sizeTiles.y; i++)
		{
			for(auto j = 0u; j < sizeTiles.x; j++)
			{
				fout << tiles[j + i * sizeTiles.x] << ' ';
			}

			fout << '\n';
		}

		return true;
	}

	void TileMap::setTileNum(unsigned t, int n)
	{
		if(t < tiles.size() && static_cast<unsigned>(n) < tileTypes.size())
		{
			tiles[t] = n;

			sf::Vertex* quad = &vertices[t * 4];
			quad[0].texCoords = {static_cast<float>(tileTypes[n].pos.x), static_cast<float>(tileTypes[n].pos.y)};
			quad[1].texCoords = {static_cast<float>(tileTypes[n].pos.x + tileSize.x), static_cast<float>(tileTypes[n].pos.y)};
			quad[2].texCoords = {static_cast<float>(tileTypes[n].pos.x + tileSize.x), static_cast<float>(tileTypes[n].pos.y + tileSize.y)};
			quad[3].texCoords = {static_cast<float>(tileTypes[n].pos.x), static_cast<float>(tileTypes[n].pos.y + tileSize.y)};
		}
	}

	void TileMap::setPosition(const sf::Vector2i& pos)
	{
		for(unsigned i = 0; i < sizeTiles.x; i++)
		{
			for(unsigned j = 0; j < sizeTiles.y; j++)
			{
				sf::Vertex* quad = &vertices[(i + j * sizeTiles.x) * 4];
				quad[0].position = static_cast<sf::Vector2f>(pos + static_cast<sf::Vector2i>(quad[0].position) - position);
				quad[1].position = static_cast<sf::Vector2f>(pos + static_cast<sf::Vector2i>(quad[1].position) - position);
				quad[2].position = static_cast<sf::Vector2f>(pos + static_cast<sf::Vector2i>(quad[2].position) - position);
				quad[3].position = static_cast<sf::Vector2f>(pos + static_cast<sf::Vector2i>(quad[3].position) - position);
			}
		}

		position = pos;
	}

	void TileMap::setTileSize(const sf::Vector2u& ts)
	{
		tileSize = ts;
	}

	void TileMap::setSize(const sf::Vector2u& s)
	{
		sizeTiles = s;
	}

	void TileMap::setTextureFile(const std::string& str)
	{
		textureFile = str;
	}

	int TileMap::getTileNum(unsigned t) const
	{
		if(t < tiles.size())
			return tiles[t];
		else
			return -1;
	}

	const sf::Vector2u& TileMap::getTileSize() const
	{
		return tileSize;
	}

	const sf::Vector2u& TileMap::getSize() const
	{
		return sizeTiles;
	}

	const std::string& TileMap::getTextureFile() const
	{
		return textureFile;
	}

	unsigned TileMap::getNumOfTileTypes() const
	{
		return tileTypes.size();
	}

	void TileMap::draw(sf::RenderTarget& target, sf::RenderStates states) const
	{
		states.texture = texture;
		target.draw(vertices, states);
	}
}
<|endoftext|>


<commit_before>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * 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 <iostream>
#include <sstream>

#include <zorba/zorba.h>
#include <zorba/external_module.h>
#include <zorba/external_function.h>
#include <zorba/serialization_callback.h>
#include <zorba/store_manager.h>

#ifdef WIN32
#include <direct.h>
#endif

using namespace zorba;

bool
debugger_serialization_example_1(Zorba* aZorba)
{
  try {
    // the stringstream used for query materialization
    std::stringstream lExecutionPlan;

    {
      XQuery_t lQuery = aZorba->createQuery();
      lQuery->setDebugMode(true);
      lQuery->compile("declare function local:foo() { let $i := 1 return ()}; ()");
      lQuery->saveExecutionPlan(lExecutionPlan, ZORBA_USE_BINARY_ARCHIVE);
      std::cout << lQuery << std::endl;
    }

    {
      XQuery_t lQuery = aZorba->createQuery();
      lQuery->loadExecutionPlan(lExecutionPlan);
      std::cout << lQuery << std::endl;
    }

  } catch (ZorbaException& e) {
    std::cerr << e << std::endl;
    return false;
  }

	return true;
}

std::string
replace_all(const std::string& aSrc, const std::string& aSearch, const std::string& aReplace)
{
}

bool
debugger_serialization_example_2(Zorba* aZorba)
{
  try {
    // the stringstream used for query materialization
    std::stringstream lExecutionPlan;
    std::ostringstream lQueryStream;

#ifdef UNIX
    char* lCWD = get_current_dir_name();
#else
    char* lCWD = _getcwd(0, 256);
    std::string lStr(lCWD);
    free(lCWD);
    size_t lStart, lEnd = 0;

    while ((lStart = lStr.find("\\", lEnd)) != std::string::npos) {
      lEnd = lStart + 1;
      lStr.replace(lStart, 1, "/");
    }
#endif

    lQueryStream
      << "import module namespace g = 'http://www.28msec.com/template/guestbook/guestbook'"
      << " at 'file:///" << lCWD << "/guestbook.xq"
      << "';" << std::endl
      << "g:add()";

    {
      XQuery_t lQuery = aZorba->createQuery();
      lQuery->setDebugMode(true);
      std::cout << lQueryStream.str() << std::endl;
      lQuery->compile(lQueryStream.str());
      lQuery->saveExecutionPlan(lExecutionPlan, ZORBA_USE_BINARY_ARCHIVE);
      std::cout << lQuery << std::endl;
    }

    {
      XQuery_t lQuery = aZorba->createQuery();
      lQuery->loadExecutionPlan(lExecutionPlan);
      std::cout << lQuery << std::endl;
    }

  } catch (QueryException& qe) {
    // error "Collection guestbook:entries does not exist." is OK
    if (qe.getErrorCode() != XDDY0003_COLLECTION_DOES_NOT_EXIST) {
      std::cerr << qe << std::endl;
      return false;
    }
  } catch (ZorbaException& e) {
    std::cerr << e << std::endl;
    return false;
  }

	return true;
}

int test_debugger_serialization( int argc, char * argv[] )
{
  void* lStore = zorba::StoreManager::getStore();
  Zorba* lZorba = Zorba::getInstance(lStore);
  bool res = false;

  std::cout << "executing debugger serialization example 1" << std::endl;
  res = debugger_serialization_example_1(lZorba);
  if (!res) return 1;
  std::cout << std::endl;

  std::cout << "executing debugger serialization example 2" << std::endl;
  res = debugger_serialization_example_2(lZorba);
  if (!res) return 1;
  std::cout << std::endl;

  lZorba->shutdown();
  zorba::StoreManager::shutdownStore(lStore);
  return 0;
}

<commit_msg>Remove use of gcc-specific function<commit_after>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * 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 <iostream>
#include <sstream>

#include <zorba/zorba.h>
#include <zorba/external_module.h>
#include <zorba/external_function.h>
#include <zorba/serialization_callback.h>
#include <zorba/store_manager.h>

#ifdef WIN32
#include <direct.h>
#endif

using namespace zorba;

bool
debugger_serialization_example_1(Zorba* aZorba)
{
  try {
    // the stringstream used for query materialization
    std::stringstream lExecutionPlan;

    {
      XQuery_t lQuery = aZorba->createQuery();
      lQuery->setDebugMode(true);
      lQuery->compile("declare function local:foo() { let $i := 1 return ()}; ()");
      lQuery->saveExecutionPlan(lExecutionPlan, ZORBA_USE_BINARY_ARCHIVE);
      std::cout << lQuery << std::endl;
    }

    {
      XQuery_t lQuery = aZorba->createQuery();
      lQuery->loadExecutionPlan(lExecutionPlan);
      std::cout << lQuery << std::endl;
    }

  } catch (ZorbaException& e) {
    std::cerr << e << std::endl;
    return false;
  }

	return true;
}

std::string
replace_all(const std::string& aSrc, const std::string& aSearch, const std::string& aReplace)
{
}

bool
debugger_serialization_example_2(Zorba* aZorba)
{
  try {
    // the stringstream used for query materialization
    std::stringstream lExecutionPlan;
    std::ostringstream lQueryStream;

#ifdef UNIX
    char lCWD[1024];
    if (getcwd(lCWD, 1024) == NULL) {
      return false;
    }
#else
    char* lCWD = _getcwd(0, 256);
    std::string lStr(lCWD);
    free(lCWD);
    size_t lStart, lEnd = 0;

    while ((lStart = lStr.find("\\", lEnd)) != std::string::npos) {
      lEnd = lStart + 1;
      lStr.replace(lStart, 1, "/");
    }
#endif

    lQueryStream
      << "import module namespace g = 'http://www.28msec.com/template/guestbook/guestbook'"
      << " at 'file:///" << lCWD << "/guestbook.xq"
      << "';" << std::endl
      << "g:add()";

    {
      XQuery_t lQuery = aZorba->createQuery();
      lQuery->setDebugMode(true);
      std::cout << lQueryStream.str() << std::endl;
      lQuery->compile(lQueryStream.str());
      lQuery->saveExecutionPlan(lExecutionPlan, ZORBA_USE_BINARY_ARCHIVE);
      std::cout << lQuery << std::endl;
    }

    {
      XQuery_t lQuery = aZorba->createQuery();
      lQuery->loadExecutionPlan(lExecutionPlan);
      std::cout << lQuery << std::endl;
    }

  } catch (QueryException& qe) {
    // error "Collection guestbook:entries does not exist." is OK
    if (qe.getErrorCode() != XDDY0003_COLLECTION_DOES_NOT_EXIST) {
      std::cerr << qe << std::endl;
      return false;
    }
  } catch (ZorbaException& e) {
    std::cerr << e << std::endl;
    return false;
  }

	return true;
}

int test_debugger_serialization( int argc, char * argv[] )
{
  void* lStore = zorba::StoreManager::getStore();
  Zorba* lZorba = Zorba::getInstance(lStore);
  bool res = false;

  std::cout << "executing debugger serialization example 1" << std::endl;
  res = debugger_serialization_example_1(lZorba);
  if (!res) return 1;
  std::cout << std::endl;

  std::cout << "executing debugger serialization example 2" << std::endl;
  res = debugger_serialization_example_2(lZorba);
  if (!res) return 1;
  std::cout << std::endl;

  lZorba->shutdown();
  zorba::StoreManager::shutdownStore(lStore);
  return 0;
}

<|endoftext|>


<commit_before>/*******************************
Copyright (c) 2016-2018 Gr�goire Angerand

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 "perf.h"
#include <y/core/Chrono.h>

#include <thread>
#include <mutex>
#include <cstdio>

#include "os.h"

namespace y {
namespace perf {

#ifdef Y_PERF_LOG_ENABLED
static constexpr usize buffer_size = 16 * 1024;
thread_local static std::unique_ptr<char[]> buffer;
thread_local static usize buffer_offset = 0;
thread_local static u32 tid = 0;
static std::mutex mutex;
static bool initialized = false;
static std::unique_ptr<io::Writer> output;

static void write(const char* str, usize len);

static void write_buffer() {
	std::unique_lock lock(mutex);
	if(output && buffer) {
		if(!initialized) {
			initialized = true;
			const char beg[] = R"({"traceEvents":[)";
			output->write(beg, sizeof(beg) - 1);
		}
		output->write(buffer.get(), buffer_offset);
		buffer_offset = 0;
		event("perf", "done writing buffer");
	}
}
#endif

void set_output_ptr(std::unique_ptr<io::Writer>&& out) {
	unused(out);
#ifdef Y_PERF_LOG_ENABLED
	std::unique_lock lock(mutex);
	initialized = false;
	output = std::move(out);
#endif
}

#ifdef Y_PERF_LOG_ENABLED
static void init_thread() {
	if(!buffer.get()) {
		buffer = std::make_unique<char[]>(buffer_size);
		std::stringstream ss;
		ss << std::this_thread::get_id();
		tid = std::stoul(ss.str());
	}
}

static void write(const char* str, usize len) {
	init_thread();
	usize remaining = buffer_size - buffer_offset;
	if(len >= remaining) {
		write_buffer();
	}
	std::memcpy(buffer.get() + buffer_offset, str, len);
	buffer_offset += len;
}

static double micros() {
	return core::Chrono::program().to_micros();
}

static constexpr usize print_buffer_len = 256;

static int paren(const char* buff) {
	if(const char* p = std::strchr(buff, '('); p) {
		return p - buff;
	}
	return print_buffer_len;
}

void enter(const char* cat, const char* func) {
	char b[print_buffer_len];
	usize len = std::snprintf(b, sizeof(b), R"({"name":"%.*s","cat":"%s","ph":"B","pid":0,"tid":%u,"ts":%f},)", paren(func), func, cat, tid, micros());
	if(len >= sizeof(b)) {
		y_fatal("Too long.");
	}
	write(b, len);
}

void leave(const char* cat, const char* func) {
	char b[print_buffer_len];
	usize len = std::snprintf(b, sizeof(b), R"({"name":"%.*s","cat":"%s","ph":"E","pid":0,"tid":%u,"ts":%f},)", paren(func), func, cat, tid, micros());
	if(len >= sizeof(b)) {
		y_fatal("Too long.");
	}
	write(b, len);
}

void event(const char* cat, const char* name) {
	char b[print_buffer_len];
	usize len = std::snprintf(b, sizeof(b), R"({"name":"%s","cat":"%s","ph":"i","pid":0,"tid":%u,"ts":%f},)", name, cat, tid, micros());
	if(len >= sizeof(b)) {
		y_fatal("Too long.");
	}
	write(b, len);
}

thread_local static struct Flush : NonCopyable {
	~Flush() {
		char b[print_buffer_len];
		usize len = std::snprintf(b, sizeof(b), R"({"name":"thread closed","cat":"perf","ph":"i","pid":0,"tid":%u,"ts":%f}]})", tid, micros());
		if(len >= sizeof(b)) {
			y_fatal("Too long.");
		}
		write(b, len);
		write_buffer();
	}
} flush;
#endif

}
}
<commit_msg>Fixed a segfault due to static object destruction order.<commit_after>/*******************************
Copyright (c) 2016-2018 Gr�goire Angerand

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 "perf.h"
#include <y/core/Chrono.h>

#include <thread>
#include <mutex>
#include <cstdio>

#include "os.h"

namespace y {
namespace perf {

#ifdef Y_PERF_LOG_ENABLED
static constexpr usize buffer_size = 16 * 1024;
thread_local static char* buffer = nullptr; // can't use unique_ptr here
thread_local static usize buffer_offset = 0;
thread_local static u32 tid = 0;
static std::mutex mutex;
static bool initialized = false;
static std::unique_ptr<io::Writer> output;

static void write(const char* str, usize len);

static void write_buffer() {
	std::unique_lock lock(mutex);
	if(output && buffer) {
		if(!initialized) {
			initialized = true;
			const char beg[] = R"({"traceEvents":[)";
			output->write(beg, sizeof(beg) - 1);
		}
		output->write(buffer, buffer_offset);
		buffer_offset = 0;
		event("perf", "done writing buffer");
	}
}
#endif

void set_output_ptr(std::unique_ptr<io::Writer>&& out) {
	unused(out);
#ifdef Y_PERF_LOG_ENABLED
	std::unique_lock lock(mutex);
	initialized = false;
	output = std::move(out);
#endif
}

#ifdef Y_PERF_LOG_ENABLED
static void init_thread() {
	if(!buffer) {
		buffer = new char[buffer_size];
		std::stringstream ss;
		ss << std::this_thread::get_id();
		tid = std::stoul(ss.str());
	}
}

static void write(const char* str, usize len) {
	init_thread();
	usize remaining = buffer_size - buffer_offset;
	if(len >= remaining) {
		write_buffer();
	}
	std::memcpy(buffer + buffer_offset, str, len);
	buffer_offset += len;
}

static double micros() {
	return core::Chrono::program().to_micros();
}

static constexpr usize print_buffer_len = 256;

static int paren(const char* buff) {
	if(const char* p = std::strchr(buff, '('); p) {
		return p - buff;
	}
	return print_buffer_len;
}

void enter(const char* cat, const char* func) {
	char b[print_buffer_len];
	usize len = std::snprintf(b, sizeof(b), R"({"name":"%.*s","cat":"%s","ph":"B","pid":0,"tid":%u,"ts":%f},)", paren(func), func, cat, tid, micros());
	if(len >= sizeof(b)) {
		y_fatal("Too long.");
	}
	write(b, len);
}

void leave(const char* cat, const char* func) {
	char b[print_buffer_len];
	usize len = std::snprintf(b, sizeof(b), R"({"name":"%.*s","cat":"%s","ph":"E","pid":0,"tid":%u,"ts":%f},)", paren(func), func, cat, tid, micros());
	if(len >= sizeof(b)) {
		y_fatal("Too long.");
	}
	write(b, len);
}

void event(const char* cat, const char* name) {
	char b[print_buffer_len];
	usize len = std::snprintf(b, sizeof(b), R"({"name":"%s","cat":"%s","ph":"i","pid":0,"tid":%u,"ts":%f},)", name, cat, tid, micros());
	if(len >= sizeof(b)) {
		y_fatal("Too long.");
	}
	write(b, len);
}

thread_local static struct Close : NonCopyable {
	~Close() {
		char b[print_buffer_len];
		usize len = std::snprintf(b, sizeof(b), R"({"name":"thread closed","cat":"perf","ph":"i","pid":0,"tid":%u,"ts":%f}]})", tid, micros());
		if(len >= sizeof(b)) {
			y_fatal("Too long.");
		}
		write(b, len);
		write_buffer();
		delete[] buffer;
	}
} close;
#endif

}
}
<|endoftext|>


<commit_before>/**
 * Copyright © 2017 IBM Corporation
 *
 * 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 "functor.hpp"
#include <sdbusplus/bus.hpp>

namespace phosphor
{
namespace inventory
{
namespace manager
{
namespace functor
{
bool PropertyConditionBase::operator()(
    sdbusplus::bus::bus& bus,
    sdbusplus::message::message&,
    Manager& mgr) const
{
    std::string path(_path);
    return (*this)(path, bus, mgr);
}

bool PropertyConditionBase::operator()(
    const std::string& path,
    sdbusplus::bus::bus& bus,
    Manager&) const
{
    std::string host;

    if (_service)
    {
        host.assign(_service);
    }
    else
    {
        auto mapperCall = bus.new_method_call(
                              "xyz.openbmc_project.ObjectMapper",
                              "/xyz/openbmc_project/ObjectMapper",
                              "xyz.openbmc_project.ObjectMapper",
                              "GetObject");
        mapperCall.append(path);
        mapperCall.append(std::vector<std::string>({_iface}));

        auto mapperResponseMsg = bus.call(mapperCall);
        if (mapperResponseMsg.is_method_error())
        {
            return false;
        }

        std::map<std::string, std::vector<std::string>> mapperResponse;
        mapperResponseMsg.read(mapperResponse);

        if (mapperResponse.empty())
        {
            return false;
        }

        host = mapperResponse.begin()->first;

        if (host == bus.get_unique_name())
        {
            // TODO I can't call myself here.
            return false;
        }
    }
    auto hostCall = bus.new_method_call(
                        host.c_str(),
                        path.c_str(),
                        "org.freedesktop.DBus.Properties",
                        "Get");
    hostCall.append(_iface);
    hostCall.append(_property);

    auto hostResponseMsg = bus.call(hostCall);
    if (hostResponseMsg.is_method_error())
    {
        return false;
    }

    return eval(hostResponseMsg);
}

} // namespace functor
} // namespace manager
} // namespace inventory
} // namespace phosphor

// vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
<commit_msg>Move object_mapper per dbus path conventions.<commit_after>/**
 * Copyright © 2017 IBM Corporation
 *
 * 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 "functor.hpp"
#include <sdbusplus/bus.hpp>

namespace phosphor
{
namespace inventory
{
namespace manager
{
namespace functor
{
bool PropertyConditionBase::operator()(
    sdbusplus::bus::bus& bus,
    sdbusplus::message::message&,
    Manager& mgr) const
{
    std::string path(_path);
    return (*this)(path, bus, mgr);
}

bool PropertyConditionBase::operator()(
    const std::string& path,
    sdbusplus::bus::bus& bus,
    Manager&) const
{
    std::string host;

    if (_service)
    {
        host.assign(_service);
    }
    else
    {
        auto mapperCall = bus.new_method_call(
                              "xyz.openbmc_project.ObjectMapper",
                              "/xyz/openbmc_project/object_mapper",
                              "xyz.openbmc_project.ObjectMapper",
                              "GetObject");
        mapperCall.append(path);
        mapperCall.append(std::vector<std::string>({_iface}));

        auto mapperResponseMsg = bus.call(mapperCall);
        if (mapperResponseMsg.is_method_error())
        {
            return false;
        }

        std::map<std::string, std::vector<std::string>> mapperResponse;
        mapperResponseMsg.read(mapperResponse);

        if (mapperResponse.empty())
        {
            return false;
        }

        host = mapperResponse.begin()->first;

        if (host == bus.get_unique_name())
        {
            // TODO I can't call myself here.
            return false;
        }
    }
    auto hostCall = bus.new_method_call(
                        host.c_str(),
                        path.c_str(),
                        "org.freedesktop.DBus.Properties",
                        "Get");
    hostCall.append(_iface);
    hostCall.append(_property);

    auto hostResponseMsg = bus.call(hostCall);
    if (hostResponseMsg.is_method_error())
    {
        return false;
    }

    return eval(hostResponseMsg);
}

} // namespace functor
} // namespace manager
} // namespace inventory
} // namespace phosphor

// vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
<|endoftext|>


<commit_before>/**
 *  \file RMF/Category.h
 *  \brief Handle read/write of Model data from/to files.
 *
 *  Copyright 2007-2013 IMP Inventors. All rights reserved.
 *
 */

#include <boost/shared_ptr.hpp>
#include <iomanip>
#include <ostream>
#include <string>
#include <vector>

#include "RMF/FileConstHandle.h"
#include "RMF/ID.h"
#include "RMF/NodeConstHandle.h"
#include "RMF/Nullable.h"
#include "RMF/compiler_macros.h"
#include "RMF/decorator/feature.h"
#include "RMF/decorator/physics.h"
#include "RMF/decorator/sequence.h"
#include "RMF/decorator/shape.h"
#include "RMF/enums.h"
#include "RMF/infrastructure_macros.h"
#include "RMF/types.h"

RMF_ENABLE_WARNINGS

namespace RMF {

NodeConstHandle::NodeConstHandle(NodeID node,
                                 boost::shared_ptr<internal::SharedData> shared)
    : node_(node), shared_(shared) {}

FileConstHandle NodeConstHandle::get_file() const {
  return FileConstHandle(shared_);
}

std::string NodeConstHandle::get_file_name() const {
  return get_file().get_name();
}
FrameID NodeConstHandle::get_current_frame_id() const {
  return get_file().get_current_frame();
}

#define RMF_HDF5_NODE_CONST_KEY_TYPE_METHODS_DEF(Traits, UCName)        \
  std::string NodeConstHandle::get_category_name(UCName##Key k) const { \
    return get_file().get_name(get_file().get_category(k));             \
  }                                                                     \
  std::string NodeConstHandle::get_name(UCName##Key k) const {          \
    return get_file().get_name(k);                                      \
  }

RMF_FOREACH_TYPE(RMF_HDF5_NODE_CONST_KEY_TYPE_METHODS_DEF);

std::vector<NodeConstHandle> NodeConstHandle::get_children() const {
  try {
    NodeIDs children = shared_->get_children(node_);
    std::vector<NodeConstHandle> ret(children.size());
    for (unsigned int i = 0; i < ret.size(); ++i) {
      ret[i] = NodeConstHandle(children[i], shared_);
    }
    return ret;
  }
  RMF_NODE_CATCH();
}

std::string get_type_name(NodeType t) {
  switch (t) {
    case ROOT:
      return "root";
    case REPRESENTATION:
      return "rep";
    case GEOMETRY:
      return "geom";
    case FEATURE:
      return "feat";
    case ALIAS:
      return "alias";
    case BOND:
      return "bond";
    case CUSTOM:
      return "custom";
    case ORGANIZATIONAL:
      return "organizational";
    default:
      return "unknown";
  }
}

std::ostream& operator<<(std::ostream& out, NodeType t) {
  out << get_type_name(t);
  return out;
}
std::istream& operator>>(std::istream& in, NodeType& t) {
  std::string token;
  in >> token;
  for (NodeType i = ROOT; i < LINK; i = NodeType(i + 1)) {
    if (token == get_type_name(i)) {
      t = i;
      return in;
    }
  }
  t = CUSTOM;
  return in;
}

namespace {
template <class Traits>
void show_data(NodeConstHandle n, std::ostream& out,
               const std::vector<ID<Traits> >& ks, std::string prefix) {
  using std::operator<<;
  RMF_FOREACH(ID<Traits> k, ks) {
    if (n.get_file().get_current_frame() != FrameID() &&
        !n.get_frame_value(k).get_is_null()) {
      out << std::endl << prefix << n.get_file().get_name(k) << ": "
          << Showable(n.get_frame_value(k));
    } else {
      Nullable<Traits> ts = n.get_static_value(k);
      if (!ts.get_is_null()) {
        out << std::endl << prefix << n.get_file().get_name(k) << ": "
            << Showable(ts.get()) << "(s)";
      }
    }
  }
}

void show_node(NodeConstHandle n, std::ostream& out, std::string prefix = "") {
  using std::operator<<;
  out << prefix << "\"" << n.get_name() << "\" [" << get_type_name(n.get_type())
      << "]";
}
void show_node(NodeConstHandle n, std::ostream& out, FloatKeys fks,
               FloatsKeys fsks, IntKeys iks, IntsKeys isks, StringKeys sks,
               StringsKeys ssks, Vector3Keys v3ks, Vector4Keys v4ks,
               Vector3sKeys v3sks, std::string prefix) {
  using std::operator<<;
  if (true) {
    show_node(n, out);
    show_data(n, out, fks, prefix + "  ");
    show_data(n, out, iks, prefix + "  ");
    show_data(n, out, sks, prefix + "  ");
    show_data(n, out, fsks, prefix + "  ");
    show_data(n, out, isks, prefix + "  ");
    show_data(n, out, ssks, prefix + "  ");
    show_data(n, out, v3ks, prefix + "  ");
    show_data(n, out, v4ks, prefix + "  ");
    show_data(n, out, v3sks, prefix + "  ");
  }
}

void show_node_decorators(
    NodeConstHandle n, std::ostream& out, decorator::ColoredConstFactory ccf,
    decorator::ParticleConstFactory pcf,
    decorator::IntermediateParticleConstFactory ipcf,
    decorator::RigidParticleConstFactory rpcf, decorator::ScoreConstFactory scf,
    decorator::BallConstFactory bcf, decorator::CylinderConstFactory cycf,
    decorator::SegmentConstFactory segcf, decorator::ResidueConstFactory rcf,
    decorator::AtomConstFactory acf, decorator::ChainConstFactory chaincf,
    decorator::DomainConstFactory fragcf, decorator::CopyConstFactory copycf,
    decorator::DiffuserConstFactory diffusercf,
    decorator::TypedConstFactory typedcf, std::string) {
  using std::operator<<;
  out << "\"" << n.get_name() << "\" [" << get_type_name(n.get_type()) << ": ";
  if (ccf.get_is(n)) out << " color";
  if (pcf.get_is(n)) out << " particle";
  if (ipcf.get_is(n)) out << " iparticle";
  if (rpcf.get_is(n)) out << " rigid";
  if (scf.get_is(n)) out << " score";
  if (bcf.get_is(n)) out << " ball";
  if (cycf.get_is(n)) out << " cylinder";
  if (segcf.get_is(n)) out << " segment";
  if (rcf.get_is(n)) out << " residue";
  if (acf.get_is(n)) out << " atom";
  if (chaincf.get_is(n)) out << " chain";
  if (fragcf.get_is(n)) out << " domain";
  if (copycf.get_is(n)) out << " copy";
  if (typedcf.get_is(n)) out << " typed";
  if (diffusercf.get_is(n)) out << " diffuser";
  out << "]";
}

template <class TypeT>
std::vector<ID<TypeT> > get_keys(FileConstHandle f) {
  Categories kcs = f.get_categories();
  std::vector<ID<TypeT> > ret;
  for (unsigned int i = 0; i < kcs.size(); ++i) {
    std::vector<ID<TypeT> > curp = f.get_keys<TypeT>(kcs[i]);
    ret.insert(ret.end(), curp.begin(), curp.end());
  }
  return ret;
}

// Note that older g++ is confused by queue.back().get<2>()
#define RMF_PRINT_TREE(stream, NodeType, start, num_children, get_children,  \
                       show)                                                 \
  {                                                                          \
    std::vector<boost::tuple<std::string, std::string, NodeType> > queue;    \
    queue.push_back(boost::make_tuple(std::string(), std::string(), start)); \
    do {                                                                     \
      boost::tuple<std::string, std::string, NodeType>& back = queue.back(); \
      NodeType n = back.get<2>();                                            \
      std::string prefix0 = back.get<0>();                                   \
      std::string prefix1 = back.get<1>();                                   \
      queue.pop_back();                                                      \
      stream << prefix0;                                                     \
      std::vector<NodeType> children = get_children;                         \
      if (children.size() > 0)                                               \
        stream << " + ";                                                     \
      else                                                                   \
        stream << " - ";                                                     \
      show;                                                                  \
      stream << std::endl;                                                   \
      for (int i = static_cast<int>(children.size()) - 1; i >= 0; --i) {     \
        queue.push_back(                                                     \
            boost::make_tuple(prefix1 + " ", prefix1 + " ", children[i]));   \
      }                                                                      \
    } while (!queue.empty());                                                \
  }
}

void show_hierarchy(NodeConstHandle root, std::ostream& out) {
  using std::operator<<;
  RMF_PRINT_TREE(out, NodeConstHandle, root, n.get_children().size(),
                 n.get_children(), show_node(n, out));
}

void show_hierarchy_with_values(NodeConstHandle root, std::ostream& out) {
  FloatKeys fks;
  IntKeys iks;
  StringKeys sks;
  FloatsKeys fsks;
  IntsKeys isks;
  StringsKeys ssks;
  Vector3Keys v3ks;
  Vector4Keys v4ks;
  Vector3sKeys v3sks;
  fks = get_keys<FloatTraits>(root.get_file());
  iks = get_keys<IntTraits>(root.get_file());
  sks = get_keys<StringTraits>(root.get_file());
  fsks = get_keys<FloatsTraits>(root.get_file());
  isks = get_keys<IntsTraits>(root.get_file());
  ssks = get_keys<StringsTraits>(root.get_file());
  v3ks = get_keys<Vector3Traits>(root.get_file());
  v4ks = get_keys<Vector4Traits>(root.get_file());
  v3sks = get_keys<Vector3sTraits>(root.get_file());
  using std::operator<<;
  RMF_PRINT_TREE(out, NodeConstHandle, root, n.get_children().size(),
                 n.get_children(),
                 show_node(n, out, fks, fsks, iks, isks, sks, ssks, v3ks, v4ks,
                           v3sks, prefix0 + "   "));
}

void show_hierarchy_with_decorators(NodeConstHandle root, bool,
                                    std::ostream& out) {
  decorator::ColoredConstFactory ccf(root.get_file());
  decorator::ParticleConstFactory pcf(root.get_file());
  decorator::IntermediateParticleConstFactory ipcf(root.get_file());
  decorator::RigidParticleConstFactory rpcf(root.get_file());
  decorator::ScoreConstFactory scf(root.get_file());
  decorator::BallConstFactory bcf(root.get_file());
  decorator::CylinderConstFactory cycf(root.get_file());
  decorator::SegmentConstFactory segcf(root.get_file());
  decorator::ResidueConstFactory rcf(root.get_file());
  decorator::AtomConstFactory acf(root.get_file());
  decorator::ChainConstFactory chaincf(root.get_file());
  decorator::DomainConstFactory fragcf(root.get_file());
  decorator::CopyConstFactory copycf(root.get_file());
  decorator::DiffuserConstFactory diffusercf(root.get_file());
  decorator::TypedConstFactory typedcf(root.get_file());
  using std::operator<<;
  RMF_PRINT_TREE(
      out, NodeConstHandle, root, n.get_children().size(), n.get_children(),
      show_node_decorators(n, out, ccf, pcf, ipcf, rpcf, scf, bcf, cycf, segcf,
                           rcf, acf, chaincf, fragcf, copycf, diffusercf,
                           typedcf, prefix0 + "   "));
}

} /* namespace RMF */

RMF_DISABLE_WARNINGS
<commit_msg>show bond decorator too<commit_after>/**
 *  \file RMF/Category.h
 *  \brief Handle read/write of Model data from/to files.
 *
 *  Copyright 2007-2013 IMP Inventors. All rights reserved.
 *
 */

#include <boost/shared_ptr.hpp>
#include <iomanip>
#include <ostream>
#include <string>
#include <vector>

#include "RMF/FileConstHandle.h"
#include "RMF/ID.h"
#include "RMF/NodeConstHandle.h"
#include "RMF/Nullable.h"
#include "RMF/compiler_macros.h"
#include "RMF/decorator/feature.h"
#include "RMF/decorator/physics.h"
#include "RMF/decorator/sequence.h"
#include "RMF/decorator/shape.h"
#include "RMF/enums.h"
#include "RMF/infrastructure_macros.h"
#include "RMF/types.h"

RMF_ENABLE_WARNINGS

namespace RMF {

NodeConstHandle::NodeConstHandle(NodeID node,
                                 boost::shared_ptr<internal::SharedData> shared)
    : node_(node), shared_(shared) {}

FileConstHandle NodeConstHandle::get_file() const {
  return FileConstHandle(shared_);
}

std::string NodeConstHandle::get_file_name() const {
  return get_file().get_name();
}
FrameID NodeConstHandle::get_current_frame_id() const {
  return get_file().get_current_frame();
}

#define RMF_HDF5_NODE_CONST_KEY_TYPE_METHODS_DEF(Traits, UCName)        \
  std::string NodeConstHandle::get_category_name(UCName##Key k) const { \
    return get_file().get_name(get_file().get_category(k));             \
  }                                                                     \
  std::string NodeConstHandle::get_name(UCName##Key k) const {          \
    return get_file().get_name(k);                                      \
  }

RMF_FOREACH_TYPE(RMF_HDF5_NODE_CONST_KEY_TYPE_METHODS_DEF);

std::vector<NodeConstHandle> NodeConstHandle::get_children() const {
  try {
    NodeIDs children = shared_->get_children(node_);
    std::vector<NodeConstHandle> ret(children.size());
    for (unsigned int i = 0; i < ret.size(); ++i) {
      ret[i] = NodeConstHandle(children[i], shared_);
    }
    return ret;
  }
  RMF_NODE_CATCH();
}

std::string get_type_name(NodeType t) {
  switch (t) {
    case ROOT:
      return "root";
    case REPRESENTATION:
      return "rep";
    case GEOMETRY:
      return "geom";
    case FEATURE:
      return "feat";
    case ALIAS:
      return "alias";
    case BOND:
      return "bond";
    case CUSTOM:
      return "custom";
    case ORGANIZATIONAL:
      return "organizational";
    default:
      return "unknown";
  }
}

std::ostream& operator<<(std::ostream& out, NodeType t) {
  out << get_type_name(t);
  return out;
}
std::istream& operator>>(std::istream& in, NodeType& t) {
  std::string token;
  in >> token;
  for (NodeType i = ROOT; i < LINK; i = NodeType(i + 1)) {
    if (token == get_type_name(i)) {
      t = i;
      return in;
    }
  }
  t = CUSTOM;
  return in;
}

namespace {
template <class Traits>
void show_data(NodeConstHandle n, std::ostream& out,
               const std::vector<ID<Traits> >& ks, std::string prefix) {
  using std::operator<<;
  RMF_FOREACH(ID<Traits> k, ks) {
    if (n.get_file().get_current_frame() != FrameID() &&
        !n.get_frame_value(k).get_is_null()) {
      out << std::endl << prefix << n.get_file().get_name(k) << ": "
          << Showable(n.get_frame_value(k));
    } else {
      Nullable<Traits> ts = n.get_static_value(k);
      if (!ts.get_is_null()) {
        out << std::endl << prefix << n.get_file().get_name(k) << ": "
            << Showable(ts.get()) << "(s)";
      }
    }
  }
}

void show_node(NodeConstHandle n, std::ostream& out, std::string prefix = "") {
  using std::operator<<;
  out << prefix << "\"" << n.get_name() << "\" [" << get_type_name(n.get_type())
      << "]";
}
void show_node(NodeConstHandle n, std::ostream& out, FloatKeys fks,
               FloatsKeys fsks, IntKeys iks, IntsKeys isks, StringKeys sks,
               StringsKeys ssks, Vector3Keys v3ks, Vector4Keys v4ks,
               Vector3sKeys v3sks, std::string prefix) {
  using std::operator<<;
  if (true) {
    show_node(n, out);
    show_data(n, out, fks, prefix + "  ");
    show_data(n, out, iks, prefix + "  ");
    show_data(n, out, sks, prefix + "  ");
    show_data(n, out, fsks, prefix + "  ");
    show_data(n, out, isks, prefix + "  ");
    show_data(n, out, ssks, prefix + "  ");
    show_data(n, out, v3ks, prefix + "  ");
    show_data(n, out, v4ks, prefix + "  ");
    show_data(n, out, v3sks, prefix + "  ");
  }
}

void show_node_decorators(
    NodeConstHandle n, std::ostream& out, decorator::BondConstFactory bdcf,
    decorator::ColoredConstFactory ccf,
    decorator::ParticleConstFactory pcf,
    decorator::IntermediateParticleConstFactory ipcf,
    decorator::RigidParticleConstFactory rpcf, decorator::ScoreConstFactory scf,
    decorator::BallConstFactory bcf, decorator::CylinderConstFactory cycf,
    decorator::SegmentConstFactory segcf, decorator::ResidueConstFactory rcf,
    decorator::AtomConstFactory acf, decorator::ChainConstFactory chaincf,
    decorator::DomainConstFactory fragcf, decorator::CopyConstFactory copycf,
    decorator::DiffuserConstFactory diffusercf,
    decorator::TypedConstFactory typedcf, std::string) {
  using std::operator<<;
  out << "\"" << n.get_name() << "\" [" << get_type_name(n.get_type()) << ": ";
  if (bdcf.get_is(n)) out << " bond";
  if (ccf.get_is(n)) out << " color";
  if (pcf.get_is(n)) out << " particle";
  if (ipcf.get_is(n)) out << " iparticle";
  if (rpcf.get_is(n)) out << " rigid";
  if (scf.get_is(n)) out << " score";
  if (bcf.get_is(n)) out << " ball";
  if (cycf.get_is(n)) out << " cylinder";
  if (segcf.get_is(n)) out << " segment";
  if (rcf.get_is(n)) out << " residue";
  if (acf.get_is(n)) out << " atom";
  if (chaincf.get_is(n)) out << " chain";
  if (fragcf.get_is(n)) out << " domain";
  if (copycf.get_is(n)) out << " copy";
  if (typedcf.get_is(n)) out << " typed";
  if (diffusercf.get_is(n)) out << " diffuser";
  out << "]";
}

template <class TypeT>
std::vector<ID<TypeT> > get_keys(FileConstHandle f) {
  Categories kcs = f.get_categories();
  std::vector<ID<TypeT> > ret;
  for (unsigned int i = 0; i < kcs.size(); ++i) {
    std::vector<ID<TypeT> > curp = f.get_keys<TypeT>(kcs[i]);
    ret.insert(ret.end(), curp.begin(), curp.end());
  }
  return ret;
}

// Note that older g++ is confused by queue.back().get<2>()
#define RMF_PRINT_TREE(stream, NodeType, start, num_children, get_children,  \
                       show)                                                 \
  {                                                                          \
    std::vector<boost::tuple<std::string, std::string, NodeType> > queue;    \
    queue.push_back(boost::make_tuple(std::string(), std::string(), start)); \
    do {                                                                     \
      boost::tuple<std::string, std::string, NodeType>& back = queue.back(); \
      NodeType n = back.get<2>();                                            \
      std::string prefix0 = back.get<0>();                                   \
      std::string prefix1 = back.get<1>();                                   \
      queue.pop_back();                                                      \
      stream << prefix0;                                                     \
      std::vector<NodeType> children = get_children;                         \
      if (children.size() > 0)                                               \
        stream << " + ";                                                     \
      else                                                                   \
        stream << " - ";                                                     \
      show;                                                                  \
      stream << std::endl;                                                   \
      for (int i = static_cast<int>(children.size()) - 1; i >= 0; --i) {     \
        queue.push_back(                                                     \
            boost::make_tuple(prefix1 + " ", prefix1 + " ", children[i]));   \
      }                                                                      \
    } while (!queue.empty());                                                \
  }
}

void show_hierarchy(NodeConstHandle root, std::ostream& out) {
  using std::operator<<;
  RMF_PRINT_TREE(out, NodeConstHandle, root, n.get_children().size(),
                 n.get_children(), show_node(n, out));
}

void show_hierarchy_with_values(NodeConstHandle root, std::ostream& out) {
  FloatKeys fks;
  IntKeys iks;
  StringKeys sks;
  FloatsKeys fsks;
  IntsKeys isks;
  StringsKeys ssks;
  Vector3Keys v3ks;
  Vector4Keys v4ks;
  Vector3sKeys v3sks;
  fks = get_keys<FloatTraits>(root.get_file());
  iks = get_keys<IntTraits>(root.get_file());
  sks = get_keys<StringTraits>(root.get_file());
  fsks = get_keys<FloatsTraits>(root.get_file());
  isks = get_keys<IntsTraits>(root.get_file());
  ssks = get_keys<StringsTraits>(root.get_file());
  v3ks = get_keys<Vector3Traits>(root.get_file());
  v4ks = get_keys<Vector4Traits>(root.get_file());
  v3sks = get_keys<Vector3sTraits>(root.get_file());
  using std::operator<<;
  RMF_PRINT_TREE(out, NodeConstHandle, root, n.get_children().size(),
                 n.get_children(),
                 show_node(n, out, fks, fsks, iks, isks, sks, ssks, v3ks, v4ks,
                           v3sks, prefix0 + "   "));
}

void show_hierarchy_with_decorators(NodeConstHandle root, bool,
                                    std::ostream& out) {
  decorator::BondConstFactory bdf(root.get_file());
  decorator::ColoredConstFactory ccf(root.get_file());
  decorator::ParticleConstFactory pcf(root.get_file());
  decorator::IntermediateParticleConstFactory ipcf(root.get_file());
  decorator::RigidParticleConstFactory rpcf(root.get_file());
  decorator::ScoreConstFactory scf(root.get_file());
  decorator::BallConstFactory bcf(root.get_file());
  decorator::CylinderConstFactory cycf(root.get_file());
  decorator::SegmentConstFactory segcf(root.get_file());
  decorator::ResidueConstFactory rcf(root.get_file());
  decorator::AtomConstFactory acf(root.get_file());
  decorator::ChainConstFactory chaincf(root.get_file());
  decorator::DomainConstFactory fragcf(root.get_file());
  decorator::CopyConstFactory copycf(root.get_file());
  decorator::DiffuserConstFactory diffusercf(root.get_file());
  decorator::TypedConstFactory typedcf(root.get_file());
  using std::operator<<;
  RMF_PRINT_TREE(
      out, NodeConstHandle, root, n.get_children().size(), n.get_children(),
      show_node_decorators(n, out, bdf, ccf, pcf, ipcf, rpcf, scf, bcf, cycf, segcf,
                           rcf, acf, chaincf, fragcf, copycf, diffusercf,
                           typedcf, prefix0 + "   "));
}

} /* namespace RMF */

RMF_DISABLE_WARNINGS
<|endoftext|>