<commit_before>/****************************************************************************
**
** Copyright (C) Qxt Foundation. Some rights reserved.
**
** This file is part of the QxtWeb  module of the Qt eXTension library
**
** This library is free software; you can redistribute it and/or modify it
** under the terms of th Common Public License, version 1.0, as published by
** IBM.
**
** This file is provided "AS IS", without WARRANTIES OR CONDITIONS OF ANY
** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY
** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR
** FITNESS FOR A PARTICULAR PURPOSE.
**
** You should have received a copy of the CPL along with this file.
** See the LICENSE file and the cpl1.0.txt file included with the source
** distribution for more information. If you did not receive a copy of the
** license, contact the Qxt Foundation.
**
** <http://libqxt.org>  <foundation@libqxt.org>
**
****************************************************************************/

/*!
        \class QxtHtmlTemplate QxtHtmlTemplate
        \ingroup web
        \brief Basic Html Template Engine

        open a file containing html code and php style variables.
        use the square bracket operators to assign content for a variable

        \code
        QxtHtmlTemplate index;
        if(!index.open)
                return 404;
        index["content"]="hello world";
        echo()<<index.render();
        \endcode
        the realatet html code would look like:
        \code
        <html>
        <head>
                <title>Test Page</title>
        </head>
                <?=content?>
        </html>
        \endcode
*/

/*!
        \fn QxtHtmlTemplate::open(const QString& filename)
        Returns true on sucess and false on failure.
        note that it will also return false for an empty html file.

        \fn QString QxtHtmlTemplate::render() const
        Uses the variables you set and renders the opened file.
        returns an empty string on failure.
        Does NOT take care of not assigned variables, they will remain in the returned string
 */

#include "qxthtmltemplate.h"
#include <QFile>
#include <QStringList>

QxtHtmlTemplate::QxtHtmlTemplate() : QMap<QString,QString>()
{}

void QxtHtmlTemplate::load(const QString& d)
{
    data=d;
}

bool QxtHtmlTemplate::open(const QString& filename)
{
    QFile f(filename);
    f.open(QIODevice::ReadOnly);
    data = QString::fromLocal8Bit(f.readAll());
    f.close();
    if (data.isEmpty())
        {
        qWarning("QxtHtmlTemplate::open(\"%s\") empty or non existant",qPrintable(filename));
        return false;
        }
    return true;
}

QString QxtHtmlTemplate::render() const
{
    ///try to preserve indention by parsing char by char and saving the last non-space character

    QString output = data;
    int lastnewline=0;

    for (int i=0;i<output.count();i++)
    {
        if (output.at(i)=='\n')
        {
            lastnewline=i;
        }

        if (output.at(i)=='<' && output.at(i+1)=='?'  && output.at(i+2)=='=')
        {
            int j=i+3;
            QString var;

            for (int jj=j;jj<output.count();jj++)
            {
                if (output.at(jj)=='?' && output.at(jj+1)=='>')
                {
                    j=jj;
                    break;
                }
                var+=output.at(jj);
            }

            if (j==i)
            {
                qWarning("QxtHtmlTemplate::render()  unterminated <?= ");
                continue;
            }

            if(!contains(var))
            {
                qWarning("QxtHtmlTemplate::render()  unused variable \"%s\"",qPrintable(var));
                continue;
            }
            output.replace(i,j-i+2,QString(value(var)).replace("\n","\n"+QString(i-lastnewline-1,QChar(' '))));

        }

    }

    return output;
}

<commit_msg>warning about recursion<commit_after>/****************************************************************************
**
** Copyright (C) Qxt Foundation. Some rights reserved.
**
** This file is part of the QxtWeb  module of the Qt eXTension library
**
** This library is free software; you can redistribute it and/or modify it
** under the terms of th Common Public License, version 1.0, as published by
** IBM.
**
** This file is provided "AS IS", without WARRANTIES OR CONDITIONS OF ANY
** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY
** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR
** FITNESS FOR A PARTICULAR PURPOSE.
**
** You should have received a copy of the CPL along with this file.
** See the LICENSE file and the cpl1.0.txt file included with the source
** distribution for more information. If you did not receive a copy of the
** license, contact the Qxt Foundation.
**
** <http://libqxt.org>  <foundation@libqxt.org>
**
****************************************************************************/

/*!
        \class QxtHtmlTemplate QxtHtmlTemplate
        \ingroup web
        \brief Basic Html Template Engine

        open a file containing html code and php style variables.
        use the square bracket operators to assign content for a variable

        \code
        QxtHtmlTemplate index;
        if(!index.open)
                return 404;
        index["content"]="hello world";
        echo()<<index.render();
        \endcode
        the realatet html code would look like:
        \code
        <html>
        <head>
                <title>Test Page</title>
        </head>
                <?=content?>
        </html>
        \endcode

        funny storry: whe are using this class to make our documentation (eat your own dogfood, you know ;).
        but when we where parsing exactly this file you read right now the first time, QxtHtmlTemplate got stuck in an infinite loop. guess why. becouse of that example above :D
        So be warned: when you assign content to a variable that contains the variable name itself, render() will never return.

*/

/*!
        \fn QxtHtmlTemplate::open(const QString& filename)
        Returns true on sucess and false on failure.
        note that it will also return false for an empty html file.

        \fn QString QxtHtmlTemplate::render() const
        Uses the variables you set and renders the opened file.
        returns an empty string on failure.
        Does NOT take care of not assigned variables, they will remain in the returned string
 */

#include "qxthtmltemplate.h"
#include <QFile>
#include <QStringList>

QxtHtmlTemplate::QxtHtmlTemplate() : QMap<QString,QString>()
{}

void QxtHtmlTemplate::load(const QString& d)
{
    data=d;
}

bool QxtHtmlTemplate::open(const QString& filename)
{
    QFile f(filename);
    f.open(QIODevice::ReadOnly);
    data = QString::fromLocal8Bit(f.readAll());
    f.close();
    if (data.isEmpty())
        {
        qWarning("QxtHtmlTemplate::open(\"%s\") empty or non existant",qPrintable(filename));
        return false;
        }
    return true;
}

QString QxtHtmlTemplate::render() const
{
    ///try to preserve indention by parsing char by char and saving the last non-space character

    QString output = data;
    int lastnewline=0;

    for (int i=0;i<output.count();i++)
    {
        if (output.at(i)=='\n')
        {
            lastnewline=i;
        }

        if (output.at(i)=='<' && output.at(i+1)=='?'  && output.at(i+2)=='=')
        {
            int j=i+3;
            QString var;

            for (int jj=j;jj<output.count();jj++)
            {
                if (output.at(jj)=='?' && output.at(jj+1)=='>')
                {
                    j=jj;
                    break;
                }
                var+=output.at(jj);
            }

            if (j==i)
            {
                qWarning("QxtHtmlTemplate::render()  unterminated <?= ");
                continue;
            }

            if(!contains(var))
            {
                qWarning("QxtHtmlTemplate::render()  unused variable \"%s\"",qPrintable(var));
                continue;
            }
            output.replace(i,j-i+2,QString(value(var)).replace("\n","\n"+QString(i-lastnewline-1,QChar(' '))));

        }

    }

    return output;
}

<|endoftext|>


<commit_before><commit_msg>[Sketcher] Solver message updated when toggling driving in datum dialog<commit_after><|endoftext|>


<commit_before>#pragma once

#include "TextureAtlas.hpp"
#include <vector>
#include <string>
#include <memory>
#include "ft2build.h"
#include FT_FREETYPE_H
#include "vec.hpp"

namespace rffalcon
{
	struct GlyphKerning
	{
		wchar_t charCode;
		float kerning;
	};

	struct TextureGlyph
	{
        wchar_t charCode;
		int outlineType;
		float outlineThickness;
		int width;
		int height;
		int offsetX;
		int offsetY;
		float s0;
		float t0;
		float s1;
		float t1;
		float advanceX;
		float advanceY;
		std::vector<GlyphKerning> kerning;

		float getKerning(char kerningCharCode)
		{
			int result = 0;
			for (int index = 0; index < kerning.size(); ++index)
			{
				GlyphKerning k = kerning[index];
				if (k.charCode == kerningCharCode)
				{
					result = k.kerning;
				}
			}
			return result;
		}
	};

	class TextureFont
	{
	public:
		TextureFont(std::shared_ptr<TextureAtlas> atlas, const float pointSize, const std::string &filename);
		~TextureFont();

		float getHeight() const;
		int loadGlyphs(const std::wstring &text);
		std::shared_ptr<TextureGlyph> getGlyph(const wchar_t charCode);

	private:
		void _initialize();
		void _loadFace(FT_Library *library, FT_Face *face);
		void _loadFace(FT_Library *library, FT_Face *face, float pointSize);
		bool _shouldLoadGlyph(const wchar_t charCode);
		FT_Int32 _getFlags();
		void _setFiltering(FT_Library library);
		GlyphData _getGlyphData(FT_Library library, FT_Face face);
		void _addTextureGlyph(wchar_t charCode, GlyphData glyphData, s1::ivec4 region, FT_Face face, FT_UInt glyphIndex);
		s1::ivec4 _renderToAtlas(GlyphData glyphData, const wchar_t charCode, FT_Face face, FT_UInt glyphIndex);
		void _generateKerning();
		std::shared_ptr<TextureGlyph> _tryGetGlyph(const wchar_t charCode);

		std::shared_ptr<TextureAtlas> _atlas;
		float _pointSize;
		std::vector<std::shared_ptr<TextureGlyph>> _glyphs;
		float _height = 0;
		float _ascender = 0;
		float _descender = 0;
		float _linegap = 0;
		int _outlineType = 0;
		float _outlineThickness = 0.0;
		std::string _filename;
		bool _hinting = true;
		bool _filtering = true;
		unsigned char _lcdWeights[5];
	};
}<commit_msg>Fix to getKerning API, takes wchar_t and returns float, not char and int.<commit_after>#pragma once

#include "TextureAtlas.hpp"
#include <vector>
#include <string>
#include <memory>
#include "ft2build.h"
#include FT_FREETYPE_H
#include "vec.hpp"

namespace rffalcon
{
	struct GlyphKerning
	{
		wchar_t charCode;
		float kerning;
	};

	struct TextureGlyph
	{
        wchar_t charCode;
		int outlineType;
		float outlineThickness;
		int width;
		int height;
		int offsetX;
		int offsetY;
		float s0;
		float t0;
		float s1;
		float t1;
		float advanceX;
		float advanceY;
		std::vector<GlyphKerning> kerning;

		float getKerning(wchar_t kerningCharCode)
		{
			float result = 0.0f;
			for (int index = 0; index < static_cast<int>(kerning.size()); ++index)
			{
				GlyphKerning k = kerning[index];
				if (k.charCode == kerningCharCode)
				{
					result = k.kerning;
				}
			}
			return result;
		}
	};

	class TextureFont
	{
	public:
		TextureFont(std::shared_ptr<TextureAtlas> atlas, const float pointSize, const std::string &filename);
		~TextureFont();

		float getHeight() const;
		int loadGlyphs(const std::wstring &text);
		std::shared_ptr<TextureGlyph> getGlyph(const wchar_t charCode);

	private:
		void _initialize();
		void _loadFace(FT_Library *library, FT_Face *face);
		void _loadFace(FT_Library *library, FT_Face *face, float pointSize);
		bool _shouldLoadGlyph(const wchar_t charCode);
		FT_Int32 _getFlags();
		void _setFiltering(FT_Library library);
		GlyphData _getGlyphData(FT_Library library, FT_Face face);
		void _addTextureGlyph(wchar_t charCode, GlyphData glyphData, s1::ivec4 region, FT_Face face, FT_UInt glyphIndex);
		s1::ivec4 _renderToAtlas(GlyphData glyphData, const wchar_t charCode, FT_Face face, FT_UInt glyphIndex);
		void _generateKerning();
		std::shared_ptr<TextureGlyph> _tryGetGlyph(const wchar_t charCode);

		std::shared_ptr<TextureAtlas> _atlas;
		float _pointSize;
		std::vector<std::shared_ptr<TextureGlyph>> _glyphs;
		float _height = 0;
		float _ascender = 0;
		float _descender = 0;
		float _linegap = 0;
		int _outlineType = 0;
		float _outlineThickness = 0.0;
		std::string _filename;
		bool _hinting = true;
		bool _filtering = true;
		unsigned char _lcdWeights[5];
	};
}<|endoftext|>


<commit_before>/// HEADER
#include <csapex/msg/input.h>

/// COMPONENT
#include <csapex/msg/output.h>
#include <csapex/command/delete_connection.h>
#include <csapex/command/command.h>
#include <csapex/utility/assert.h>

/// SYSTEM
#include <iostream>

using namespace csapex;

Input::Input(Settings& settings, const UUID &uuid)
    : Connectable(settings, uuid), target(NULL), buffer_(new Buffer), optional_(false)
{
    QObject::connect(this, SIGNAL(gotMessage(ConnectionType::Ptr)), this, SLOT(handleMessage(ConnectionType::Ptr)), Qt::QueuedConnection);
}

Input::Input(Settings &settings, Unique* parent, int sub_id)
    : Connectable(settings, parent, sub_id, TYPE_IN), target(NULL), buffer_(new Buffer), optional_(false)
{
    QObject::connect(this, SIGNAL(gotMessage(ConnectionType::Ptr)), this, SLOT(handleMessage(ConnectionType::Ptr)), Qt::QueuedConnection);
}

Input::~Input()
{
    if(target != NULL) {
        target->removeConnection(this);
    }

    free();
}

void Input::reset()
{
    free();
    setSequenceNumber(0);
}

bool Input::tryConnect(Connectable* other_side)
{
    if(!other_side->canOutput()) {
        std::cerr << "cannot connect, other side can't output" << std::endl;
        return false;
    }

    return other_side->tryConnect(this);
}

bool Input::acknowledgeConnection(Connectable* other_side)
{
    target = dynamic_cast<Output*>(other_side);
    connect(other_side, SIGNAL(destroyed(QObject*)), this, SLOT(removeConnection(QObject*)));
    connect(other_side, SIGNAL(enabled(bool)), this, SIGNAL(connectionEnabled(bool)));
    return true;
}

void Input::removeConnection(Connectable* other_side)
{
    if(target != NULL) {
        apex_assert_hard(other_side == target);
        target = NULL;

        Q_EMIT connectionRemoved(this);
    }
}

Command::Ptr Input::removeAllConnectionsCmd()
{
    Command::Ptr cmd(new command::DeleteConnection(target, this));
    return cmd;
}

void Input::setOptional(bool optional)
{
    optional_ = optional;
}

bool Input::isOptional() const
{
    return optional_;
}

bool Input::hasMessage() const
{
    return isConnected() && buffer_->isFilled() && !buffer_->isType<connection_types::NoMessage>();
}

void Input::stop()
{
    buffer_->disable();
    Connectable::stop();
}

void Input::free()
{
    buffer_->free();

    setBlocked(false);
}

void Input::enable()
{
    Connectable::enable();
//    if(isConnected() && !getSource()->isEnabled()) {
//        getSource()->enable();
//    }
}

void Input::disable()
{
    Connectable::disable();

//    if(isBlocked()) {
        free();
        notifyMessageProcessed();
//    }
//    if(isConnected() && getSource()->isEnabled()) {
//        getSource()->disable();
//    }
}

void Input::removeAllConnectionsNotUndoable()
{
    if(target != NULL) {
        target->removeConnection(this);
        target = NULL;
        setError(false);
        Q_EMIT disconnected(this);
    }
}

bool Input::canConnectTo(Connectable* other_side, bool move) const
{
    return Connectable::canConnectTo(other_side, move) && (move || !isConnected());
}

bool Input::targetsCanBeMovedTo(Connectable* other_side) const
{
    return target->canConnectTo(other_side, true) /*&& canConnectTo(getConnected())*/;
}

bool Input::isConnected() const
{
    return target != NULL;
}

void Input::connectionMovePreview(Connectable *other_side)
{
    Q_EMIT(connectionInProgress(getSource(), other_side));
}

void Input::validateConnections()
{
    bool e = false;
    if(isConnected()) {
        if(!target->getType()->canConnectTo(getType().get())) {
            e = true;
        }
    }

    setError(e);
}

Connectable *Input::getSource() const
{
    return target;
}

void Input::inputMessage(ConnectionType::Ptr message)
{
    Q_EMIT gotMessage(message);
}

void Input::handleMessage(ConnectionType::Ptr message)
{
    if(!isEnabled()) {
        return;
    }

    int s = message->sequenceNumber();
    if(s < sequenceNumber()) {
        std::cerr << "connector @" << getUUID().getFullName() <<
                     ": dropping old message @ with #" << s <<
                     " < #" << sequenceNumber() << std::endl;
        return;
    }
    setSequenceNumber(s);

    setBlocked(true);

    buffer_->write(message);

    count_++;

    Q_EMIT messageArrived(this);
}

void Input::notifyMessageProcessed()
{
    Connectable::notifyMessageProcessed();

    if(target) {
        target->notifyMessageProcessed();
    }
}
<commit_msg>errors<commit_after>/// HEADER
#include <csapex/msg/input.h>

/// COMPONENT
#include <csapex/msg/output.h>
#include <csapex/command/delete_connection.h>
#include <csapex/command/command.h>
#include <csapex/utility/assert.h>

/// SYSTEM
#include <iostream>

using namespace csapex;

Input::Input(Settings& settings, const UUID &uuid)
    : Connectable(settings, uuid), target(NULL), buffer_(new Buffer), optional_(false)
{
    QObject::connect(this, SIGNAL(gotMessage(ConnectionType::Ptr)), this, SLOT(handleMessage(ConnectionType::Ptr)), Qt::QueuedConnection);
}

Input::Input(Settings &settings, Unique* parent, int sub_id)
    : Connectable(settings, parent, sub_id, TYPE_IN), target(NULL), buffer_(new Buffer), optional_(false)
{
    QObject::connect(this, SIGNAL(gotMessage(ConnectionType::Ptr)), this, SLOT(handleMessage(ConnectionType::Ptr)), Qt::QueuedConnection);
}

Input::~Input()
{
    if(target != NULL) {
        target->removeConnection(this);
    }

    free();
}

void Input::reset()
{
    free();
    setSequenceNumber(0);
}

bool Input::tryConnect(Connectable* other_side)
{
    if(!other_side->canOutput()) {
        std::cerr << "cannot connect, other side can't output" << std::endl;
        return false;
    }

    return other_side->tryConnect(this);
}

bool Input::acknowledgeConnection(Connectable* other_side)
{
    target = dynamic_cast<Output*>(other_side);
    connect(other_side, SIGNAL(destroyed(QObject*)), this, SLOT(removeConnection(QObject*)));
    connect(other_side, SIGNAL(enabled(bool)), this, SIGNAL(connectionEnabled(bool)));
    return true;
}

void Input::removeConnection(Connectable* other_side)
{
    if(target != NULL) {
        apex_assert_hard(other_side == target);
        target = NULL;

        Q_EMIT connectionRemoved(this);
    }
}

Command::Ptr Input::removeAllConnectionsCmd()
{
    Command::Ptr cmd(new command::DeleteConnection(target, this));
    return cmd;
}

void Input::setOptional(bool optional)
{
    optional_ = optional;
}

bool Input::isOptional() const
{
    return optional_;
}

bool Input::hasMessage() const
{
    return isConnected() && buffer_->isFilled() && !buffer_->isType<connection_types::NoMessage>();
}

void Input::stop()
{
    buffer_->disable();
    Connectable::stop();
}

void Input::free()
{
    buffer_->free();

    setBlocked(false);
}

void Input::enable()
{
    Connectable::enable();
//    if(isConnected() && !getSource()->isEnabled()) {
//        getSource()->enable();
//    }
}

void Input::disable()
{
    Connectable::disable();

//    if(isBlocked()) {
        free();
        notifyMessageProcessed();
//    }
//    if(isConnected() && getSource()->isEnabled()) {
//        getSource()->disable();
//    }
}

void Input::removeAllConnectionsNotUndoable()
{
    if(target != NULL) {
        target->removeConnection(this);
        target = NULL;
        setError(false);
        Q_EMIT disconnected(this);
    }
}

bool Input::canConnectTo(Connectable* other_side, bool move) const
{
    return Connectable::canConnectTo(other_side, move) && (move || !isConnected());
}

bool Input::targetsCanBeMovedTo(Connectable* other_side) const
{
    return target->canConnectTo(other_side, true) /*&& canConnectTo(getConnected())*/;
}

bool Input::isConnected() const
{
    return target != NULL;
}

void Input::connectionMovePreview(Connectable *other_side)
{
    Q_EMIT(connectionInProgress(getSource(), other_side));
}

void Input::validateConnections()
{
    bool e = false;
    if(isConnected()) {
        if(!target->getType()->canConnectTo(getType().get())) {
            e = true;
        }
    }

    setError(e);
}

Connectable *Input::getSource() const
{
    return target;
}

void Input::inputMessage(ConnectionType::Ptr message)
{
    Q_EMIT gotMessage(message);
}

void Input::handleMessage(ConnectionType::Ptr message)
{
    if(!isEnabled()) {
        return;
    }

    int s = message->sequenceNumber();
    if(s < sequenceNumber()) {
        std::cerr << "connector @" << getUUID().getFullName() <<
                     ": dropping old message @ with #" << s <<
                     " < #" << sequenceNumber() << std::endl;
        return;
    }
    setSequenceNumber(s);

    setBlocked(true);

    try {
        buffer_->write(message);
    } catch(const std::exception& e) {
        std::cerr << getUUID() << ": writing message failed: " << e.what() << std::endl;
        throw e;
    }

    count_++;

    Q_EMIT messageArrived(this);
}

void Input::notifyMessageProcessed()
{
    Connectable::notifyMessageProcessed();

    if(target) {
        target->notifyMessageProcessed();
    }
}
<|endoftext|>


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

/// \author Adolfo Rodriguez Tsouroukdissian

#include <stdexcept>
#include <gtest/gtest.h>
#include <ros/console.h>
#include <joint_trajectory_controller/joint_trajectory_segment.h>

using namespace trajectory_interface;
using namespace trajectory_msgs;

typedef JointTrajectorySegment<double> Segment;

class JointTrajectorySegmentTest : public ::testing::Test
{
public:
  JointTrajectorySegmentTest()
    : traj_start_time(0.5)
  {
    p_start.positions.resize(1, 2.0);
    p_start.velocities.resize(1, -1.0);
    p_start.time_from_start = ros::Duration(1.0);

    p_end.positions.resize(1, 4.0);
    p_end.velocities.resize(1, -2.0);
    p_end.time_from_start = ros::Duration(2.0);
  }

protected:
  ros::Time traj_start_time;
  JointTrajectoryPoint p_start;
  JointTrajectoryPoint p_end;
};

TEST_F(JointTrajectorySegmentTest, InvalidSegmentConstruction)
{
  // Empty start point
  {
    JointTrajectoryPoint p_start_bad;
    EXPECT_THROW(Segment(traj_start_time, p_start_bad, p_end), std::invalid_argument);
    try {Segment(traj_start_time, JointTrajectoryPoint(), p_end);}
    catch (const std::invalid_argument& ex) {ROS_ERROR_STREAM(ex.what());}
  }

  // Start/end data size mismatch
  {
    JointTrajectoryPoint p_start_bad = p_start;
    p_start_bad.positions.push_back(0.0);
    EXPECT_THROW(Segment(traj_start_time, p_start_bad, p_end), std::invalid_argument);
    try {Segment(traj_start_time, p_start_bad, p_end);}
    catch (const std::invalid_argument& ex) {ROS_ERROR_STREAM(ex.what());}
  }

  // Invalid start state
  {
    JointTrajectoryPoint p_start_bad = p_start;
    p_start_bad.velocities.push_back(0.0);
    EXPECT_THROW(Segment(traj_start_time, p_start_bad, p_end), std::invalid_argument);
    try {Segment(traj_start_time, p_start_bad, p_end);}
    catch (const std::invalid_argument& ex) {ROS_ERROR_STREAM(ex.what());}
  }

  // Invalid end state
  {
    JointTrajectoryPoint p_end_bad = p_end;
    p_end_bad.velocities.push_back(0.0);
    EXPECT_THROW(Segment(traj_start_time, p_start, p_end_bad), std::invalid_argument);
    try {Segment(traj_start_time, p_start, p_end_bad);}
    catch (const std::invalid_argument& ex) {ROS_ERROR_STREAM(ex.what());}
  }
}

TEST_F(JointTrajectorySegmentTest, ValidSegmentConstruction)
{
  // Construct segment
  EXPECT_NO_THROW(Segment(traj_start_time, p_start, p_end));
  Segment segment(traj_start_time, p_start, p_end);

  // Check start/end times
  {
    const typename Segment::Time start_time = (traj_start_time + p_start.time_from_start).toSec();
    const typename Segment::Time end_time   = (traj_start_time + p_end.time_from_start).toSec();
    EXPECT_EQ(start_time, segment.startTime());
    EXPECT_EQ(end_time,   segment.endTime());
  }

  // Check start state
  {
    typename Segment::State state;
    segment.sample(segment.startTime(), state);
    EXPECT_EQ(p_start.positions.front(),  state.front().position);
    EXPECT_EQ(p_start.velocities.front(), state.front().velocity);
  }

  // Check end state
  {
    typename Segment::State state;
    segment.sample(segment.endTime(), state);
    EXPECT_EQ(p_end.positions.front(),  state.front().position);
    EXPECT_EQ(p_end.velocities.front(), state.front().velocity);
  }
}

int main(int argc, char** argv)
{
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

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

/// \author Adolfo Rodriguez Tsouroukdissian

#include <stdexcept>
#include <gtest/gtest.h>
#include <ros/console.h>
#include <joint_trajectory_controller/joint_trajectory_segment.h>

using namespace trajectory_interface;
using namespace trajectory_msgs;

typedef JointTrajectorySegment<double> Segment;

class JointTrajectorySegmentTest : public ::testing::Test
{
public:
  JointTrajectorySegmentTest()
    : traj_start_time(0.5)
  {
    p_start.positions.resize(1, 2.0);
    p_start.velocities.resize(1, -1.0);
    p_start.time_from_start = ros::Duration(1.0);

    p_end.positions.resize(1, 4.0);
    p_end.velocities.resize(1, -2.0);
    p_end.time_from_start = ros::Duration(2.0);

    start_time = (traj_start_time + p_start.time_from_start).toSec();
    start_state.resize(1);
    start_state.front().position = p_start.positions.front();
    start_state.front().velocity = p_start.velocities.front();

    end_time = (traj_start_time + p_end.time_from_start).toSec();
    end_state.resize(1);
    end_state.front().position = p_end.positions.front();
    end_state.front().velocity = p_end.velocities.front();
  }

protected:
  ros::Time traj_start_time;
  JointTrajectoryPoint p_start;
  JointTrajectoryPoint p_end;

  typename Segment::Time start_time, end_time;
  typename Segment::State start_state, end_state;
};

TEST_F(JointTrajectorySegmentTest, InvalidSegmentConstruction)
{
  // Empty start point
  {
    JointTrajectoryPoint p_start_bad;
    EXPECT_THROW(Segment(traj_start_time, p_start_bad, p_end), std::invalid_argument);
    try {Segment(traj_start_time, JointTrajectoryPoint(), p_end);}
    catch (const std::invalid_argument& ex) {ROS_ERROR_STREAM(ex.what());}
  }

  // Start/end data size mismatch
  {
    JointTrajectoryPoint p_start_bad = p_start;
    p_start_bad.positions.push_back(0.0);
    EXPECT_THROW(Segment(traj_start_time, p_start_bad, p_end), std::invalid_argument);
    try {Segment(traj_start_time, p_start_bad, p_end);}
    catch (const std::invalid_argument& ex) {ROS_ERROR_STREAM(ex.what());}
  }

  // Invalid start state
  {
    JointTrajectoryPoint p_start_bad = p_start;
    p_start_bad.velocities.push_back(0.0);
    EXPECT_THROW(Segment(traj_start_time, p_start_bad, p_end), std::invalid_argument);
    try {Segment(traj_start_time, p_start_bad, p_end);}
    catch (const std::invalid_argument& ex) {ROS_ERROR_STREAM(ex.what());}
  }

  // Invalid end state
  {
    JointTrajectoryPoint p_end_bad = p_end;
    p_end_bad.velocities.push_back(0.0);
    EXPECT_THROW(Segment(traj_start_time, p_start, p_end_bad), std::invalid_argument);
    try {Segment(traj_start_time, p_start, p_end_bad);}
    catch (const std::invalid_argument& ex) {ROS_ERROR_STREAM(ex.what());}
  }
}

TEST_F(JointTrajectorySegmentTest, ValidSegmentConstructionRos)
{
  // Construct segment from ROS message
  EXPECT_NO_THROW(Segment(traj_start_time, p_start, p_end));
  Segment segment(traj_start_time, p_start, p_end);

  // Check start/end times
  {
    const typename Segment::Time start_time = (traj_start_time + p_start.time_from_start).toSec();
    const typename Segment::Time end_time   = (traj_start_time + p_end.time_from_start).toSec();
    EXPECT_EQ(start_time, segment.startTime());
    EXPECT_EQ(end_time,   segment.endTime());
  }

  // Check start state
  {
    typename Segment::State state;
    segment.sample(segment.startTime(), state);
    EXPECT_EQ(p_start.positions.front(),  state.front().position);
    EXPECT_EQ(p_start.velocities.front(), state.front().velocity);
  }

  // Check end state
  {
    typename Segment::State state;
    segment.sample(segment.endTime(), state);
    EXPECT_EQ(p_end.positions.front(),  state.front().position);
    EXPECT_EQ(p_end.velocities.front(), state.front().velocity);
  }
}

TEST_F(JointTrajectorySegmentTest, ValidSegmentConstruction)
{
  // Construct segment from ROS message
  EXPECT_NO_THROW(Segment(start_time,start_state, end_time, end_state));
  Segment segment(start_time,start_state, end_time, end_state);

  // Check start/end times
  {
    const typename Segment::Time start_time = (traj_start_time + p_start.time_from_start).toSec();
    const typename Segment::Time end_time   = (traj_start_time + p_end.time_from_start).toSec();
    EXPECT_EQ(start_time, segment.startTime());
    EXPECT_EQ(end_time,   segment.endTime());
  }

  // Check start state
  {
    typename Segment::State state;
    segment.sample(segment.startTime(), state);
    EXPECT_EQ(p_start.positions.front(),  state.front().position);
    EXPECT_EQ(p_start.velocities.front(), state.front().velocity);
  }

  // Check end state
  {
    typename Segment::State state;
    segment.sample(segment.endTime(), state);
    EXPECT_EQ(p_end.positions.front(),  state.front().position);
    EXPECT_EQ(p_end.velocities.front(), state.front().velocity);
  }
}

int main(int argc, char** argv)
{
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

<|endoftext|>


<commit_before>//
// Copyright 2016 Francisco Jerez
//
// 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.
//

///
/// \file
/// Some thin wrappers around the Clang/LLVM API used to preserve
/// compatibility with older API versions while keeping the ifdef clutter low
/// in the rest of the clover::llvm subtree.  In case of an API break please
/// consider whether it's possible to preserve backwards compatibility by
/// introducing a new one-liner inline function or typedef here under the
/// compat namespace in order to keep the running code free from preprocessor
/// conditionals.
///

#ifndef CLOVER_LLVM_COMPAT_HPP
#define CLOVER_LLVM_COMPAT_HPP

#include "util/algorithm.hpp"

#include <llvm/Linker/Linker.h>
#include <llvm/Transforms/IPO.h>
#include <llvm/Target/TargetMachine.h>
#if HAVE_LLVM >= 0x0400
#include <llvm/Support/Error.h>
#else
#include <llvm/Support/ErrorOr.h>
#endif

#if HAVE_LLVM >= 0x0307
#include <llvm/IR/LegacyPassManager.h>
#include <llvm/Analysis/TargetLibraryInfo.h>
#else
#include <llvm/PassManager.h>
#include <llvm/Target/TargetLibraryInfo.h>
#include <llvm/Target/TargetSubtargetInfo.h>
#include <llvm/Support/FormattedStream.h>
#endif

#include <clang/Frontend/CodeGenOptions.h>
#include <clang/Frontend/CompilerInstance.h>

namespace clover {
   namespace llvm {
      namespace compat {
#if HAVE_LLVM >= 0x0307
         typedef ::llvm::TargetLibraryInfoImpl target_library_info;
#else
         typedef ::llvm::TargetLibraryInfo target_library_info;
#endif

         inline void
         set_lang_defaults(clang::CompilerInvocation &inv,
                           clang::LangOptions &lopts, clang::InputKind ik,
                           const ::llvm::Triple &t,
                           clang::PreprocessorOptions &ppopts,
                           clang::LangStandard::Kind std) {
#if HAVE_LLVM >= 0x0309
            inv.setLangDefaults(lopts, ik, t, ppopts, std);
#else
            inv.setLangDefaults(lopts, ik, std);
#endif
         }

         inline void
         add_link_bitcode_file(clang::CodeGenOptions &opts,
                               const std::string &path) {
#if HAVE_LLVM >= 0x0308
            opts.LinkBitcodeFiles.emplace_back(::llvm::Linker::Flags::None, path);
#else
            opts.LinkBitcodeFile = path;
#endif
         }

#if HAVE_LLVM >= 0x0307
         typedef ::llvm::legacy::PassManager pass_manager;
#else
         typedef ::llvm::PassManager pass_manager;
#endif

         inline void
         add_data_layout_pass(pass_manager &pm) {
#if HAVE_LLVM < 0x0307
            pm.add(new ::llvm::DataLayoutPass());
#endif
         }

         inline void
         add_internalize_pass(pass_manager &pm,
                              const std::vector<std::string> &names) {
#if HAVE_LLVM >= 0x0309
            pm.add(::llvm::createInternalizePass(
                      [=](const ::llvm::GlobalValue &gv) {
                         return std::find(names.begin(), names.end(),
                                          gv.getName()) != names.end();
                      }));
#else
            pm.add(::llvm::createInternalizePass(std::vector<const char *>(
                      map(std::mem_fn(&std::string::data), names))));
#endif
         }

         inline std::unique_ptr<::llvm::Linker>
         create_linker(::llvm::Module &mod) {
#if HAVE_LLVM >= 0x0308
            return std::unique_ptr<::llvm::Linker>(new ::llvm::Linker(mod));
#else
            return std::unique_ptr<::llvm::Linker>(new ::llvm::Linker(&mod));
#endif
         }

         inline bool
         link_in_module(::llvm::Linker &linker,
                        std::unique_ptr<::llvm::Module> mod) {
#if HAVE_LLVM >= 0x0308
            return linker.linkInModule(std::move(mod));
#else
            return linker.linkInModule(mod.get());
#endif
         }

#if HAVE_LLVM >= 0x0307
         typedef ::llvm::raw_svector_ostream &raw_ostream_to_emit_file;
#else
         typedef ::llvm::formatted_raw_ostream raw_ostream_to_emit_file;
#endif

#if HAVE_LLVM >= 0x0307
         typedef ::llvm::DataLayout data_layout;
#else
         typedef const ::llvm::DataLayout *data_layout;
#endif

         inline data_layout
         get_data_layout(::llvm::TargetMachine &tm) {
#if HAVE_LLVM >= 0x0307
            return tm.createDataLayout();
#else
            return tm.getSubtargetImpl()->getDataLayout();
#endif
         }

#if HAVE_LLVM >= 0x0309
         const auto default_reloc_model = ::llvm::None;
#else
         const auto default_reloc_model = ::llvm::Reloc::Default;
#endif

         template<typename M, typename F> void
         handle_module_error(M &mod, const F &f) {
#if HAVE_LLVM >= 0x0400
            if (::llvm::Error err = mod.takeError())
               ::llvm::handleAllErrors(std::move(err), [&](::llvm::ErrorInfoBase &eib) {
                     f(eib.message());
                  });
#else
            if (!mod)
               f(mod.getError().message());
#endif
         }
      }
   }
}

#endif
<commit_msg>clover: Fix build against clang SVN >= r293097<commit_after>//
// Copyright 2016 Francisco Jerez
//
// 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.
//

///
/// \file
/// Some thin wrappers around the Clang/LLVM API used to preserve
/// compatibility with older API versions while keeping the ifdef clutter low
/// in the rest of the clover::llvm subtree.  In case of an API break please
/// consider whether it's possible to preserve backwards compatibility by
/// introducing a new one-liner inline function or typedef here under the
/// compat namespace in order to keep the running code free from preprocessor
/// conditionals.
///

#ifndef CLOVER_LLVM_COMPAT_HPP
#define CLOVER_LLVM_COMPAT_HPP

#include "util/algorithm.hpp"

#include <llvm/Linker/Linker.h>
#include <llvm/Transforms/IPO.h>
#include <llvm/Target/TargetMachine.h>
#if HAVE_LLVM >= 0x0400
#include <llvm/Support/Error.h>
#else
#include <llvm/Support/ErrorOr.h>
#endif

#if HAVE_LLVM >= 0x0307
#include <llvm/IR/LegacyPassManager.h>
#include <llvm/Analysis/TargetLibraryInfo.h>
#else
#include <llvm/PassManager.h>
#include <llvm/Target/TargetLibraryInfo.h>
#include <llvm/Target/TargetSubtargetInfo.h>
#include <llvm/Support/FormattedStream.h>
#endif

#include <clang/Frontend/CodeGenOptions.h>
#include <clang/Frontend/CompilerInstance.h>

namespace clover {
   namespace llvm {
      namespace compat {
#if HAVE_LLVM >= 0x0307
         typedef ::llvm::TargetLibraryInfoImpl target_library_info;
#else
         typedef ::llvm::TargetLibraryInfo target_library_info;
#endif

         inline void
         set_lang_defaults(clang::CompilerInvocation &inv,
                           clang::LangOptions &lopts, clang::InputKind ik,
                           const ::llvm::Triple &t,
                           clang::PreprocessorOptions &ppopts,
                           clang::LangStandard::Kind std) {
#if HAVE_LLVM >= 0x0309
            inv.setLangDefaults(lopts, ik, t, ppopts, std);
#else
            inv.setLangDefaults(lopts, ik, std);
#endif
         }

         inline void
         add_link_bitcode_file(clang::CodeGenOptions &opts,
                               const std::string &path) {
#if HAVE_LLVM >= 0x0500
            clang::CodeGenOptions::BitcodeFileToLink F;

            F.Filename = path;
            F.PropagateAttrs = true;
            F.LinkFlags = ::llvm::Linker::Flags::None;
            opts.LinkBitcodeFiles.emplace_back(F);
#elif HAVE_LLVM >= 0x0308
            opts.LinkBitcodeFiles.emplace_back(::llvm::Linker::Flags::None, path);
#else
            opts.LinkBitcodeFile = path;
#endif
         }

#if HAVE_LLVM >= 0x0307
         typedef ::llvm::legacy::PassManager pass_manager;
#else
         typedef ::llvm::PassManager pass_manager;
#endif

         inline void
         add_data_layout_pass(pass_manager &pm) {
#if HAVE_LLVM < 0x0307
            pm.add(new ::llvm::DataLayoutPass());
#endif
         }

         inline void
         add_internalize_pass(pass_manager &pm,
                              const std::vector<std::string> &names) {
#if HAVE_LLVM >= 0x0309
            pm.add(::llvm::createInternalizePass(
                      [=](const ::llvm::GlobalValue &gv) {
                         return std::find(names.begin(), names.end(),
                                          gv.getName()) != names.end();
                      }));
#else
            pm.add(::llvm::createInternalizePass(std::vector<const char *>(
                      map(std::mem_fn(&std::string::data), names))));
#endif
         }

         inline std::unique_ptr<::llvm::Linker>
         create_linker(::llvm::Module &mod) {
#if HAVE_LLVM >= 0x0308
            return std::unique_ptr<::llvm::Linker>(new ::llvm::Linker(mod));
#else
            return std::unique_ptr<::llvm::Linker>(new ::llvm::Linker(&mod));
#endif
         }

         inline bool
         link_in_module(::llvm::Linker &linker,
                        std::unique_ptr<::llvm::Module> mod) {
#if HAVE_LLVM >= 0x0308
            return linker.linkInModule(std::move(mod));
#else
            return linker.linkInModule(mod.get());
#endif
         }

#if HAVE_LLVM >= 0x0307
         typedef ::llvm::raw_svector_ostream &raw_ostream_to_emit_file;
#else
         typedef ::llvm::formatted_raw_ostream raw_ostream_to_emit_file;
#endif

#if HAVE_LLVM >= 0x0307
         typedef ::llvm::DataLayout data_layout;
#else
         typedef const ::llvm::DataLayout *data_layout;
#endif

         inline data_layout
         get_data_layout(::llvm::TargetMachine &tm) {
#if HAVE_LLVM >= 0x0307
            return tm.createDataLayout();
#else
            return tm.getSubtargetImpl()->getDataLayout();
#endif
         }

#if HAVE_LLVM >= 0x0309
         const auto default_reloc_model = ::llvm::None;
#else
         const auto default_reloc_model = ::llvm::Reloc::Default;
#endif

         template<typename M, typename F> void
         handle_module_error(M &mod, const F &f) {
#if HAVE_LLVM >= 0x0400
            if (::llvm::Error err = mod.takeError())
               ::llvm::handleAllErrors(std::move(err), [&](::llvm::ErrorInfoBase &eib) {
                     f(eib.message());
                  });
#else
            if (!mod)
               f(mod.getError().message());
#endif
         }
      }
   }
}

#endif
<|endoftext|>


<commit_before>//#define _GRIBCXX_DEBUG
#include <algorithm>
#include <cctype>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <functional>
#include <iostream>
#include <iomanip>
#include <list>
#include <map>
#include <memory>
#include <numeric>
#include <queue>
#include <set>
#include <string>
#include <utility>
#include <vector>
using namespace std;

// 基本テンプレート
#pragma region MACRO
#define P(x) cout << (x) << endl
#define p(x) cout << (x)
#define PED cout << "\n"
#define rep(i,n) for(int i=0; i<(int)n; ++i)
#define REP(i,x,n) for(int i=x; i<(int)n; ++i)
#define repi(i,n) for(int i=0; i<=(int)n; ++i)
#define REPI(i,x,n) for(int i=x; i<=(int)n; ++i)
#define ILP while(true)
#define FOR(i,c) for(__typeof((c).begin())!=(c).begin(); i!=(c).end(); ++i)
#define ALL(c) (c).begin(), (c).end()
#define mp make_pair
#pragma endregion

#pragma region TYPE_DEF
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<string, string> pss;
typedef pair<string, int> psi;
typedef pair<int, string> pis;
typedef vector<int> vi;
typedef vector<double> vd;
typedef vector<long> vl;
typedef vector<long long> vll;
typedef vector<string> vs;
#pragma endregion

// Effective std
#pragma region ESTD
template<typename C, typename T>
constexpr int count(C& c, T t) { return count(ALL(c), t); }
template<typename C, typename F>
constexpr int count_if(C& c, F f) { return count_if(ALL(c), f); }
template<typename C, typename T, typename U>
constexpr void replace(C& c, T t, U u) { replace(ALL(c), t, u); }
template<typename C, typename F, typename U>
constexpr void replace_if(C& c, F f, U u) { (ALL(c), f, u); }
template<typename C>
constexpr void sort(C& c) { sort(ALL(c)); }
template<typename C, typename Pred>
constexpr void sort(C& c, Pred p) { sort(ALL(c), p); }
template<typename C>
constexpr void reverse(C& c) { reverse(ALL(c)); }

#pragma endregion

// グラフテンプレート
#pragma region GRAPH

typedef int Weight;
struct Edge {
  int src, dst;
  Weight weight;
  Edge(int src, int dst, Weight weight) :
    src(src), dst(dst), weight(weight) {}
};

bool operator < (const Edge &e, const Edge &f) {
  return e.weight != f.weight ? e.weight > f.weight :
    e.src != f.src ? e.src < f.src : e.dst < f.dst;
}

typedef vector<Edge> Edges;
typedef vector<Edges> Graph;
typedef vector<Weight> Array;
typedef vector<Array> Matrix;

#pragma endregion

// 素数
#pragma region PRIME
bool is_prime(unsigned n) {
  switch(n) {
    case 0:
    case 1: return false;
    case 2: return true;
  }
  if (n%2==0) return false;
  for (unsigned i=3; i*i<=n; i+=2)
    if (n%i==0) return false;
  return true;
}
#pragma endregion

// 大文字/小文字変換
void mutal_tr(string &s) {
  for(int i=s.size(); i--;) {
    if(islower(s[i])) s[i] = toupper(s[i]);
    else if (isupper(s[i])) s[i] = tolower(s[i]);
  }
}
void to_upper(string &s) {
  for(int i=s.size(); i--;) s[i] = toupper(s[i]);
}
void to_lower(string &s) {
  for(int i=s.size(); i--;) s[i] = tolower(s[i]);
}

// 集合
template<class T>
set<T> intersection(const set<T>& sa, const set<T>& sb) {
  set<T> ret;
  for(T a : sa) if(sb.find(a) != sb.end()) ret.insert(a);
  return ret;
}

// 定数
#pragma region CONST_VAL
#define PI (2*acos(0.0))
#define EPS (1e-9)
#define MOD (int)(1e9+7)
#pragma endregion

int main() {
  return 0;
}
<commit_msg>template.cpp<commit_after>//#define _GRIBCXX_DEBUG
#include <algorithm>
#include <cctype>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <functional>
#include <iostream>
#include <iomanip>
#include <list>
#include <map>
#include <memory>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <utility>
#include <vector>
using namespace std;

// 基本テンプレート
#pragma region MACRO
#define P(x) cout << (x) << endl
#define p(x) cout << (x)
#define PED cout << "\n"
#define rep(i,n) for(int i=0; i<(int)n; ++i)
#define REP(i,x,n) for(int i=x; i<(int)n; ++i)
#define repi(i,n) for(int i=0; i<=(int)n; ++i)
#define REPI(i,x,n) for(int i=x; i<=(int)n; ++i)
#define ILP while(true)
#define FOR(i,c) for(__typeof((c).begin())!=(c).begin(); i!=(c).end(); ++i)
#define ALL(c) (c).begin(), (c).end()
#define mp make_pair
#pragma endregion

#pragma region TYPE_DEF
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<string, string> pss;
typedef pair<string, int> psi;
typedef pair<int, string> pis;
typedef vector<int> vi;
typedef vector<double> vd;
typedef vector<long> vl;
typedef vector<long long> vll;
typedef vector<string> vs;
#pragma endregion

// Effective std
#pragma region ESTD
template<typename C, typename T>
constexpr int count(C& c, T t) { return count(ALL(c), t); }
template<typename C, typename F>
constexpr int count_if(C& c, F f) { return count_if(ALL(c), f); }
template<typename C, typename T, typename U>
constexpr void replace(C& c, T t, U u) { replace(ALL(c), t, u); }
template<typename C, typename F, typename U>
constexpr void replace_if(C& c, F f, U u) { (ALL(c), f, u); }
template<typename C>
constexpr void sort(C& c) { sort(ALL(c)); }
template<typename C, typename Pred>
constexpr void sort(C& c, Pred p) { sort(ALL(c), p); }
template<typename C>
constexpr void reverse(C& c) { reverse(ALL(c)); }

#pragma endregion

// グラフテンプレート
#pragma region GRAPH

typedef int Weight;
struct Edge {
  int src, dst;
  Weight weight;
  Edge(int src, int dst, Weight weight) :
    src(src), dst(dst), weight(weight) {}
};

bool operator < (const Edge &e, const Edge &f) {
  return e.weight != f.weight ? e.weight > f.weight :
    e.src != f.src ? e.src < f.src : e.dst < f.dst;
}

typedef vector<Edge> Edges;
typedef vector<Edges> Graph;
typedef vector<Weight> Array;
typedef vector<Array> Matrix;

#pragma endregion

// 素数
#pragma region PRIME
bool is_prime(unsigned n) {
  switch(n) {
    case 0:
    case 1: return false;
    case 2: return true;
  }
  if (n%2==0) return false;
  for (unsigned i=3; i*i<=n; i+=2)
    if (n%i==0) return false;
  return true;
}
#pragma endregion

// 大文字/小文字変換
void mutal_tr(string &s) {
  for(int i=s.size(); i--;) {
    if(islower(s[i])) s[i] = toupper(s[i]);
    else if (isupper(s[i])) s[i] = tolower(s[i]);
  }
}
void to_upper(string &s) {
  for(int i=s.size(); i--;) s[i] = toupper(s[i]);
}
void to_lower(string &s) {
  for(int i=s.size(); i--;) s[i] = tolower(s[i]);
}

// 集合
template<class T>
set<T> intersection(const set<T>& sa, const set<T>& sb) {
  set<T> ret;
  for(T a : sa) if(sb.find(a) != sb.end()) ret.insert(a);
  return ret;
}

// 定数
#pragma region CONST_VAL
#define PI (2*acos(0.0))
#define EPS (1e-9)
#define MOD (int)(1e9+7)
#pragma endregion

int main() {
  return 0;
}
<|endoftext|>


<commit_before>#include "interpreterTest.h"

#include <src/interpreter/interpreter.h>

#include <src/textLanguage/robotsBlockParser.h>

using namespace qrTest::robotsTests::interpreterCoreTests;

using namespace interpreterCore::interpreter;
using namespace ::testing;

void InterpreterTest::SetUp()
{
	mQrguiFacade.reset(new QrguiFacade("./unittests/basicTest.qrs"));
	qDebug() << "loading" << QFileInfo("unittests/basicTest.qrs").absoluteFilePath();

	mQrguiFacade->setActiveTab(qReal::Id::loadFromString(
			"qrm:/RobotsMetamodel/RobotsDiagram/RobotsDiagramNode/{f08fa823-e187-4755-87ba-e4269ae4e798}"));

	mFakeConnectToRobotAction.reset(new QAction(nullptr));

	ON_CALL(mConfigurationInterfaceMock, devices()).WillByDefault(
			Return(QList<interpreterBase::robotModel::robotParts::Device *>())
			);
	EXPECT_CALL(mConfigurationInterfaceMock, devices()).Times(AtLeast(1));

	/// @todo: Do we need this code in some common place? Why do we need to write
	/// it every time when we are going to use RobotModelManager mock?

	ON_CALL(mModel, name()).WillByDefault(Return("mockRobot"));
	EXPECT_CALL(mModel, name()).Times(AtLeast(1));

	ON_CALL(mModel, needsConnection()).WillByDefault(Return(false));
	EXPECT_CALL(mModel, needsConnection()).Times(AtLeast(0));

	ON_CALL(mModel, init()).WillByDefault(Return());
	EXPECT_CALL(mModel, init()).Times(AtLeast(0));

	ON_CALL(mModel, configuration()).WillByDefault(ReturnRef(mConfigurationInterfaceMock));
	EXPECT_CALL(mModel, configuration()).Times(AtLeast(0));

	ON_CALL(mModel, connectToRobot()).WillByDefault(
			Invoke(&mModelManager, &RobotModelManagerInterfaceMock::emitConnected)
			);
	EXPECT_CALL(mModel, connectToRobot()).Times(AtLeast(0));

	ON_CALL(mModel, disconnectFromRobot()).WillByDefault(
			Invoke(&mModelManager, &RobotModelManagerInterfaceMock::emitDisconnected)
			);
	EXPECT_CALL(mModel, disconnectFromRobot()).Times(AtLeast(0));

	ON_CALL(mModel, configurablePorts()).WillByDefault(Return(QList<interpreterBase::robotModel::PortInfo>()));
	EXPECT_CALL(mModel, configurablePorts()).Times(AtLeast(0));

	ON_CALL(mModel, availablePorts()).WillByDefault(Return(QList<interpreterBase::robotModel::PortInfo>()));
	EXPECT_CALL(mModel, availablePorts()).Times(AtLeast(0));

	ON_CALL(mModel, applyConfiguration()).WillByDefault(
			Invoke(&mModelManager, &RobotModelManagerInterfaceMock::emitAllDevicesConfigured)
			);
	EXPECT_CALL(mModel, applyConfiguration()).Times(1);

	ON_CALL(mModel, connectionState()).WillByDefault(Return(RobotModelInterfaceMock::connectedState));
	EXPECT_CALL(mModel, connectionState()).Times(2);

	ON_CALL(mModel, timeline()).WillByDefault(ReturnRef(mTimeline));
	EXPECT_CALL(mModel, timeline()).Times(AtLeast(1));

	ON_CALL(mModelManager, model()).WillByDefault(ReturnRef(mModel));
	EXPECT_CALL(mModelManager, model()).Times(AtLeast(1));

	ON_CALL(mBlocksFactoryManager, addFactory(_, _)).WillByDefault(Return());
	EXPECT_CALL(mBlocksFactoryManager, addFactory(_, _)).Times(0);

	/// @todo Don't like it.
	interpreterCore::textLanguage::RobotsBlockParser parser(
			mQrguiFacade->mainWindowInterpretersInterface().errorReporter()
			, mModelManager
			, []() { return 0; }
			);

	DummyBlockFactory *blocksFactory = new DummyBlockFactory;
	blocksFactory->configure(
			mQrguiFacade->graphicalModelAssistInterface()
			, mQrguiFacade->logicalModelAssistInterface()
			, mModelManager
			, *mQrguiFacade->mainWindowInterpretersInterface().errorReporter()
			, &parser
			);

	ON_CALL(mBlocksFactoryManager, block(_, _)).WillByDefault(
			Invoke([=] (qReal::Id const &id, interpreterBase::robotModel::RobotModelInterface const &robotModel) {
					Q_UNUSED(robotModel)
					return blocksFactory->block(id);
			} )
			);
	EXPECT_CALL(mBlocksFactoryManager, block(_, _)).Times(AtLeast(0));

	ON_CALL(mBlocksFactoryManager, enabledBlocks(_)).WillByDefault(
			Invoke([=] (interpreterBase::robotModel::RobotModelInterface const &robotModel) {
					Q_UNUSED(robotModel)
					return blocksFactory->providedBlocks().toSet();
			} )
			);
	EXPECT_CALL(mBlocksFactoryManager, enabledBlocks(_)).Times(0);

	mInterpreter.reset(new Interpreter(
			mQrguiFacade->graphicalModelAssistInterface()
			, mQrguiFacade->logicalModelAssistInterface()
			, mQrguiFacade->mainWindowInterpretersInterface()
			, mQrguiFacade->projectManagementInterface()
			, mBlocksFactoryManager
			, mModelManager
			, parser
			, *mFakeConnectToRobotAction
			));
}

TEST_F(InterpreterTest, interpret)
{
	EXPECT_CALL(mModel, stopRobot()).Times(1);

	mInterpreter->interpret();
}

TEST_F(InterpreterTest, stopRobot)
{
	// It shall be called directly here and in destructor of a model.
	EXPECT_CALL(mModel, stopRobot()).Times(2);

	mInterpreter->interpret();
	mInterpreter->stopRobot();
}
<commit_msg>More build info requested<commit_after>#include "interpreterTest.h"

#include <src/interpreter/interpreter.h>

#include <src/textLanguage/robotsBlockParser.h>

using namespace qrTest::robotsTests::interpreterCoreTests;

using namespace interpreterCore::interpreter;
using namespace ::testing;

#include<QApplication>
void InterpreterTest::SetUp()
{
	qDebug() << "app" << QApplication::applicationFilePath();
	qDebug() << "loading" << QFileInfo("unittests/basicTest.qrs").absoluteFilePath();
	mQrguiFacade.reset(new QrguiFacade("/home/travis/qreal/qreal/bin/unittests/basicTest.qrs"));

	mQrguiFacade->setActiveTab(qReal::Id::loadFromString(
			"qrm:/RobotsMetamodel/RobotsDiagram/RobotsDiagramNode/{f08fa823-e187-4755-87ba-e4269ae4e798}"));

	mFakeConnectToRobotAction.reset(new QAction(nullptr));

	ON_CALL(mConfigurationInterfaceMock, devices()).WillByDefault(
			Return(QList<interpreterBase::robotModel::robotParts::Device *>())
			);
	EXPECT_CALL(mConfigurationInterfaceMock, devices()).Times(AtLeast(1));

	/// @todo: Do we need this code in some common place? Why do we need to write
	/// it every time when we are going to use RobotModelManager mock?

	ON_CALL(mModel, name()).WillByDefault(Return("mockRobot"));
	EXPECT_CALL(mModel, name()).Times(AtLeast(1));

	ON_CALL(mModel, needsConnection()).WillByDefault(Return(false));
	EXPECT_CALL(mModel, needsConnection()).Times(AtLeast(0));

	ON_CALL(mModel, init()).WillByDefault(Return());
	EXPECT_CALL(mModel, init()).Times(AtLeast(0));

	ON_CALL(mModel, configuration()).WillByDefault(ReturnRef(mConfigurationInterfaceMock));
	EXPECT_CALL(mModel, configuration()).Times(AtLeast(0));

	ON_CALL(mModel, connectToRobot()).WillByDefault(
			Invoke(&mModelManager, &RobotModelManagerInterfaceMock::emitConnected)
			);
	EXPECT_CALL(mModel, connectToRobot()).Times(AtLeast(0));

	ON_CALL(mModel, disconnectFromRobot()).WillByDefault(
			Invoke(&mModelManager, &RobotModelManagerInterfaceMock::emitDisconnected)
			);
	EXPECT_CALL(mModel, disconnectFromRobot()).Times(AtLeast(0));

	ON_CALL(mModel, configurablePorts()).WillByDefault(Return(QList<interpreterBase::robotModel::PortInfo>()));
	EXPECT_CALL(mModel, configurablePorts()).Times(AtLeast(0));

	ON_CALL(mModel, availablePorts()).WillByDefault(Return(QList<interpreterBase::robotModel::PortInfo>()));
	EXPECT_CALL(mModel, availablePorts()).Times(AtLeast(0));

	ON_CALL(mModel, applyConfiguration()).WillByDefault(
			Invoke(&mModelManager, &RobotModelManagerInterfaceMock::emitAllDevicesConfigured)
			);
	EXPECT_CALL(mModel, applyConfiguration()).Times(1);

	ON_CALL(mModel, connectionState()).WillByDefault(Return(RobotModelInterfaceMock::connectedState));
	EXPECT_CALL(mModel, connectionState()).Times(2);

	ON_CALL(mModel, timeline()).WillByDefault(ReturnRef(mTimeline));
	EXPECT_CALL(mModel, timeline()).Times(AtLeast(1));

	ON_CALL(mModelManager, model()).WillByDefault(ReturnRef(mModel));
	EXPECT_CALL(mModelManager, model()).Times(AtLeast(1));

	ON_CALL(mBlocksFactoryManager, addFactory(_, _)).WillByDefault(Return());
	EXPECT_CALL(mBlocksFactoryManager, addFactory(_, _)).Times(0);

	/// @todo Don't like it.
	interpreterCore::textLanguage::RobotsBlockParser parser(
			mQrguiFacade->mainWindowInterpretersInterface().errorReporter()
			, mModelManager
			, []() { return 0; }
			);

	DummyBlockFactory *blocksFactory = new DummyBlockFactory;
	blocksFactory->configure(
			mQrguiFacade->graphicalModelAssistInterface()
			, mQrguiFacade->logicalModelAssistInterface()
			, mModelManager
			, *mQrguiFacade->mainWindowInterpretersInterface().errorReporter()
			, &parser
			);

	ON_CALL(mBlocksFactoryManager, block(_, _)).WillByDefault(
			Invoke([=] (qReal::Id const &id, interpreterBase::robotModel::RobotModelInterface const &robotModel) {
					Q_UNUSED(robotModel)
					return blocksFactory->block(id);
			} )
			);
	EXPECT_CALL(mBlocksFactoryManager, block(_, _)).Times(AtLeast(0));

	ON_CALL(mBlocksFactoryManager, enabledBlocks(_)).WillByDefault(
			Invoke([=] (interpreterBase::robotModel::RobotModelInterface const &robotModel) {
					Q_UNUSED(robotModel)
					return blocksFactory->providedBlocks().toSet();
			} )
			);
	EXPECT_CALL(mBlocksFactoryManager, enabledBlocks(_)).Times(0);

	mInterpreter.reset(new Interpreter(
			mQrguiFacade->graphicalModelAssistInterface()
			, mQrguiFacade->logicalModelAssistInterface()
			, mQrguiFacade->mainWindowInterpretersInterface()
			, mQrguiFacade->projectManagementInterface()
			, mBlocksFactoryManager
			, mModelManager
			, parser
			, *mFakeConnectToRobotAction
			));
}

TEST_F(InterpreterTest, interpret)
{
	EXPECT_CALL(mModel, stopRobot()).Times(1);

	mInterpreter->interpret();
}

TEST_F(InterpreterTest, stopRobot)
{
	// It shall be called directly here and in destructor of a model.
	EXPECT_CALL(mModel, stopRobot()).Times(2);

	mInterpreter->interpret();
	mInterpreter->stopRobot();
}
<|endoftext|>


<commit_before>/**
 * @file
 * @brief Implementation of CorryvreckanWriter module
 * @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.
 * This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
 * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
 * Intergovernmental Organization or submit itself to any jurisdiction.
 */

#include "CorryvreckanWriterModule.hpp"

#include <string>
#include <utility>

#include "core/utils/log.h"

using namespace allpix;

CorryvreckanWriterModule::CorryvreckanWriterModule(Configuration config, Messenger* messenger, GeometryManager* geoManager)
    : Module(std::move(config)), messenger_(messenger), geometryManager_(geoManager) {
    // ... Implement ... (Typically bounds the required messages and optionally sets configuration defaults)
    LOG(TRACE) << "Initializing module " << getUniqueName();
    // Require PixelCharge messages for single detector
    messenger_->bindMulti(this, &CorryvreckanWriterModule::pixel_messages_, MsgFlags::REQUIRED);
}

// Set up the output trees
void CorryvreckanWriterModule::init() {

    LOG(TRACE) << "Initialising module " << getUniqueName();

    // Create output file and directories
    fileName_ = getOutputPath(config_.get<std::string>("file_name", "corryvreckanOutput") + ".root", true);
    outputFile_ = std::make_unique<TFile>(fileName_.c_str(), "RECREATE");
    outputFile_->cd();
    outputFile_->mkdir("pixels");

    // Loop over all detectors and make trees for data
    std::vector<std::shared_ptr<Detector>> detectors = geometryManager_->getDetectors();
    for(auto& detector : detectors) {

        // Get the detector ID and type
        std::string detectorID = detector->getName();

        // Create the tree
        std::string objectID = detectorID + "_pixels";
        std::string treeName = detectorID + "_Timepix3_pixels";
        outputTrees_[objectID] = new TTree(treeName.c_str(), treeName.c_str());
        outputTrees_[objectID]->Branch("time", &time_);

        // Map the pixel object to the tree
        treePixels_[objectID] = new corryvreckan::Pixel();
        outputTrees_[objectID]->Branch("pixels", &treePixels_[objectID]);
    }

    // Initialise the time
    time_ = 0;
}

// Make instantiations of Corryvreckan pixels, and store these in the trees during run time
void CorryvreckanWriterModule::run(unsigned int) {

    // Loop through all receieved messages
    for(auto& message : pixel_messages_) {

        std::string detectorID = message->getDetector()->getName();
        std::string objectID = detectorID + "_pixels";
        LOG(DEBUG) << "Receieved " << message->getData().size() << " pixel hits from detector " << detectorID;
        LOG(DEBUG) << "Time on event hits will be " << time_;

        // Loop through all pixels received
        for(auto& allpix_pixel : message->getData()) {

            // Make a new output pixel
            unsigned int pixelX = allpix_pixel.getPixel().getIndex().X();
            unsigned int pixelY = allpix_pixel.getPixel().getIndex().Y();
            double adc = allpix_pixel.getSignal();
            long long int time(time_);
            corryvreckan::Pixel* outputPixel = new corryvreckan::Pixel(detectorID, int(pixelY), int(pixelX), int(adc), time);

            LOG(DEBUG) << "Pixel (" << pixelX << "," << pixelY << ") written to device " << detectorID;

            // Map the pixel to the output tree and write it
            treePixels_[objectID] = outputPixel;
            outputTrees_[objectID]->Fill();
        }
    }

    // Increment the time till the next event
    time_ += 10;
}

// Save the output trees to file
// Set up the output trees
void CorryvreckanWriterModule::finalize() {

    // Loop over all detectors and store the trees
    std::vector<std::shared_ptr<Detector>> detectors = geometryManager_->getDetectors();
    for(auto& detector : detectors) {

        // Get the detector ID and type
        std::string detectorID = detector->getName();
        std::string objectID = detectorID + "_pixels";

        // Move to the write output file
        outputFile_->cd();
        outputFile_->cd("pixels");
        outputTrees_[objectID]->Write();

        // Clean up the tree and remove object pointer
        delete outputTrees_[objectID];
        treePixels_[objectID] = nullptr;
    }

    outputFile_->Close();
}
<commit_msg>CorryvreckanWriter: clean up code a bit<commit_after>/**
 * @file
 * @brief Implementation of CorryvreckanWriter module
 * @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.
 * This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
 * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
 * Intergovernmental Organization or submit itself to any jurisdiction.
 */

#include "CorryvreckanWriterModule.hpp"

#include <string>
#include <utility>

#include "core/utils/log.h"

using namespace allpix;

CorryvreckanWriterModule::CorryvreckanWriterModule(Configuration config, Messenger* messenger, GeometryManager* geoManager)
    : Module(std::move(config)), messenger_(messenger), geometryManager_(geoManager) {

    // Require PixelCharge messages for single detector
    messenger_->bindMulti(this, &CorryvreckanWriterModule::pixel_messages_, MsgFlags::REQUIRED);
}

// Set up the output trees
void CorryvreckanWriterModule::init() {

    // Create output file and directories
    fileName_ = getOutputPath(config_.get<std::string>("file_name", "corryvreckanOutput") + ".root", true);
    outputFile_ = std::make_unique<TFile>(fileName_.c_str(), "RECREATE");
    outputFile_->cd();
    outputFile_->mkdir("pixels");

    // Loop over all detectors and make trees for data
    auto detectors = geometryManager_->getDetectors();
    for(auto& detector : detectors) {

        // Get the detector ID and type
        std::string detectorID = detector->getName();

        // Create the tree
        std::string objectID = detectorID + "_pixels";
        std::string treeName = detectorID + "_Timepix3_pixels";
        outputTrees_[objectID] = new TTree(treeName.c_str(), treeName.c_str());
        outputTrees_[objectID]->Branch("time", &time_);

        // Map the pixel object to the tree
        treePixels_[objectID] = new corryvreckan::Pixel();
        outputTrees_[objectID]->Branch("pixels", &treePixels_[objectID]);
    }

    // Initialise the time
    time_ = 0;
}

// Make instantiations of Corryvreckan pixels, and store these in the trees during run time
void CorryvreckanWriterModule::run(unsigned int) {

    // Loop through all receieved messages
    for(auto& message : pixel_messages_) {

        auto detectorID = message->getDetector()->getName();
        auto objectID = detectorID + "_pixels";
        LOG(DEBUG) << "Receieved " << message->getData().size() << " pixel hits from detector " << detectorID;
        LOG(DEBUG) << "Time on event hits will be " << time_;

        // Loop through all pixels received
        for(auto& allpix_pixel : message->getData()) {

            // Make a new output pixel
            unsigned int pixelX = allpix_pixel.getPixel().getIndex().X();
            unsigned int pixelY = allpix_pixel.getPixel().getIndex().Y();
            double adc = allpix_pixel.getSignal();
            long long int time(time_);
            auto outputPixel = new corryvreckan::Pixel(detectorID, int(pixelY), int(pixelX), int(adc), time);

            LOG(DEBUG) << "Pixel (" << pixelX << "," << pixelY << ") written to device " << detectorID;

            // Map the pixel to the output tree and write it
            treePixels_[objectID] = outputPixel;
            outputTrees_[objectID]->Fill();
        }
    }

    // Increment the time till the next event
    time_ += 10;
}

// Save the output trees to file
void CorryvreckanWriterModule::finalize() {

    // Loop over all detectors and store the trees
    std::vector<std::shared_ptr<Detector>> detectors = geometryManager_->getDetectors();
    for(auto& detector : detectors) {

        // Get the detector ID and type
        std::string detectorID = detector->getName();
        std::string objectID = detectorID + "_pixels";

        // Move to the write output file
        outputFile_->cd();
        outputFile_->cd("pixels");
        outputTrees_[objectID]->Write();

        // Clean up the tree and remove object pointer
        delete outputTrees_[objectID];
        treePixels_[objectID] = nullptr;
    }
    // Print statistics
    LOG(STATUS) << "Wrote output data to file:" << std::endl << fileName_;

    outputFile_->Close();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: WinClipboard.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: tra $ $Date: 2001-07-24 07:53:23 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

#ifndef _WINCLIPBOARD_HXX_
#include "WinClipboard.hxx"
#endif

#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_CLIPBOARDEVENT_HPP_
#include <com/sun/star/datatransfer/clipboard/ClipboardEvent.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif

#ifndef _WINCLIPBIMPL_HXX_
#include "WinClipbImpl.hxx"
#endif

//------------------------------------------------------------------------
// namespace directives
//------------------------------------------------------------------------

using namespace rtl;
using namespace osl;
using namespace std;
using namespace cppu;

using namespace com::sun::star::uno;
using namespace com::sun::star::datatransfer;
using namespace com::sun::star::datatransfer::clipboard;
using namespace com::sun::star::lang;

//------------------------------------------------------------------------
// defines
//------------------------------------------------------------------------

#define WINCLIPBOARD_IMPL_NAME  "com.sun.star.datatransfer.clipboard.ClipboardW32"

//------------------------------------------------------------------------
// helper functions
//------------------------------------------------------------------------

namespace
{
    Sequence< OUString > SAL_CALL WinClipboard_getSupportedServiceNames()
    {
        Sequence< OUString > aRet(1);
        aRet[0] = OUString::createFromAscii("com.sun.star.datatransfer.clipboard.SystemClipboard");
        return aRet;
    }
}

//------------------------------------------------------------------------
// ctor
//------------------------------------------------------------------------
/*XEventListener,*/
CWinClipboard::CWinClipboard( const Reference< XMultiServiceFactory >& rServiceManager, const OUString& aClipboardName ) :
    WeakComponentImplHelper4< XClipboardEx, XFlushableClipboard, XClipboardNotifier, XServiceInfo >( m_aCbListenerMutex ),
    m_SrvMgr( rServiceManager )
{
    m_pImpl.reset( new CWinClipbImpl( aClipboardName, this ) );
}

//========================================================================
// XClipboard
//========================================================================

//------------------------------------------------------------------------
// getContent
// to avoid unecessary traffic we check first if there is a clipboard
// content which was set via setContent, in this case we don't need
// to query the content from the clipboard, create a new wrapper object
// and so on, we simply return the orignial XTransferable instead of our
// DOTransferable
//------------------------------------------------------------------------

Reference< XTransferable > SAL_CALL CWinClipboard::getContents( ) throw( RuntimeException )
{
    MutexGuard aGuard( m_aMutex );

    if ( rBHelper.bDisposed )
        throw DisposedException( OUString::createFromAscii( "object is already disposed" ),
                                 static_cast< XClipboardEx* >( this ) );

    if ( NULL != m_pImpl.get( ) )
        return m_pImpl->getContents( );

    return Reference< XTransferable >( );
}

//------------------------------------------------------------------------
// setContent
//------------------------------------------------------------------------

void SAL_CALL CWinClipboard::setContents( const Reference< XTransferable >& xTransferable,
                                          const Reference< XClipboardOwner >& xClipboardOwner )
                                          throw( RuntimeException )
{
    MutexGuard aGuard( m_aMutex );

    if ( rBHelper.bDisposed )
        throw DisposedException( OUString::createFromAscii( "object is already disposed" ),
                                 static_cast< XClipboardEx* >( this ) );

    if ( NULL != m_pImpl.get( ) )
        m_pImpl->setContents( xTransferable, xClipboardOwner );
}

//------------------------------------------------------------------------
// getName
//------------------------------------------------------------------------

OUString SAL_CALL CWinClipboard::getName(  ) throw( RuntimeException )
{
    if ( rBHelper.bDisposed )
        throw DisposedException( OUString::createFromAscii( "object is already disposed" ),
                                 static_cast< XClipboardEx* >( this ) );

    if ( NULL != m_pImpl.get( ) )
        return m_pImpl->getName( );

    return OUString::createFromAscii( "" );
}

//========================================================================
// XFlushableClipboard
//========================================================================

void SAL_CALL CWinClipboard::flushClipboard( ) throw( RuntimeException )
{
    MutexGuard aGuard( m_aMutex );

    if ( rBHelper.bDisposed )
        throw DisposedException( OUString::createFromAscii( "object is already disposed" ),
                                 static_cast< XClipboardEx* >( this ) );

    if ( NULL != m_pImpl.get( ) )
        m_pImpl->flushClipboard( );
}

//========================================================================
// XClipboardEx
//========================================================================

sal_Int8 SAL_CALL CWinClipboard::getRenderingCapabilities(  ) throw( RuntimeException )
{
    if ( rBHelper.bDisposed )
        throw DisposedException( OUString::createFromAscii( "object is already disposed" ),
                                 static_cast< XClipboardEx* >( this ) );

    if ( NULL != m_pImpl.get( ) )
        return m_pImpl->getRenderingCapabilities( );

    return 0;
}

//========================================================================
// XClipboardNotifier
//========================================================================

//------------------------------------------------------------------------
// getName
//------------------------------------------------------------------------

void SAL_CALL CWinClipboard::addClipboardListener( const Reference< XClipboardListener >& listener )
    throw( RuntimeException )
{
    if ( rBHelper.bDisposed )
        throw DisposedException( OUString::createFromAscii( "object is already disposed" ),
                                 static_cast< XClipboardEx* >( this ) );

    // check input parameter
    if ( !listener.is( ) )
        throw IllegalArgumentException( OUString::createFromAscii( "empty reference" ),
                                        static_cast< XClipboardEx* >( this ),
                                        1 );

    rBHelper.aLC.addInterface( getCppuType( &listener ), listener );
}

//------------------------------------------------------------------------
// getName
//------------------------------------------------------------------------

void SAL_CALL CWinClipboard::removeClipboardListener( const Reference< XClipboardListener >& listener )
    throw( RuntimeException )
{
    if ( rBHelper.bDisposed )
        throw DisposedException( OUString::createFromAscii( "object is already disposed" ),
                                 static_cast< XClipboardEx* >( this ) );

    // check input parameter
    if ( !listener.is( ) )
        throw IllegalArgumentException( OUString::createFromAscii( "empty reference" ),
                                        static_cast< XClipboardEx* >( this ),
                                        1 );

    rBHelper.aLC.removeInterface( getCppuType( &listener ), listener );
}

//------------------------------------------------------------------------
// getName
//------------------------------------------------------------------------

void SAL_CALL CWinClipboard::notifyAllClipboardListener( )
{
    if ( !rBHelper.bDisposed )
    {
        ClearableMutexGuard aGuard( rBHelper.rMutex );
        if ( !rBHelper.bDisposed )
        {
            aGuard.clear( );

            OInterfaceContainerHelper* pICHelper = rBHelper.aLC.getContainer(
                getCppuType( ( Reference< XClipboardListener > * ) 0 ) );

            if ( pICHelper )
            {
                OInterfaceIteratorHelper iter( *pICHelper );
                Reference< XTransferable > rXTransf = m_pImpl->getContents( );
                ClipboardEvent aClipbEvent( static_cast< XClipboard* >( this ), rXTransf );

                while( iter.hasMoreElements( ) )
                {
                    try
                    {
                        Reference< XClipboardListener > xCBListener( iter.next( ), UNO_QUERY );
                        if ( xCBListener.is( ) )
                            xCBListener->changedContents( aClipbEvent );
                    }
                    catch( RuntimeException& )
                    {
                        OSL_ENSURE( false, "RuntimeException caught" );
                    }
                    catch( ... )
                    {
                        OSL_ENSURE( false, "Exception during event dispatching" );
                    }
                } // while
            } // end if
        } // end if
    } // end if
}

//------------------------------------------------
// overwritten base class method which will be
// called by the base class dispose method
//------------------------------------------------

void SAL_CALL CWinClipboard::disposing()
{
    // do my own stuff
    m_pImpl->dispose( );

    // force destruction of the impl class
    m_pImpl.reset( NULL );
}

// -------------------------------------------------
// XServiceInfo
// -------------------------------------------------

OUString SAL_CALL CWinClipboard::getImplementationName(  )
    throw(RuntimeException)
{
    return OUString::createFromAscii( WINCLIPBOARD_IMPL_NAME );
}

// -------------------------------------------------
//  XServiceInfo
// -------------------------------------------------

sal_Bool SAL_CALL CWinClipboard::supportsService( const OUString& ServiceName )
    throw(RuntimeException)
{
    Sequence < OUString > SupportedServicesNames = WinClipboard_getSupportedServiceNames();

    for ( sal_Int32 n = SupportedServicesNames.getLength(); n--; )
        if (SupportedServicesNames[n].compareTo(ServiceName) == 0)
            return sal_True;

    return sal_False;
}

// -------------------------------------------------
//  XServiceInfo
// -------------------------------------------------

Sequence< OUString > SAL_CALL CWinClipboard::getSupportedServiceNames(   )
    throw(RuntimeException)
{
    return WinClipboard_getSupportedServiceNames();
}<commit_msg>INTEGRATION: CWS rt02 (1.10.94); FILE MERGED 2003/10/01 12:06:04 rt 1.10.94.1: #i19697# No newline at end of file<commit_after>/*************************************************************************
 *
 *  $RCSfile: WinClipboard.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: rt $ $Date: 2003-10-06 14:37:52 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

#ifndef _WINCLIPBOARD_HXX_
#include "WinClipboard.hxx"
#endif

#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_CLIPBOARDEVENT_HPP_
#include <com/sun/star/datatransfer/clipboard/ClipboardEvent.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif

#ifndef _WINCLIPBIMPL_HXX_
#include "WinClipbImpl.hxx"
#endif

//------------------------------------------------------------------------
// namespace directives
//------------------------------------------------------------------------

using namespace rtl;
using namespace osl;
using namespace std;
using namespace cppu;

using namespace com::sun::star::uno;
using namespace com::sun::star::datatransfer;
using namespace com::sun::star::datatransfer::clipboard;
using namespace com::sun::star::lang;

//------------------------------------------------------------------------
// defines
//------------------------------------------------------------------------

#define WINCLIPBOARD_IMPL_NAME  "com.sun.star.datatransfer.clipboard.ClipboardW32"

//------------------------------------------------------------------------
// helper functions
//------------------------------------------------------------------------

namespace
{
    Sequence< OUString > SAL_CALL WinClipboard_getSupportedServiceNames()
    {
        Sequence< OUString > aRet(1);
        aRet[0] = OUString::createFromAscii("com.sun.star.datatransfer.clipboard.SystemClipboard");
        return aRet;
    }
}

//------------------------------------------------------------------------
// ctor
//------------------------------------------------------------------------
/*XEventListener,*/
CWinClipboard::CWinClipboard( const Reference< XMultiServiceFactory >& rServiceManager, const OUString& aClipboardName ) :
    WeakComponentImplHelper4< XClipboardEx, XFlushableClipboard, XClipboardNotifier, XServiceInfo >( m_aCbListenerMutex ),
    m_SrvMgr( rServiceManager )
{
    m_pImpl.reset( new CWinClipbImpl( aClipboardName, this ) );
}

//========================================================================
// XClipboard
//========================================================================

//------------------------------------------------------------------------
// getContent
// to avoid unecessary traffic we check first if there is a clipboard
// content which was set via setContent, in this case we don't need
// to query the content from the clipboard, create a new wrapper object
// and so on, we simply return the orignial XTransferable instead of our
// DOTransferable
//------------------------------------------------------------------------

Reference< XTransferable > SAL_CALL CWinClipboard::getContents( ) throw( RuntimeException )
{
    MutexGuard aGuard( m_aMutex );

    if ( rBHelper.bDisposed )
        throw DisposedException( OUString::createFromAscii( "object is already disposed" ),
                                 static_cast< XClipboardEx* >( this ) );

    if ( NULL != m_pImpl.get( ) )
        return m_pImpl->getContents( );

    return Reference< XTransferable >( );
}

//------------------------------------------------------------------------
// setContent
//------------------------------------------------------------------------

void SAL_CALL CWinClipboard::setContents( const Reference< XTransferable >& xTransferable,
                                          const Reference< XClipboardOwner >& xClipboardOwner )
                                          throw( RuntimeException )
{
    MutexGuard aGuard( m_aMutex );

    if ( rBHelper.bDisposed )
        throw DisposedException( OUString::createFromAscii( "object is already disposed" ),
                                 static_cast< XClipboardEx* >( this ) );

    if ( NULL != m_pImpl.get( ) )
        m_pImpl->setContents( xTransferable, xClipboardOwner );
}

//------------------------------------------------------------------------
// getName
//------------------------------------------------------------------------

OUString SAL_CALL CWinClipboard::getName(  ) throw( RuntimeException )
{
    if ( rBHelper.bDisposed )
        throw DisposedException( OUString::createFromAscii( "object is already disposed" ),
                                 static_cast< XClipboardEx* >( this ) );

    if ( NULL != m_pImpl.get( ) )
        return m_pImpl->getName( );

    return OUString::createFromAscii( "" );
}

//========================================================================
// XFlushableClipboard
//========================================================================

void SAL_CALL CWinClipboard::flushClipboard( ) throw( RuntimeException )
{
    MutexGuard aGuard( m_aMutex );

    if ( rBHelper.bDisposed )
        throw DisposedException( OUString::createFromAscii( "object is already disposed" ),
                                 static_cast< XClipboardEx* >( this ) );

    if ( NULL != m_pImpl.get( ) )
        m_pImpl->flushClipboard( );
}

//========================================================================
// XClipboardEx
//========================================================================

sal_Int8 SAL_CALL CWinClipboard::getRenderingCapabilities(  ) throw( RuntimeException )
{
    if ( rBHelper.bDisposed )
        throw DisposedException( OUString::createFromAscii( "object is already disposed" ),
                                 static_cast< XClipboardEx* >( this ) );

    if ( NULL != m_pImpl.get( ) )
        return m_pImpl->getRenderingCapabilities( );

    return 0;
}

//========================================================================
// XClipboardNotifier
//========================================================================

//------------------------------------------------------------------------
// getName
//------------------------------------------------------------------------

void SAL_CALL CWinClipboard::addClipboardListener( const Reference< XClipboardListener >& listener )
    throw( RuntimeException )
{
    if ( rBHelper.bDisposed )
        throw DisposedException( OUString::createFromAscii( "object is already disposed" ),
                                 static_cast< XClipboardEx* >( this ) );

    // check input parameter
    if ( !listener.is( ) )
        throw IllegalArgumentException( OUString::createFromAscii( "empty reference" ),
                                        static_cast< XClipboardEx* >( this ),
                                        1 );

    rBHelper.aLC.addInterface( getCppuType( &listener ), listener );
}

//------------------------------------------------------------------------
// getName
//------------------------------------------------------------------------

void SAL_CALL CWinClipboard::removeClipboardListener( const Reference< XClipboardListener >& listener )
    throw( RuntimeException )
{
    if ( rBHelper.bDisposed )
        throw DisposedException( OUString::createFromAscii( "object is already disposed" ),
                                 static_cast< XClipboardEx* >( this ) );

    // check input parameter
    if ( !listener.is( ) )
        throw IllegalArgumentException( OUString::createFromAscii( "empty reference" ),
                                        static_cast< XClipboardEx* >( this ),
                                        1 );

    rBHelper.aLC.removeInterface( getCppuType( &listener ), listener );
}

//------------------------------------------------------------------------
// getName
//------------------------------------------------------------------------

void SAL_CALL CWinClipboard::notifyAllClipboardListener( )
{
    if ( !rBHelper.bDisposed )
    {
        ClearableMutexGuard aGuard( rBHelper.rMutex );
        if ( !rBHelper.bDisposed )
        {
            aGuard.clear( );

            OInterfaceContainerHelper* pICHelper = rBHelper.aLC.getContainer(
                getCppuType( ( Reference< XClipboardListener > * ) 0 ) );

            if ( pICHelper )
            {
                OInterfaceIteratorHelper iter( *pICHelper );
                Reference< XTransferable > rXTransf = m_pImpl->getContents( );
                ClipboardEvent aClipbEvent( static_cast< XClipboard* >( this ), rXTransf );

                while( iter.hasMoreElements( ) )
                {
                    try
                    {
                        Reference< XClipboardListener > xCBListener( iter.next( ), UNO_QUERY );
                        if ( xCBListener.is( ) )
                            xCBListener->changedContents( aClipbEvent );
                    }
                    catch( RuntimeException& )
                    {
                        OSL_ENSURE( false, "RuntimeException caught" );
                    }
                    catch( ... )
                    {
                        OSL_ENSURE( false, "Exception during event dispatching" );
                    }
                } // while
            } // end if
        } // end if
    } // end if
}

//------------------------------------------------
// overwritten base class method which will be
// called by the base class dispose method
//------------------------------------------------

void SAL_CALL CWinClipboard::disposing()
{
    // do my own stuff
    m_pImpl->dispose( );

    // force destruction of the impl class
    m_pImpl.reset( NULL );
}

// -------------------------------------------------
// XServiceInfo
// -------------------------------------------------

OUString SAL_CALL CWinClipboard::getImplementationName(  )
    throw(RuntimeException)
{
    return OUString::createFromAscii( WINCLIPBOARD_IMPL_NAME );
}

// -------------------------------------------------
//  XServiceInfo
// -------------------------------------------------

sal_Bool SAL_CALL CWinClipboard::supportsService( const OUString& ServiceName )
    throw(RuntimeException)
{
    Sequence < OUString > SupportedServicesNames = WinClipboard_getSupportedServiceNames();

    for ( sal_Int32 n = SupportedServicesNames.getLength(); n--; )
        if (SupportedServicesNames[n].compareTo(ServiceName) == 0)
            return sal_True;

    return sal_False;
}

// -------------------------------------------------
//  XServiceInfo
// -------------------------------------------------

Sequence< OUString > SAL_CALL CWinClipboard::getSupportedServiceNames(   )
    throw(RuntimeException)
{
    return WinClipboard_getSupportedServiceNames();
}
<|endoftext|>