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

#include "maemoglobal.h"

#include <utils/ssh/sshconnection.h>
#include <utils/ssh/sshremoteprocessrunner.h>

using namespace Utils;

namespace Qt4ProjectManager {
namespace Internal {

AbstractMaemoPackageInstaller::AbstractMaemoPackageInstaller(QObject *parent)
    : QObject(parent), m_isRunning(false)
{
}

AbstractMaemoPackageInstaller::~AbstractMaemoPackageInstaller() {}

void AbstractMaemoPackageInstaller::installPackage(const SshConnection::Ptr &connection,
    const QString &packageFilePath, bool removePackageFile)
{
    Q_ASSERT(connection && connection->state() == SshConnection::Connected);
    Q_ASSERT(!m_isRunning);

    prepareInstallation();
    m_installer = SshRemoteProcessRunner::create(connection);
    connect(m_installer.data(), SIGNAL(connectionError(Utils::SshError)),
        SLOT(handleConnectionError()));
    connect(m_installer.data(), SIGNAL(processOutputAvailable(QByteArray)),
        SLOT(handleInstallerOutput(QByteArray)));
    connect(m_installer.data(), SIGNAL(processErrorOutputAvailable(QByteArray)),
        SLOT(handleInstallerErrorOutput(QByteArray)));
    connect(m_installer.data(), SIGNAL(processClosed(int)),
        SLOT(handleInstallationFinished(int)));

    const QString space = QLatin1String(" ");
    QString cmdLine = MaemoGlobal::remoteSudo() + space + installCommand()
        + space + installCommandArguments().join(space) + space
        + packageFilePath;
    if (removePackageFile) {
        cmdLine += QLatin1String(" && (rm ") + packageFilePath
            + QLatin1String(" || :)");
    }
    m_installer->run(cmdLine.toUtf8());
    m_isRunning = true;
}

void AbstractMaemoPackageInstaller::cancelInstallation()
{
    Q_ASSERT(m_isRunning);
    const SshRemoteProcessRunner::Ptr killProcess
        = SshRemoteProcessRunner::create(m_installer->connection());
    killProcess->run("pkill " + installCommand().toUtf8());
    setFinished();
}

void AbstractMaemoPackageInstaller::handleConnectionError()
{
    if (!m_isRunning)
        return;
    emit finished(tr("Connection failure: %1")
        .arg(m_installer->connection()->errorString()));
    setFinished();
}

void AbstractMaemoPackageInstaller::handleInstallationFinished(int exitStatus)
{
    if (!m_isRunning)
        return;

    if (exitStatus != SshRemoteProcess::ExitedNormally
            || m_installer->process()->exitCode() != 0) {
        emit finished(tr("Installing package failed."));
    } else if (!errorString().isEmpty()) {
        emit finished(errorString());
    } else {
        emit finished();
    }

    setFinished();
}

void AbstractMaemoPackageInstaller::handleInstallerOutput(const QByteArray &output)
{
    emit stdoutData(QString::fromUtf8(output));
}

void AbstractMaemoPackageInstaller::handleInstallerErrorOutput(const QByteArray &output)
{
    emit stderrData(QString::fromUtf8(output));
}

void AbstractMaemoPackageInstaller::setFinished()
{
    disconnect(m_installer.data(), 0, this, 0);
    m_installer.clear();
    m_isRunning = false;
}

MaemoDebianPackageInstaller::MaemoDebianPackageInstaller(QObject *parent)
    : AbstractMaemoPackageInstaller(parent)
{
    connect(this, SIGNAL(stderrData(QString)),
        SLOT(handleInstallerErrorOutput(QString)));
}

void MaemoDebianPackageInstaller::prepareInstallation()
{
    m_installerStderr.clear();
}

QString MaemoDebianPackageInstaller::installCommand() const
{
    return QLatin1String("dpkg");
}

QStringList MaemoDebianPackageInstaller::installCommandArguments() const
{
    return QStringList() << QLatin1String("-i")
        << QLatin1String("--no-force-downgrade");
}

void MaemoDebianPackageInstaller::handleInstallerErrorOutput(const QString &output)
{
    m_installerStderr += output;
}

QString MaemoDebianPackageInstaller::errorString() const
{
    if (m_installerStderr.contains(QLatin1String("Will not downgrade"))) {
        return tr("Installation failed: "
            "You tried to downgrade a package, which is not allowed.");
    } else {
        return QString();
    }
}

MaemoRpmPackageInstaller::MaemoRpmPackageInstaller(QObject *parent)
    : AbstractMaemoPackageInstaller(parent)
{
}

QString MaemoRpmPackageInstaller::installCommand() const
{
    return QLatin1String("rpm");
}

QStringList MaemoRpmPackageInstaller::installCommandArguments() const
{
    return QStringList() << QLatin1String("-Uhv");
}

MaemoTarPackageInstaller::MaemoTarPackageInstaller(QObject *parent)
    : AbstractMaemoPackageInstaller(parent)
{
}

QString MaemoTarPackageInstaller::installCommand() const
{
    return QLatin1String("tar");
}

QStringList MaemoTarPackageInstaller::installCommandArguments() const
{
    return QStringList() << QLatin1String("xvf");
}

} // namespace Internal
} // namespace Qt4ProjectManager
<commit_msg>Meego: Allow re-installation of package with equal version number.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "maemopackageinstaller.h"

#include "maemoglobal.h"

#include <utils/ssh/sshconnection.h>
#include <utils/ssh/sshremoteprocessrunner.h>

using namespace Utils;

namespace Qt4ProjectManager {
namespace Internal {

AbstractMaemoPackageInstaller::AbstractMaemoPackageInstaller(QObject *parent)
    : QObject(parent), m_isRunning(false)
{
}

AbstractMaemoPackageInstaller::~AbstractMaemoPackageInstaller() {}

void AbstractMaemoPackageInstaller::installPackage(const SshConnection::Ptr &connection,
    const QString &packageFilePath, bool removePackageFile)
{
    Q_ASSERT(connection && connection->state() == SshConnection::Connected);
    Q_ASSERT(!m_isRunning);

    prepareInstallation();
    m_installer = SshRemoteProcessRunner::create(connection);
    connect(m_installer.data(), SIGNAL(connectionError(Utils::SshError)),
        SLOT(handleConnectionError()));
    connect(m_installer.data(), SIGNAL(processOutputAvailable(QByteArray)),
        SLOT(handleInstallerOutput(QByteArray)));
    connect(m_installer.data(), SIGNAL(processErrorOutputAvailable(QByteArray)),
        SLOT(handleInstallerErrorOutput(QByteArray)));
    connect(m_installer.data(), SIGNAL(processClosed(int)),
        SLOT(handleInstallationFinished(int)));

    const QString space = QLatin1String(" ");
    QString cmdLine = MaemoGlobal::remoteSudo() + space + installCommand()
        + space + installCommandArguments().join(space) + space
        + packageFilePath;
    if (removePackageFile) {
        cmdLine += QLatin1String(" && (rm ") + packageFilePath
            + QLatin1String(" || :)");
    }
    m_installer->run(cmdLine.toUtf8());
    m_isRunning = true;
}

void AbstractMaemoPackageInstaller::cancelInstallation()
{
    Q_ASSERT(m_isRunning);
    const SshRemoteProcessRunner::Ptr killProcess
        = SshRemoteProcessRunner::create(m_installer->connection());
    killProcess->run("pkill " + installCommand().toUtf8());
    setFinished();
}

void AbstractMaemoPackageInstaller::handleConnectionError()
{
    if (!m_isRunning)
        return;
    emit finished(tr("Connection failure: %1")
        .arg(m_installer->connection()->errorString()));
    setFinished();
}

void AbstractMaemoPackageInstaller::handleInstallationFinished(int exitStatus)
{
    if (!m_isRunning)
        return;

    if (exitStatus != SshRemoteProcess::ExitedNormally
            || m_installer->process()->exitCode() != 0) {
        emit finished(tr("Installing package failed."));
    } else if (!errorString().isEmpty()) {
        emit finished(errorString());
    } else {
        emit finished();
    }

    setFinished();
}

void AbstractMaemoPackageInstaller::handleInstallerOutput(const QByteArray &output)
{
    emit stdoutData(QString::fromUtf8(output));
}

void AbstractMaemoPackageInstaller::handleInstallerErrorOutput(const QByteArray &output)
{
    emit stderrData(QString::fromUtf8(output));
}

void AbstractMaemoPackageInstaller::setFinished()
{
    disconnect(m_installer.data(), 0, this, 0);
    m_installer.clear();
    m_isRunning = false;
}

MaemoDebianPackageInstaller::MaemoDebianPackageInstaller(QObject *parent)
    : AbstractMaemoPackageInstaller(parent)
{
    connect(this, SIGNAL(stderrData(QString)),
        SLOT(handleInstallerErrorOutput(QString)));
}

void MaemoDebianPackageInstaller::prepareInstallation()
{
    m_installerStderr.clear();
}

QString MaemoDebianPackageInstaller::installCommand() const
{
    return QLatin1String("dpkg");
}

QStringList MaemoDebianPackageInstaller::installCommandArguments() const
{
    return QStringList() << QLatin1String("-i")
        << QLatin1String("--no-force-downgrade");
}

void MaemoDebianPackageInstaller::handleInstallerErrorOutput(const QString &output)
{
    m_installerStderr += output;
}

QString MaemoDebianPackageInstaller::errorString() const
{
    if (m_installerStderr.contains(QLatin1String("Will not downgrade"))) {
        return tr("Installation failed: "
            "You tried to downgrade a package, which is not allowed.");
    } else {
        return QString();
    }
}

MaemoRpmPackageInstaller::MaemoRpmPackageInstaller(QObject *parent)
    : AbstractMaemoPackageInstaller(parent)
{
}

QString MaemoRpmPackageInstaller::installCommand() const
{
    return QLatin1String("rpm");
}

QStringList MaemoRpmPackageInstaller::installCommandArguments() const
{
    // --replacepkgs to re-install package, even if the same version is already installed
    return QStringList() << QLatin1String("-Uhv") << QLatin1String("--replacepkgs");
}

MaemoTarPackageInstaller::MaemoTarPackageInstaller(QObject *parent)
    : AbstractMaemoPackageInstaller(parent)
{
}

QString MaemoTarPackageInstaller::installCommand() const
{
    return QLatin1String("tar");
}

QStringList MaemoTarPackageInstaller::installCommandArguments() const
{
    return QStringList() << QLatin1String("xvf");
}

} // namespace Internal
} // namespace Qt4ProjectManager
<|endoftext|>


<commit_before>#include <Kunlaboro/Component.inl>
#include <Kunlaboro/Entity.inl>
#include <Kunlaboro/EntitySystem.inl>
#include <Kunlaboro/Views.inl>

#include "catch.hpp"

#include <atomic>
#include <random>

struct NumberComponent : public Kunlaboro::Component
{
	NumberComponent(int i)
		: Number(i)
	{ }

	int Number;
};

struct NameComponent : public Kunlaboro::Component
{
	NameComponent(const std::string& name)
		: Name(name)
	{ }

	std::string Name;
};

TEST_CASE("fizzbuzz", "[entity][view]")
{
	Kunlaboro::EntitySystem es;

	for (int i = 1; i <= 15; ++i)
	{
		auto ent = es.entityCreate();

		if (i % 3 == 0 && i % 5 == 0)
			ent.addComponent<NameComponent>("fizzbuzz");
		else if (i % 3 == 0)
			ent.addComponent<NameComponent>("fizz");
		else if (i % 5 == 0)
			ent.addComponent<NameComponent>("buzz");
		ent.addComponent<NumberComponent>(i);
	}

	SECTION("Range-based for")
	{
		std::string result;

		auto view = Kunlaboro::EntityView(es);
		for (auto& ent : view)
		{
			if (ent.hasComponent<NameComponent>())
				result += ent.getComponent<NameComponent>()->Name + " ";
			else if (ent.hasComponent<NumberComponent>())
				result += std::to_string(ent.getComponent<NumberComponent>()->Number) + " ";
		}

		REQUIRE(result == "1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz ");
	}

	SECTION("forEach - match any")
	{
		std::string result;

		auto view = Kunlaboro::EntityView(es).withComponents<Kunlaboro::Match_Any, NumberComponent, NameComponent>();
		view.forEach([&result](Kunlaboro::Entity&, NumberComponent* number, NameComponent* name) {
			if (name)
				result += name->Name + " ";
			else
				result += std::to_string(number->Number) + " ";
		});

		REQUIRE(result == "1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz ");
	}

	SECTION("forEach - match all")
	{
		std::string result;

		auto view = Kunlaboro::EntityView(es).withComponents<Kunlaboro::Match_All, NumberComponent, NameComponent>();
		view.forEach([&result](Kunlaboro::Entity&, NumberComponent& number, NameComponent& name) {
			result += std::to_string(number.Number);
			result += name.Name + " ";
		});

		REQUIRE(result == "3fizz 5buzz 6fizz 9fizz 10buzz 12fizz 15fizzbuzz ");
	}
}

struct Position : public Kunlaboro::Component
{
	Position(float x, float y)
		: X(x)
		, Y(y)
	{ }

	volatile float X, Y;
};
struct Velocity : public Kunlaboro::Component
{
	Velocity(float x, float y)
		: X(x)
		, Y(y)
	{ }

	volatile float X, Y;
};

TEST_CASE("Simple n-body simulation", "[performance][view]")
{
	Kunlaboro::EntitySystem es;

	SECTION("Creation, 100 particles")
	{
		const int ParticleCount = 100;

		std::random_device rand;
		std::uniform_real_distribution<float> ang(0, 3.14159f * 2);
		std::uniform_real_distribution<float> mag(0, 100);

		for (int i = 0; i < ParticleCount; ++i)
		{
			auto ent = es.entityCreate();
			float angle = ang(rand);
			float magnitude = mag(rand);

			ent.addComponent<Position>(std::cos(angle) * magnitude, std::sin(angle) * magnitude);
			ent.addComponent<Velocity>((mag(rand) - 50) / 5, (mag(rand) - 50) / 5);
		}

		REQUIRE(es.componentGetPool(Kunlaboro::ComponentFamily<Position>::getFamily()).countBits() == ParticleCount);
		REQUIRE(es.componentGetPool(Kunlaboro::ComponentFamily<Velocity>::getFamily()).countBits() == ParticleCount);

		SECTION("Iteration, 100 steps, 100 000 calls per step")
		{
			const int IterationCount = 100;

			std::atomic<uint32_t> gravityIterations(0)
			                    , velocityIterations(0);

			auto entityView = Kunlaboro::EntityView(es).withComponents<Kunlaboro::Match_All, Position,Velocity>();
			auto particleList = Kunlaboro::EntityView(es).withComponents<Kunlaboro::Match_All, Position>();

			for (int step = 0; step < IterationCount; ++step)
			{
				entityView.forEach([&gravityIterations, &velocityIterations, &particleList](Kunlaboro::Entity& ent, Position& pos, Velocity& vel) {
					particleList.forEach([&gravityIterations, &ent, &pos, &vel](Kunlaboro::Entity& ent2, Position& pos2) {
						if (ent == ent2)
							return;

						const float xDelta = (pos2.X - pos.X);
						const float yDelta = (pos2.Y - pos.Y);
						const float deltaSqrt = std::sqrt(xDelta*xDelta + yDelta*yDelta + 1e-9f);
						const float invDist = 1 / deltaSqrt;
						const float invDist2 = invDist * invDist;

						vel.X += xDelta * invDist2;
						vel.Y += yDelta * invDist2;

						gravityIterations.fetch_add(1);
					});

					pos.X += vel.X;
					pos.Y += vel.Y;

					velocityIterations.fetch_add(1);
				});
			}

			REQUIRE(gravityIterations  == ParticleCount * (ParticleCount - 1) * IterationCount);
			REQUIRE(velocityIterations == ParticleCount * IterationCount);
		}

		SECTION("Parallel gravity iteration, 100 steps, 100 000 calls per step")
		{
			const int IterationCount = 100;

			std::atomic<uint32_t> gravityIterations(0)
			                    , velocityIterations(0);

			Kunlaboro::detail::JobQueue queue;
			auto entityView = Kunlaboro::EntityView(es).withComponents<Kunlaboro::Match_All, Position,Velocity>();
			auto particleList = Kunlaboro::EntityView(es).withComponents<Kunlaboro::Match_All, Position>().parallel(queue);

			for (int step = 0; step < IterationCount; ++step)
			{
				entityView.forEach([&gravityIterations, &velocityIterations, &particleList](Kunlaboro::Entity& ent, Position& pos, Velocity& vel) {
					particleList.forEach([&gravityIterations, &ent, &pos, &vel](Kunlaboro::Entity& ent2, Position& pos2) {
						if (ent == ent2)
							return;

						const float xDelta = (pos2.X - pos.X);
						const float yDelta = (pos2.Y - pos.Y);
						const float deltaSqrt = std::sqrt(xDelta*xDelta + yDelta*yDelta + 1e-9f);
						const float invDist = 1 / deltaSqrt;
						const float invDist2 = invDist * invDist;

						vel.X += xDelta * invDist2;
						vel.Y += yDelta * invDist2;

						gravityIterations.fetch_add(1, std::memory_order_relaxed);
					});

					pos.X += vel.X;
					pos.Y += vel.Y;

					velocityIterations.fetch_add(1, std::memory_order_relaxed);
				});
			}

			REQUIRE(gravityIterations  == ParticleCount * (ParticleCount - 1) * IterationCount);
			REQUIRE(velocityIterations == ParticleCount * IterationCount);
		}

	}
}
<commit_msg>Better result reporting on AppVeyor<commit_after>#include <Kunlaboro/Component.inl>
#include <Kunlaboro/Entity.inl>
#include <Kunlaboro/EntitySystem.inl>
#include <Kunlaboro/Views.inl>

#include "catch.hpp"

#include <atomic>
#include <random>

struct NumberComponent : public Kunlaboro::Component
{
	NumberComponent(int i)
		: Number(i)
	{ }

	int Number;
};

struct NameComponent : public Kunlaboro::Component
{
	NameComponent(const std::string& name)
		: Name(name)
	{ }

	std::string Name;
};

TEST_CASE("fizzbuzz", "[comprehensive][entity][view]")
{
	Kunlaboro::EntitySystem es;

	for (int i = 1; i <= 15; ++i)
	{
		auto ent = es.entityCreate();

		if (i % 3 == 0 && i % 5 == 0)
			ent.addComponent<NameComponent>("fizzbuzz");
		else if (i % 3 == 0)
			ent.addComponent<NameComponent>("fizz");
		else if (i % 5 == 0)
			ent.addComponent<NameComponent>("buzz");
		ent.addComponent<NumberComponent>(i);
	}

	SECTION("Range-based for")
	{
		std::string result;

		auto view = Kunlaboro::EntityView(es);
		for (auto& ent : view)
		{
			if (ent.hasComponent<NameComponent>())
				result += ent.getComponent<NameComponent>()->Name + " ";
			else if (ent.hasComponent<NumberComponent>())
				result += std::to_string(ent.getComponent<NumberComponent>()->Number) + " ";
		}

		REQUIRE(result == "1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz ");
	}

	SECTION("forEach - match any")
	{
		std::string result;

		auto view = Kunlaboro::EntityView(es).withComponents<Kunlaboro::Match_Any, NumberComponent, NameComponent>();
		view.forEach([&result](Kunlaboro::Entity&, NumberComponent* number, NameComponent* name) {
			if (name)
				result += name->Name + " ";
			if (number)
				result += std::to_string(number->Number) + " ";
		});

		REQUIRE(result == "1 2 fizz 3 4 buzz 5 fizz 6 7 8 fizz 9 buzz 10 11 fizz 12 13 14 fizzbuzz 15 ");
	}

	SECTION("forEach - match all")
	{
		std::string result;

		auto view = Kunlaboro::EntityView(es).withComponents<Kunlaboro::Match_All, NumberComponent, NameComponent>();
		view.forEach([&result](Kunlaboro::Entity&, NumberComponent& number, NameComponent& name) {
			result += std::to_string(number.Number);
			result += name.Name + " ";
		});

		REQUIRE(result == "3fizz 5buzz 6fizz 9fizz 10buzz 12fizz 15fizzbuzz ");
	}
}

struct Position : public Kunlaboro::Component
{
	Position(float x, float y)
		: X(x)
		, Y(y)
	{ }

	volatile float X, Y;
};
struct Velocity : public Kunlaboro::Component
{
	Velocity(float x, float y)
		: X(x)
		, Y(y)
	{ }

	volatile float X, Y;
};

TEST_CASE("Simple n-body simulation - 100 particles", "[comprehensive][performance][view]")
{
	Kunlaboro::EntitySystem es;

	const int ParticleCount = 100;

	std::random_device rand;
	std::uniform_real_distribution<float> ang(0, 3.14159f * 2);
	std::uniform_real_distribution<float> mag(0, 100);

	for (int i = 0; i < ParticleCount; ++i)
	{
		auto ent = es.entityCreate();
		float angle = ang(rand);
		float magnitude = mag(rand);

		ent.addComponent<Position>(std::cos(angle) * magnitude, std::sin(angle) * magnitude);
		ent.addComponent<Velocity>((mag(rand) - 50) / 5, (mag(rand) - 50) / 5);
	}

	REQUIRE(es.componentGetPool(Kunlaboro::ComponentFamily<Position>::getFamily()).countBits() == ParticleCount);
	REQUIRE(es.componentGetPool(Kunlaboro::ComponentFamily<Velocity>::getFamily()).countBits() == ParticleCount);

	SECTION("forEach Iteration, 100 steps, 100 000 calls per step")
	{
		const int IterationCount = 100;

		std::atomic<uint32_t> gravityIterations(0)
		                    , velocityIterations(0);

		auto entityView = Kunlaboro::EntityView(es).withComponents<Kunlaboro::Match_All, Position,Velocity>();
		auto particleList = Kunlaboro::EntityView(es).withComponents<Kunlaboro::Match_All, Position>();

		for (int step = 0; step < IterationCount; ++step)
		{
			entityView.forEach([&gravityIterations, &velocityIterations, &particleList](Kunlaboro::Entity& ent, Position& pos, Velocity& vel) {
				particleList.forEach([&gravityIterations, &ent, &pos, &vel](Kunlaboro::Entity& ent2, Position& pos2) {
					if (ent == ent2)
						return;

					const float xDelta = (pos2.X - pos.X);
					const float yDelta = (pos2.Y - pos.Y);
					const float deltaSqrt = std::sqrt(xDelta*xDelta + yDelta*yDelta + 1e-9f);
					const float invDist = 1 / deltaSqrt;
					const float invDist2 = invDist * invDist;

					vel.X += xDelta * invDist2;
					vel.Y += yDelta * invDist2;

					gravityIterations.fetch_add(1);
				});

				pos.X += vel.X;
				pos.Y += vel.Y;

				velocityIterations.fetch_add(1);
			});
		}

		REQUIRE(gravityIterations  == ParticleCount * (ParticleCount - 1) * IterationCount);
		REQUIRE(velocityIterations == ParticleCount * IterationCount);
	}

	SECTION("Parallel gravity iteration, 100 steps, 100 000 calls per step")
	{
		const int IterationCount = 100;

		std::atomic<uint32_t> gravityIterations(0)
		                    , velocityIterations(0);

		Kunlaboro::detail::JobQueue queue;
		auto entityView = Kunlaboro::EntityView(es).withComponents<Kunlaboro::Match_All, Position,Velocity>();
		auto particleList = Kunlaboro::EntityView(es).withComponents<Kunlaboro::Match_All, Position>().parallel(queue);

		for (int step = 0; step < IterationCount; ++step)
		{
			entityView.forEach([&gravityIterations, &velocityIterations, &particleList](Kunlaboro::Entity& ent, Position& pos, Velocity& vel) {
				particleList.forEach([&gravityIterations, &ent, &pos, &vel](Kunlaboro::Entity& ent2, Position& pos2) {
					if (ent == ent2)
						return;

					const float xDelta = (pos2.X - pos.X);
					const float yDelta = (pos2.Y - pos.Y);
					const float deltaSqrt = std::sqrt(xDelta*xDelta + yDelta*yDelta + 1e-9f);
					const float invDist = 1 / deltaSqrt;
					const float invDist2 = invDist * invDist;

					vel.X += xDelta * invDist2;
					vel.Y += yDelta * invDist2;

					gravityIterations.fetch_add(1, std::memory_order_relaxed);
				});

				pos.X += vel.X;
				pos.Y += vel.Y;

				velocityIterations.fetch_add(1, std::memory_order_relaxed);
			});
		}

		REQUIRE(gravityIterations  == ParticleCount * (ParticleCount - 1) * IterationCount);
		REQUIRE(velocityIterations == ParticleCount * IterationCount);
	}
}
<|endoftext|>


<commit_before>#include "WrapperGenerator.h"

using namespace std;

void WrapperGenerator::initOpToGenMap() {
    shared_ptr<TracingInnerWrapperGenerator> traceGen;
    shared_ptr<CachingIPCInnerWrapperGenerator> cachingIPCGen;
    shared_ptr<NonCachingIPCInnerWrapperGenerator> nonCachingIPCGen;

    traceGen = make_shared<TracingInnerWrapperGenerator>(operationMap);
    cachingIPCGen = make_shared<CachingIPCInnerWrapperGenerator>();
    nonCachingIPCGen = make_shared<NonCachingIPCInnerWrapperGenerator>();

    operationToGenerator = WrapperGenMap({{"MUTEX_LOCK", traceGen},
                                          {"MUTEX_UNLOCK", traceGen},
                                          {"CV_WAIT", traceGen},
                                          {"CV_BROADCAST", traceGen},
                                          {"CV_SIGNAL", traceGen},
                                          {"QUEUE_ENQUEUE", traceGen},
                                          {"QUEUE_DEQUEUE", traceGen},
                                          {"MESSAGE_SEND", traceGen},
                                          {"MESSAGE_RECEIVE", traceGen},
                                          {"MKNOD", cachingIPCGen},
                                          {"OPEN", cachingIPCGen},
                                          {"PIPE", cachingIPCGen},
                                          {"MSGGET", cachingIPCGen},
                                          {"READ", nonCachingIPCGen},
                                          {"WRITE", nonCachingIPCGen},
                                          {"MSGRCV", nonCachingIPCGen},
                                          {"MSGSND", nonCachingIPCGen}});
}

WrapperGenerator::WrapperGenerator(shared_ptr<unordered_map<string,
                                   FunctionPrototype>> _prototypeMap,
                                   std::shared_ptr<std::unordered_map<std::string,
                                   std::string>> _operationMap,
                                   string pathPrefix):
                                   prototypeMap(_prototypeMap),
                                   operationMap(_operationMap) {
    initOpToGenMap();

    headerFile.open(pathPrefix + "VProfEventWrappers.h");
    implementationFile.open(pathPrefix + "VProfEventWrappers.cpp");

    const string generatedFileMessage =
        " ///////////////////////////////////////////////////// \n"
        " // Note that this file was generated by VProfiler. // \n"
        " // Please do not change the contents of this file! // \n"
        " ///////////////////////////////////////////////////// \n\n";

    headerFile << generatedFileMessage;
    implementationFile << generatedFileMessage;
}

vector<string> WrapperGenerator::getFilenames() {
    vector<string> result;

    for (auto kv : *prototypeMap) {
        result.push_back(kv.second.filename);
    }

    sort(result.begin(), result.end());
    result.erase(unique(result.begin(), result.end()), result.end());
    return result;
}

void WrapperGenerator::GenerateHeader() {
    vector<string> includeNames = getFilenames();
    headerFile << "#ifndef VPROFEVENTWRAPPERS_H\n#define VPROFEVENTWRAPPERS_H\n";
    for (string &includeName : includeNames) {
        headerFile << "#include \"" + includeName + "\"\n";
    }
    headerFile << "#include \"trace_tool.h\"\n\n"
                  "#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n";

    for (auto kv : *prototypeMap) {
        headerFile << kv.second.functionPrototype + ";\n\n";
    }

    headerFile << "#ifdef __cplusplus\n}\n#endif\n\n#endif";

    headerFile.close();
}

void WrapperGenerator::GenerateImplementations() {
    string operation;
    implementationFile << "#include \"VProfEventWrappers.h\"\n\n";

    for (auto kv : *prototypeMap) {
        operation = (*operationMap)[kv.first];

        implementationFile << kv.second.functionPrototype + " {\n\t";

        if (kv.second.returnType != "void") {
            implementationFile << kv.second.returnType + " result;\n\t";
        }

        operationToGenerator[operation]->GenerateWrapperPrologue(kv.first, kv.second);

        if (kv.second.returnType != "void") {
            implementationFile << "result = ";
        }

        implementationFile << kv.second.innerCallPrefix + "(";

        for (int i = 0, j = kv.second.paramVars.size(); i < j; i++) {
            implementationFile << kv.second.paramVars[i];

            if (i != (j - 1)) {
                implementationFile << ", ";
            }
        }

        implementationFile <<");\n\t";

        operationToGenerator[operation]->GenerateWrapperEpilogue(kv.first, kv.second);

        if (kv.second.returnType != "void") {
            implementationFile << "\treturn result;\n";
        }

        implementationFile << "}\n\n";
    }

    implementationFile.close();
}

void WrapperGenerator::GenerateWrappers() {
    GenerateHeader();
    GenerateImplementations();
}
<commit_msg>Change tab to newline.<commit_after>#include "WrapperGenerator.h"

using namespace std;

void WrapperGenerator::initOpToGenMap() {
    shared_ptr<TracingInnerWrapperGenerator> traceGen;
    shared_ptr<CachingIPCInnerWrapperGenerator> cachingIPCGen;
    shared_ptr<NonCachingIPCInnerWrapperGenerator> nonCachingIPCGen;

    traceGen = make_shared<TracingInnerWrapperGenerator>(operationMap);
    cachingIPCGen = make_shared<CachingIPCInnerWrapperGenerator>();
    nonCachingIPCGen = make_shared<NonCachingIPCInnerWrapperGenerator>();

    operationToGenerator = WrapperGenMap({{"MUTEX_LOCK", traceGen},
                                          {"MUTEX_UNLOCK", traceGen},
                                          {"CV_WAIT", traceGen},
                                          {"CV_BROADCAST", traceGen},
                                          {"CV_SIGNAL", traceGen},
                                          {"QUEUE_ENQUEUE", traceGen},
                                          {"QUEUE_DEQUEUE", traceGen},
                                          {"MESSAGE_SEND", traceGen},
                                          {"MESSAGE_RECEIVE", traceGen},
                                          {"MKNOD", cachingIPCGen},
                                          {"OPEN", cachingIPCGen},
                                          {"PIPE", cachingIPCGen},
                                          {"MSGGET", cachingIPCGen},
                                          {"READ", nonCachingIPCGen},
                                          {"WRITE", nonCachingIPCGen},
                                          {"MSGRCV", nonCachingIPCGen},
                                          {"MSGSND", nonCachingIPCGen}});
}

WrapperGenerator::WrapperGenerator(shared_ptr<unordered_map<string,
                                   FunctionPrototype>> _prototypeMap,
                                   std::shared_ptr<std::unordered_map<std::string,
                                   std::string>> _operationMap,
                                   string pathPrefix):
                                   prototypeMap(_prototypeMap),
                                   operationMap(_operationMap) {
    initOpToGenMap();

    headerFile.open(pathPrefix + "VProfEventWrappers.h");
    implementationFile.open(pathPrefix + "VProfEventWrappers.cpp");

    const string generatedFileMessage =
        " ///////////////////////////////////////////////////// \n"
        " // Note that this file was generated by VProfiler. // \n"
        " // Please do not change the contents of this file! // \n"
        " ///////////////////////////////////////////////////// \n\n";

    headerFile << generatedFileMessage;
    implementationFile << generatedFileMessage;
}

vector<string> WrapperGenerator::getFilenames() {
    vector<string> result;

    for (auto kv : *prototypeMap) {
        result.push_back(kv.second.filename);
    }

    sort(result.begin(), result.end());
    result.erase(unique(result.begin(), result.end()), result.end());
    return result;
}

void WrapperGenerator::GenerateHeader() {
    vector<string> includeNames = getFilenames();
    headerFile << "#ifndef VPROFEVENTWRAPPERS_H\n#define VPROFEVENTWRAPPERS_H\n";
    for (string &includeName : includeNames) {
        headerFile << "#include \"" + includeName + "\"\n";
    }
    headerFile << "#include \"trace_tool.h\"\n\n"
                  "#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n";

    for (auto kv : *prototypeMap) {
        headerFile << kv.second.functionPrototype + ";\n\n";
    }

    headerFile << "#ifdef __cplusplus\n}\n#endif\n\n#endif";

    headerFile.close();
}

void WrapperGenerator::GenerateImplementations() {
    string operation;
    implementationFile << "#include \"VProfEventWrappers.h\"\n\n";

    for (auto kv : *prototypeMap) {
        operation = (*operationMap)[kv.first];

        implementationFile << kv.second.functionPrototype + " {\n\t";

        if (kv.second.returnType != "void") {
            implementationFile << kv.second.returnType + " result;\n\t";
        }

        operationToGenerator[operation]->GenerateWrapperPrologue(kv.first, kv.second);

        if (kv.second.returnType != "void") {
            implementationFile << "result = ";
        }

        implementationFile << kv.second.innerCallPrefix + "(";

        for (int i = 0, j = kv.second.paramVars.size(); i < j; i++) {
            implementationFile << kv.second.paramVars[i];

            if (i != (j - 1)) {
                implementationFile << ", ";
            }
        }

        implementationFile <<");\n\n";

        operationToGenerator[operation]->GenerateWrapperEpilogue(kv.first, kv.second);

        if (kv.second.returnType != "void") {
            implementationFile << "\treturn result;\n";
        }

        implementationFile << "}\n\n";
    }

    implementationFile.close();
}

void WrapperGenerator::GenerateWrappers() {
    GenerateHeader();
    GenerateImplementations();
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include <stdio.h>
#include <tools/fsys.hxx>
#include <comphelper/string.hxx>
#include "export.hxx"
#include <iostream>

using namespace std;
using comphelper::string::getToken;
using comphelper::string::getTokenCount;

namespace
{
    static ::rtl::OString lcl_NormalizeFilename(const ::rtl::OString& rFilename)
    {
        return rFilename.copy(
            ::std::max(
                rFilename.lastIndexOf( "\\" ),
                rFilename.lastIndexOf( "/" ))+1);
    };
}

extern void ConvertHalfwitdhToFullwidth( String& rString );

//
// class PFormEntrys
//

ByteString PFormEntrys::Dump()
{
    ByteString sRet( "PFormEntrys\n" );
    ByteString a("sText");
    if (sText.size())
        Export::DumpMap(a , sText);
    return sRet;
}

sal_Bool PFormEntrys::GetTransex3Text( ByteString &rReturn,
    sal_uInt16 nTyp, const ByteString &nLangIndex, sal_Bool bDel )
{
    sal_Bool rc = GetText( rReturn , nTyp , nLangIndex , bDel );
    ByteString test( rReturn );
    for( sal_uInt16 idx = 0; idx < rReturn.Len(); idx++ )
    {
        if( rReturn.GetChar( idx ) == '\"' && ( idx >= 1 )  &&  rReturn.GetChar( idx-1 ) == '\\' )
        {
            rReturn.Erase( idx-1 , 1 );
        }
    }
    //if( !rReturn.Equals( test ) )
    //    printf("*CHANGED******************\n%s\n%s\n",test.GetBuffer(),rReturn.GetBuffer());
    return rc;
}
/*****************************************************************************/
sal_Bool PFormEntrys::GetText( ByteString &rReturn,
    sal_uInt16 nTyp, const ByteString &nLangIndex, sal_Bool bDel )
{

    sal_Bool bReturn=sal_True;
    switch ( nTyp ) {
        case STRING_TYP_TEXT :
            rReturn = sText[ nLangIndex ];
            if ( bDel )
                sText[ nLangIndex ] = "";
            bReturn = bTextFirst[ nLangIndex ];
            bTextFirst[ nLangIndex ] = sal_False;
            break;
        case STRING_TYP_HELPTEXT :
            rReturn = sHelpText;
            break;
        case STRING_TYP_QUICKHELPTEXT :
            rReturn = sQuickHelpText[ nLangIndex ];
            if ( bDel )
                sQuickHelpText[ nLangIndex ] = "";
            bReturn = bQuickHelpTextFirst[ nLangIndex ];
            bQuickHelpTextFirst[ nLangIndex ] = sal_False;
            break;
        case STRING_TYP_TITLE :
            rReturn = sTitle[ nLangIndex ];
            if ( bDel )
                sTitle[ nLangIndex ] = "";
            bReturn = bTitleFirst[ nLangIndex ];
            bTitleFirst[ nLangIndex ] = sal_False;
            break;
    }
    return bReturn;
}

//
// class MergeData
//

MergeData::~MergeData()
{
}

PFormEntrys* MergeData::GetPFormEntries()
{
    if( aMap.find( ByteString("HACK") ) != aMap.end() )
        return aMap[ ByteString("HACK") ];
    return NULL;
}

void MergeData::Insert(PFormEntrys* pfEntrys )
{
    aMap.insert( PFormEntrysHashMap::value_type( ByteString("HACK") , pfEntrys ) );
}

rtl::OString MergeData::Dump()
{
    printf("MergeData sTyp = %s , sGid = %s , sLid =%s , sFilename = %s\n",
        sTyp.getStr(), sGID.getStr(), sLID.getStr(), sFilename.getStr());

    PFormEntrysHashMap::const_iterator idbg;
    for( idbg = aMap.begin() ; idbg != aMap.end(); ++idbg )
    {
        printf("aMap[ %s ] = " ,idbg->first.getStr());
        ( (PFormEntrys*)(idbg->second) )->Dump();
        printf("\n");
    }
    printf("\n");
    return rtl::OString(RTL_CONSTASCII_STRINGPARAM("MergeData\n"));
}

PFormEntrys* MergeData::GetPFObject( const rtl::OString& rPFO )
{
    if( aMap.find( ByteString("HACK") ) != aMap.end() )
        return aMap[ rPFO ];
    return NULL;
}

sal_Bool MergeData::operator==( ResData *pData )
{
    ByteString sResTyp_upper( pData->sResTyp );
    sResTyp_upper.ToUpperAscii();
    ByteString sTyp_upper( sTyp );
    sTyp_upper.ToUpperAscii();

    return (( pData->sId == sLID ) &&
            ( pData->sGId == sGID ) &&
            ( sResTyp_upper  ==  sTyp_upper )
            );
}

//
// class MergeDataFile
//

#define FFORMAT_UNKNOWN 0x0000
#define FFORMAT_NEW     0x0001
#define FFORMAT_OLD     0x0002

MergeDataFile::MergeDataFile(
    const ByteString &rFileName,
    const ByteString& sFile,
    bool bErrLog,
    bool bCaseSensitive)
    : bErrorLog( bErrLog )
{
    SvFileStream aInputStream( String( rFileName, RTL_TEXTENCODING_ASCII_US ), STREAM_STD_READ );
    aInputStream.SetStreamCharSet( RTL_TEXTENCODING_MS_1252 );
    rtl::OString sLine;
    const ByteString sHACK("HACK");
    const ::rtl::OString sFileNormalized(lcl_NormalizeFilename(sFile));
    const bool isFileEmpty = !sFileNormalized.isEmpty();

    if( !aInputStream.IsOpen() )
    {
        printf("Warning : Can't open %s\n", rFileName.GetBuffer());
        return;
    }
    while ( !aInputStream.IsEof())
    {
        xub_StrLen nToks;
        aInputStream.ReadLine( sLine );
        nToks = getTokenCount(sLine, '\t');
        if ( nToks == 15 )
        {
            // Skip all wrong filenames
            const ::rtl::OString filename = lcl_NormalizeFilename(getToken(sLine, 1 , '\t'));
            if(isFileEmpty || sFileNormalized.equals("") || (!isFileEmpty && filename.equals(sFileNormalized)) )
            {
                sal_Int32 rIdx = 0;
                const ByteString sTYP = sLine.getToken( 3, '\t', rIdx );
                const ByteString sGID = sLine.getToken( 0, '\t', rIdx ); // 4
                const ByteString sLID = sLine.getToken( 0, '\t', rIdx ); // 5
                ByteString sPFO = sLine.getToken( 1, '\t', rIdx ); // 7
                sPFO = sHACK;
                ByteString nLANG = sLine.getToken( 1, '\t', rIdx ); // 9
                nLANG = comphelper::string::strip(nLANG, ' ');
                const ByteString sTEXT = sLine.getToken( 0, '\t', rIdx ); // 10
                const ByteString sQHTEXT = sLine.getToken( 1, '\t', rIdx ); // 12
                const ByteString sTITLE = sLine.getToken( 0, '\t', rIdx );  // 13

                if( !nLANG.EqualsIgnoreCaseAscii("en-US") )
                {
                    aLanguageSet.insert(nLANG);
                    InsertEntry( sTYP, sGID, sLID, sPFO, nLANG, sTEXT, sQHTEXT, sTITLE, filename, bCaseSensitive );
                }
            }
        }
        else if ( nToks == 10 )
        {
            printf("ERROR: File format is obsolete and no longer supported!\n");
        }
    }
    aInputStream.Close();
}

MergeDataFile::~MergeDataFile()
{
    for (MergeDataHashMap::iterator aI = aMap.begin(), aEnd = aMap.end(); aI != aEnd; ++aI)
        delete aI->second;
}

ByteString MergeDataFile::Dump(){
    ByteString sRet( "MergeDataFile\n" );

    printf("MergeDataFile\n");
    MergeDataHashMap::const_iterator idbg;
    for( idbg = aMap.begin() ; idbg != aMap.end(); ++idbg )
    {
        printf("aMap[ %s ] = ",idbg->first.getStr());
        idbg->second->Dump();
        printf("\n");
    }
    printf("\n");
    return sRet;
}

std::vector<rtl::OString> MergeDataFile::GetLanguages(){
    return std::vector<rtl::OString>(aLanguageSet.begin(),aLanguageSet.end());
}

MergeData *MergeDataFile::GetMergeData( ResData *pResData , bool bCaseSensitive )
{
    ByteString sOldG = pResData->sGId;
    ByteString sOldL = pResData->sId;
    ByteString sGID = pResData->sGId;
    ByteString sLID;
    if(!sGID.Len())
        sGID = pResData->sId;
    else
        sLID = pResData->sId;
    pResData->sGId = sGID;
    pResData->sId = sLID;

    ByteString sKey = CreateKey( pResData->sResTyp , pResData->sGId , pResData->sId , pResData->sFilename , bCaseSensitive );

    if(aMap.find( sKey ) != aMap.end())
    {
        pResData->sGId = sOldG;
        pResData->sId = sOldL;
        return aMap[ sKey ];
    }
    pResData->sGId = sOldG;
    pResData->sId = sOldL;
    return NULL;
}

PFormEntrys *MergeDataFile::GetPFormEntrys( ResData *pResData )
{
    // search for requested PFormEntrys
    MergeData *pData = GetMergeData( pResData );
    if ( pData )
        return pData->GetPFormEntries();
    return NULL;
}

PFormEntrys *MergeDataFile::GetPFormEntrysCaseSensitive( ResData *pResData )
{
    // search for requested PFormEntrys
    MergeData *pData = GetMergeData( pResData , true );
    if ( pData )
        return pData->GetPFormEntries();
    return NULL;
}

void MergeDataFile::InsertEntry(
    const ByteString &rTYP, const ByteString &rGID,
    const ByteString &rLID, const ByteString &rPFO,
    const ByteString &nLANG, const ByteString &rTEXT,
    const ByteString &rQHTEXT, const ByteString &rTITLE ,
    const ByteString &rInFilename , bool bCaseSensitive
    )
{
    MergeData *pData;

    // search for MergeData
    ByteString sKey = CreateKey( rTYP , rGID , rLID , rInFilename , bCaseSensitive );
    MergeDataHashMap::const_iterator mit;
    mit = aMap.find( sKey );
    if( mit != aMap.end() )
    {
        pData = mit->second;
    }
    else
    {
        pData = new MergeData( rTYP, rGID, rLID, rInFilename );
        aMap.insert( MergeDataHashMap::value_type( sKey, pData ) );
    }

    PFormEntrys *pFEntrys = 0;

    // search for PFormEntrys
    pFEntrys = pData->GetPFObject( rPFO );
    if( !pFEntrys )
    {
        // create new PFormEntrys, cause no one exists with current properties
        pFEntrys = new PFormEntrys( rPFO );
        pData->Insert( pFEntrys );
    }

    // finaly insert the cur string
    pFEntrys->InsertEntry( nLANG , rTEXT, rQHTEXT, rTITLE );
}

ByteString MergeDataFile::CreateKey( const ByteString& rTYP , const ByteString& rGID , const ByteString& rLID , const ByteString& rFilename , bool bCaseSensitive )
{
    static const ::rtl::OString sStroke('-');
    ::rtl::OString sKey( rTYP );
    sKey += sStroke;
    sKey += rGID;
    sKey += sStroke;
    sKey += rLID;
    sKey += sStroke;
    sKey += lcl_NormalizeFilename(rFilename);
    OSL_TRACE("created key: %s", sKey.getStr());
    if(bCaseSensitive)
        return sKey;         // officecfg case sensitive identifier
    return sKey.toAsciiUpperCase();
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>unused test string<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include <stdio.h>
#include <tools/fsys.hxx>
#include <comphelper/string.hxx>
#include "export.hxx"
#include <iostream>

using namespace std;
using comphelper::string::getToken;
using comphelper::string::getTokenCount;

namespace
{
    static ::rtl::OString lcl_NormalizeFilename(const ::rtl::OString& rFilename)
    {
        return rFilename.copy(
            ::std::max(
                rFilename.lastIndexOf( "\\" ),
                rFilename.lastIndexOf( "/" ))+1);
    };
}

extern void ConvertHalfwitdhToFullwidth( String& rString );

//
// class PFormEntrys
//

ByteString PFormEntrys::Dump()
{
    ByteString sRet( "PFormEntrys\n" );
    ByteString a("sText");
    if (sText.size())
        Export::DumpMap(a , sText);
    return sRet;
}

sal_Bool PFormEntrys::GetTransex3Text( ByteString &rReturn,
    sal_uInt16 nTyp, const ByteString &nLangIndex, sal_Bool bDel )
{
    sal_Bool rc = GetText( rReturn , nTyp , nLangIndex , bDel );
    for( sal_uInt16 idx = 0; idx < rReturn.Len(); idx++ )
    {
        if( rReturn.GetChar( idx ) == '\"' && ( idx >= 1 )  &&  rReturn.GetChar( idx-1 ) == '\\' )
        {
            rReturn.Erase( idx-1 , 1 );
        }
    }
    return rc;
}
/*****************************************************************************/
sal_Bool PFormEntrys::GetText( ByteString &rReturn,
    sal_uInt16 nTyp, const ByteString &nLangIndex, sal_Bool bDel )
{

    sal_Bool bReturn=sal_True;
    switch ( nTyp ) {
        case STRING_TYP_TEXT :
            rReturn = sText[ nLangIndex ];
            if ( bDel )
                sText[ nLangIndex ] = "";
            bReturn = bTextFirst[ nLangIndex ];
            bTextFirst[ nLangIndex ] = sal_False;
            break;
        case STRING_TYP_HELPTEXT :
            rReturn = sHelpText;
            break;
        case STRING_TYP_QUICKHELPTEXT :
            rReturn = sQuickHelpText[ nLangIndex ];
            if ( bDel )
                sQuickHelpText[ nLangIndex ] = "";
            bReturn = bQuickHelpTextFirst[ nLangIndex ];
            bQuickHelpTextFirst[ nLangIndex ] = sal_False;
            break;
        case STRING_TYP_TITLE :
            rReturn = sTitle[ nLangIndex ];
            if ( bDel )
                sTitle[ nLangIndex ] = "";
            bReturn = bTitleFirst[ nLangIndex ];
            bTitleFirst[ nLangIndex ] = sal_False;
            break;
    }
    return bReturn;
}

//
// class MergeData
//

MergeData::~MergeData()
{
}

PFormEntrys* MergeData::GetPFormEntries()
{
    if( aMap.find( ByteString("HACK") ) != aMap.end() )
        return aMap[ ByteString("HACK") ];
    return NULL;
}

void MergeData::Insert(PFormEntrys* pfEntrys )
{
    aMap.insert( PFormEntrysHashMap::value_type( ByteString("HACK") , pfEntrys ) );
}

rtl::OString MergeData::Dump()
{
    printf("MergeData sTyp = %s , sGid = %s , sLid =%s , sFilename = %s\n",
        sTyp.getStr(), sGID.getStr(), sLID.getStr(), sFilename.getStr());

    PFormEntrysHashMap::const_iterator idbg;
    for( idbg = aMap.begin() ; idbg != aMap.end(); ++idbg )
    {
        printf("aMap[ %s ] = " ,idbg->first.getStr());
        ( (PFormEntrys*)(idbg->second) )->Dump();
        printf("\n");
    }
    printf("\n");
    return rtl::OString(RTL_CONSTASCII_STRINGPARAM("MergeData\n"));
}

PFormEntrys* MergeData::GetPFObject( const rtl::OString& rPFO )
{
    if( aMap.find( ByteString("HACK") ) != aMap.end() )
        return aMap[ rPFO ];
    return NULL;
}

sal_Bool MergeData::operator==( ResData *pData )
{
    ByteString sResTyp_upper( pData->sResTyp );
    sResTyp_upper.ToUpperAscii();
    ByteString sTyp_upper( sTyp );
    sTyp_upper.ToUpperAscii();

    return (( pData->sId == sLID ) &&
            ( pData->sGId == sGID ) &&
            ( sResTyp_upper  ==  sTyp_upper )
            );
}

//
// class MergeDataFile
//

#define FFORMAT_UNKNOWN 0x0000
#define FFORMAT_NEW     0x0001
#define FFORMAT_OLD     0x0002

MergeDataFile::MergeDataFile(
    const ByteString &rFileName,
    const ByteString& sFile,
    bool bErrLog,
    bool bCaseSensitive)
    : bErrorLog( bErrLog )
{
    SvFileStream aInputStream( String( rFileName, RTL_TEXTENCODING_ASCII_US ), STREAM_STD_READ );
    aInputStream.SetStreamCharSet( RTL_TEXTENCODING_MS_1252 );
    rtl::OString sLine;
    const ByteString sHACK("HACK");
    const ::rtl::OString sFileNormalized(lcl_NormalizeFilename(sFile));
    const bool isFileEmpty = !sFileNormalized.isEmpty();

    if( !aInputStream.IsOpen() )
    {
        printf("Warning : Can't open %s\n", rFileName.GetBuffer());
        return;
    }
    while ( !aInputStream.IsEof())
    {
        xub_StrLen nToks;
        aInputStream.ReadLine( sLine );
        nToks = getTokenCount(sLine, '\t');
        if ( nToks == 15 )
        {
            // Skip all wrong filenames
            const ::rtl::OString filename = lcl_NormalizeFilename(getToken(sLine, 1 , '\t'));
            if(isFileEmpty || sFileNormalized.equals("") || (!isFileEmpty && filename.equals(sFileNormalized)) )
            {
                sal_Int32 rIdx = 0;
                const ByteString sTYP = sLine.getToken( 3, '\t', rIdx );
                const ByteString sGID = sLine.getToken( 0, '\t', rIdx ); // 4
                const ByteString sLID = sLine.getToken( 0, '\t', rIdx ); // 5
                ByteString sPFO = sLine.getToken( 1, '\t', rIdx ); // 7
                sPFO = sHACK;
                ByteString nLANG = sLine.getToken( 1, '\t', rIdx ); // 9
                nLANG = comphelper::string::strip(nLANG, ' ');
                const ByteString sTEXT = sLine.getToken( 0, '\t', rIdx ); // 10
                const ByteString sQHTEXT = sLine.getToken( 1, '\t', rIdx ); // 12
                const ByteString sTITLE = sLine.getToken( 0, '\t', rIdx );  // 13

                if( !nLANG.EqualsIgnoreCaseAscii("en-US") )
                {
                    aLanguageSet.insert(nLANG);
                    InsertEntry( sTYP, sGID, sLID, sPFO, nLANG, sTEXT, sQHTEXT, sTITLE, filename, bCaseSensitive );
                }
            }
        }
        else if ( nToks == 10 )
        {
            printf("ERROR: File format is obsolete and no longer supported!\n");
        }
    }
    aInputStream.Close();
}

MergeDataFile::~MergeDataFile()
{
    for (MergeDataHashMap::iterator aI = aMap.begin(), aEnd = aMap.end(); aI != aEnd; ++aI)
        delete aI->second;
}

ByteString MergeDataFile::Dump(){
    ByteString sRet( "MergeDataFile\n" );

    printf("MergeDataFile\n");
    MergeDataHashMap::const_iterator idbg;
    for( idbg = aMap.begin() ; idbg != aMap.end(); ++idbg )
    {
        printf("aMap[ %s ] = ",idbg->first.getStr());
        idbg->second->Dump();
        printf("\n");
    }
    printf("\n");
    return sRet;
}

std::vector<rtl::OString> MergeDataFile::GetLanguages(){
    return std::vector<rtl::OString>(aLanguageSet.begin(),aLanguageSet.end());
}

MergeData *MergeDataFile::GetMergeData( ResData *pResData , bool bCaseSensitive )
{
    ByteString sOldG = pResData->sGId;
    ByteString sOldL = pResData->sId;
    ByteString sGID = pResData->sGId;
    ByteString sLID;
    if(!sGID.Len())
        sGID = pResData->sId;
    else
        sLID = pResData->sId;
    pResData->sGId = sGID;
    pResData->sId = sLID;

    ByteString sKey = CreateKey( pResData->sResTyp , pResData->sGId , pResData->sId , pResData->sFilename , bCaseSensitive );

    if(aMap.find( sKey ) != aMap.end())
    {
        pResData->sGId = sOldG;
        pResData->sId = sOldL;
        return aMap[ sKey ];
    }
    pResData->sGId = sOldG;
    pResData->sId = sOldL;
    return NULL;
}

PFormEntrys *MergeDataFile::GetPFormEntrys( ResData *pResData )
{
    // search for requested PFormEntrys
    MergeData *pData = GetMergeData( pResData );
    if ( pData )
        return pData->GetPFormEntries();
    return NULL;
}

PFormEntrys *MergeDataFile::GetPFormEntrysCaseSensitive( ResData *pResData )
{
    // search for requested PFormEntrys
    MergeData *pData = GetMergeData( pResData , true );
    if ( pData )
        return pData->GetPFormEntries();
    return NULL;
}

void MergeDataFile::InsertEntry(
    const ByteString &rTYP, const ByteString &rGID,
    const ByteString &rLID, const ByteString &rPFO,
    const ByteString &nLANG, const ByteString &rTEXT,
    const ByteString &rQHTEXT, const ByteString &rTITLE ,
    const ByteString &rInFilename , bool bCaseSensitive
    )
{
    MergeData *pData;

    // search for MergeData
    ByteString sKey = CreateKey( rTYP , rGID , rLID , rInFilename , bCaseSensitive );
    MergeDataHashMap::const_iterator mit;
    mit = aMap.find( sKey );
    if( mit != aMap.end() )
    {
        pData = mit->second;
    }
    else
    {
        pData = new MergeData( rTYP, rGID, rLID, rInFilename );
        aMap.insert( MergeDataHashMap::value_type( sKey, pData ) );
    }

    PFormEntrys *pFEntrys = 0;

    // search for PFormEntrys
    pFEntrys = pData->GetPFObject( rPFO );
    if( !pFEntrys )
    {
        // create new PFormEntrys, cause no one exists with current properties
        pFEntrys = new PFormEntrys( rPFO );
        pData->Insert( pFEntrys );
    }

    // finaly insert the cur string
    pFEntrys->InsertEntry( nLANG , rTEXT, rQHTEXT, rTITLE );
}

ByteString MergeDataFile::CreateKey( const ByteString& rTYP , const ByteString& rGID , const ByteString& rLID , const ByteString& rFilename , bool bCaseSensitive )
{
    static const ::rtl::OString sStroke('-');
    ::rtl::OString sKey( rTYP );
    sKey += sStroke;
    sKey += rGID;
    sKey += sStroke;
    sKey += rLID;
    sKey += sStroke;
    sKey += lcl_NormalizeFilename(rFilename);
    OSL_TRACE("created key: %s", sKey.getStr());
    if(bCaseSensitive)
        return sKey;         // officecfg case sensitive identifier
    return sKey.toAsciiUpperCase();
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: sdxmlwrp.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: cl $ $Date: 2000-11-17 11:13:31 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _SFXDOCFILE_HXX
#include <sfx2/docfile.hxx>
#endif

#ifndef _SDXMLWRP_HXX
#include "sdxmlwrp.hxx"
#endif

#ifndef _SDXMLIMP_HXX
#include <xmloff/sdxmlimp.hxx>
#endif

#ifndef _SDXMLEXP_HXX
#include <xmloff/sdxmlexp.hxx>
#endif

#ifndef _DRAWDOC_HXX
#include "drawdoc.hxx"
#endif

#ifndef _UNO_MAPPING_HXX_
#include <uno/mapping.hxx>  //! only necessary until SfxMedium has a uno3 DataSource / DataSink
#endif

#include <com/sun/star/xml/sax/XErrorHandler.hpp>
#include <com/sun/star/xml/sax/XEntityResolver.hpp>
#include <com/sun/star/xml/sax/InputSource.hpp>
#include <com/sun/star/xml/sax/XDTDHandler.hpp>
#include <com/sun/star/xml/sax/XParser.hpp>
#include <com/sun/star/io/XActiveDataSource.hpp>
#include <com/sun/star/io/XActiveDataControl.hpp>

#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#include "pkgurl.hxx"

using namespace com::sun::star;
using namespace rtl;

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

char __READONLY_DATA sXML_drawing[] = "drawing";
char __READONLY_DATA sXML_impress[] = "presentation";

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

SdXMLWrapper::SdXMLWrapper(
    uno::Reference<frame::XModel>& xRef,
    SfxMedium& rMedium,
    BOOL bIsDraw, BOOL bShowProg)
:   mxLocalModel(xRef),
    mrMedium(rMedium),
    mbIsDraw(bIsDraw),
    mbShowProgress(bShowProg)
{
}

BOOL SdXMLWrapper::Import()
{
    if(!mxLocalModel.is())
    {
        DBG_ERROR("Got NO Model in XMLImport");
        return FALSE;
    }

    uno::Reference<lang::XServiceInfo> xServiceInfo(mxLocalModel, uno::UNO_QUERY);
    if(!xServiceInfo.is() || !xServiceInfo->supportsService(OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.DrawingDocument"))))
    {
        DBG_ERROR("Model is no DrawingDocument in XMLImport");
        return FALSE;
    }

    uno::Reference<lang::XMultiServiceFactory> xServiceFactory(::comphelper::getProcessServiceFactory());
    if(!xServiceFactory.is())
    {
        DBG_ERROR("XMLReader::Read: got no service manager");
        return FALSE;
    }

    // Get data source ...
    uno::Reference<io::XActiveDataSource> xSource = mrMedium.GetDataSource();

    if(!xSource.is())
    {
//      // If we didn't get a data source from a medium, we have to create one
//      XInterfaceRef xFactory = xServiceFactory->createInstance(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.frame.DataSourceFactory"));
//      if(xFactory.is())
//      {
//          XMultiServiceFactoryRef xMFactory(xFactory, USR_QUERY);
//
//          if(xMFactory.is())
//          {
//              UString sURL(S2WS(mrMedium.GetName()));
//              Sequence<Any> aArgs(1);
//              Any* pArgs = aArgs.getArray();
//
//              pArgs->setString(sURL);
//
//              XInterfaceRef xSrc = xMFactory->createInstanceWithArguments(sURL, aArgs);
//
//              if(xSrc.is())
//              {
//                  xSrc->queryInterface(XActiveDataSource::getSmartUik(), xSource);
//              }
//          }
//      }
    }

    // get data source
    if(!xSource.is())
    {
        DBG_ERROR("XMLReader::Read: data source missing");
        return FALSE;
    }

    // get parser
    uno::Reference<uno::XInterface> xXMLParser(xServiceFactory->createInstance(
        OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.xml.sax.Parser"))));
    if(!xXMLParser.is())
    {
        DBG_ERROR("com.sun.star.xml.sax.Parser service missing");
        return FALSE;
    }

    // get a pipe for connecting the data source to the parser
    uno::Reference<uno::XInterface> xPipe(xServiceFactory->createInstance(
        OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.io.Pipe"))));
    if(!xPipe.is())
    {
        DBG_ERROR("com.sun.star.io.Pipe service missing");
        return FALSE;
    }

    UINT16 nStyleFamilyMask(0);
    BOOL bLoadDoc(TRUE);

// this is stuff for loading only styles or add-load documents, needed later
//  USHORT nStyleFamilyMask = SFX_STYLE_FAMILY_ALL;
//  BOOL bInsert;
//  if( aOpt.IsFmtsOnly() )
//  {
//      bLoadDoc = FALSE;
//      bInsert = aOpt.IsMerge();
//      nStyleFamilyMask = 0U;
//      if( aOpt.IsFrmFmts() )
//          nStyleFamilyMask |= SFX_STYLE_FAMILY_FRAME;
//      if( aOpt.IsPageDescs() )
//          nStyleFamilyMask |= SFX_STYLE_FAMILY_PAGE;
//      if( aOpt.IsTxtFmts() )
//          nStyleFamilyMask |= (SFX_STYLE_FAMILY_CHAR|SFX_STYLE_FAMILY_PARA);
//      if( aOpt.IsNumRules() )
//          nStyleFamilyMask |= SFX_STYLE_FAMILY_PSEUDO;
//  }
//  else
//  {
//      bLoadDoc = TRUE;
//      bInsert = bInsertMode;
//      nStyleFamilyMask = SFX_STYLE_FAMILY_ALL;
//  }
//  aOpt.ResetAllFmtsOnly();

    // get filter
    uno::Reference<xml::sax::XDocumentHandler> xFilter =
        new SdXMLImport(mxLocalModel, bLoadDoc, nStyleFamilyMask, mbShowProgress, IsDraw());

    // connect pipe's output stream to the data source
    uno::Reference<io::XOutputStream> xPipeOutput(xPipe, uno::UNO_QUERY);
    xSource->setOutputStream(xPipeOutput);

    // connect pipe's input stream to the parser
    xml::sax::InputSource aParserInput;
    uno::Reference<io::XInputStream> xPipeInput(xPipe, uno::UNO_QUERY);
    aParserInput.aInputStream = xPipeInput;
    aParserInput.sSystemId = mrMedium.GetName();
    OUString sFileName = mrMedium.GetName();

    // connect parser and filter
    uno::Reference<xml::sax::XParser> xParser(xXMLParser, uno::UNO_QUERY);

//      uno::Reference<xml::sax::XDocumentHandler> xPacker =
//    new URLPacker(sFileName, xFilter, sal_True, sal_False);
//  xParser->setDocumentHandler(xPacker);
    xParser->setDocumentHandler(xFilter);

    // parse
    uno::Reference<io::XActiveDataControl> xSourceControl(xSource, uno::UNO_QUERY);
    xSourceControl->start();
    BOOL bRetval(TRUE);

    try
    {
        xParser->parseStream(aParserInput);
    }
    catch(xml::sax::SAXParseException)
    {
        bRetval = FALSE;
    }
    catch(xml::sax::SAXException)
    {
        bRetval = FALSE;
    }
    catch(io::IOException)
    {
        bRetval = FALSE;
    }

    return bRetval;
}

BOOL SdXMLWrapper::Export()
{
    if(!mxLocalModel.is())
    {
        DBG_ERROR("Got NO Model in XMLExport");
        return FALSE;
    }

    uno::Reference<lang::XServiceInfo> xServiceInfo(mxLocalModel, uno::UNO_QUERY);
    if(!xServiceInfo.is() || !xServiceInfo->supportsService(
        OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.DrawingDocument"))))
    {
        DBG_ERROR("Model is no DrawingDocument in XMLExport");
        return FALSE;
    }

    uno::Reference<lang::XMultiServiceFactory> xServiceFactory(::comphelper::getProcessServiceFactory());
    if(!xServiceFactory.is())
    {
        DBG_ERROR("got no service manager");
        return FALSE;
    }

    uno::Reference<uno::XInterface> xWriter(xServiceFactory->createInstance(
        OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.xml.sax.Writer"))));
    if(!xWriter.is())
    {
        DBG_ERROR("com.sun.star.xml.sax.Writer service missing");
        return FALSE;
    }

    // smart -> uno3 conversion only until SfxMedium has a uno3 DataSink
    uno::Reference<io::XOutputStream> xOut = mrMedium.GetDataSink();
    uno::Reference<io::XActiveDataSource> xSrc(xWriter, uno::UNO_QUERY);
    xSrc->setOutputStream(xOut);

    uno::Reference<xml::sax::XDocumentHandler> xHandler(xWriter, uno::UNO_QUERY);
    OUString sFileName = mrMedium.GetName();

#ifdef XMLTESTBIN
    uno::Reference<xml::sax::XDocumentHandler> xPacker =
      new URLPacker(sFileName, xHandler, sal_False, sal_True);
    SdXMLExport aExp(mxLocalModel, sFileName, xPacker, mbShowProgress, IsDraw());
#else
    SdXMLExport aExp(mxLocalModel, sFileName, xHandler, mbShowProgress, IsDraw());
#endif

    // give string descriptor as parameter for doc type
    BOOL bRet = (0 == aExp.exportDoc( IsDraw() ? sXML_drawing : sXML_impress ));

    return bRet;
}

<commit_msg>#80795#: new package concept/added SvxXMLGraphicHelper<commit_after>/*************************************************************************
 *
 *  $RCSfile: sdxmlwrp.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: ka $ $Date: 2000-12-02 10:13:02 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _SFXDOCFILE_HXX
#include <sfx2/docfile.hxx>
#endif
#ifndef _SDXMLIMP_HXX
#include <xmloff/sdxmlimp.hxx>
#endif
#ifndef _SDXMLEXP_HXX
#include <xmloff/sdxmlexp.hxx>
#endif
#ifndef _DRAWDOC_HXX
#include "drawdoc.hxx"
#endif
#ifndef _UTL_STREAM_WRAPPER_HXX_
#include <unotools/streamwrap.hxx>
#endif
#ifndef _XMLGRHLP_HXX
#include <svx/xmlgrhlp.hxx>
#endif

#include <com/sun/star/xml/sax/XErrorHandler.hpp>
#include <com/sun/star/xml/sax/XEntityResolver.hpp>
#include <com/sun/star/xml/sax/InputSource.hpp>
#include <com/sun/star/xml/sax/XDTDHandler.hpp>
#include <com/sun/star/xml/sax/XParser.hpp>
#include <com/sun/star/io/XActiveDataSource.hpp>
#include <com/sun/star/io/XActiveDataControl.hpp>

#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#include "sdxmlwrp.hxx"
#include "pkgurl.hxx"

using namespace com::sun::star;
using namespace rtl;

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

char __READONLY_DATA sXML_drawing[] = "drawing";
char __READONLY_DATA sXML_impress[] = "presentation";
char __READONLY_DATA sXML_content[] = "Content";

// ----------------
// - SdXMLWrapper -
// ----------------

SdXMLWrapper::SdXMLWrapper( uno::Reference<frame::XModel>& xRef,
                            SfxMedium& rMedium, BOOL bIsDraw, BOOL bShowProg ) :
    mxLocalModel    ( xRef ),
    mrMedium        ( rMedium ),
    mbIsDraw        ( bIsDraw ),
    mbShowProgress  ( bShowProg )
{
}

// -----------------------------------------------------------------------------

BOOL SdXMLWrapper::Import()
{
    if( !mxLocalModel.is() )
    {
        DBG_ERROR("Got NO Model in XMLImport");
        return FALSE;
    }

    uno::Reference<lang::XServiceInfo> xServiceInfo(mxLocalModel, uno::UNO_QUERY);

    if( !xServiceInfo.is() || !xServiceInfo->supportsService( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.drawing.DrawingDocument" ) ) ) )
    {
        DBG_ERROR( "Model is no DrawingDocument in XMLImport" );
        return FALSE;
    }

    uno::Reference<lang::XMultiServiceFactory> xServiceFactory( ::comphelper::getProcessServiceFactory() );

    if( !xServiceFactory.is() )
    {
        DBG_ERROR( "XMLReader::Read: got no service manager" );
        return FALSE;
    }

    uno::Reference< uno::XInterface> xXMLParser( xServiceFactory->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.xml.sax.Parser" ) ) ) );

    if( !xXMLParser.is() )
    {
        DBG_ERROR( "com.sun.star.xml.sax.Parser service missing" );
        return FALSE;
    }

    UINT16  nStyleFamilyMask = 0;
    BOOL    bLoadDoc = TRUE, bRet = FALSE;

// this is stuff for loading only styles or add-load documents, needed later
//  USHORT nStyleFamilyMask = SFX_STYLE_FAMILY_ALL;
//  BOOL bInsert;
//  if( aOpt.IsFmtsOnly() )
//  {
//      bLoadDoc = FALSE;
//      bInsert = aOpt.IsMerge();
//      nStyleFamilyMask = 0U;
//      if( aOpt.IsFrmFmts() )
//          nStyleFamilyMask |= SFX_STYLE_FAMILY_FRAME;
//      if( aOpt.IsPageDescs() )
//          nStyleFamilyMask |= SFX_STYLE_FAMILY_PAGE;
//      if( aOpt.IsTxtFmts() )
//          nStyleFamilyMask |= (SFX_STYLE_FAMILY_CHAR|SFX_STYLE_FAMILY_PARA);
//      if( aOpt.IsNumRules() )
//          nStyleFamilyMask |= SFX_STYLE_FAMILY_PSEUDO;
//  }
//  else
//  {
//      bLoadDoc = TRUE;
//      bInsert = bInsertMode;
//      nStyleFamilyMask = SFX_STYLE_FAMILY_ALL;
//  }
//  aOpt.ResetAllFmtsOnly();

    try
    {
        xml::sax::InputSource                   aParserInput;
        SvStorageStreamRef                      xIStm;
        SvStorage*                              pStorage = mrMedium.GetStorage();
        uno::Reference< io::XActiveDataSource > xSource;

        aParserInput.sSystemId = mrMedium.GetName();

        if( pStorage )
        {

            static const String aContentStmName( RTL_CONSTASCII_USTRINGPARAM( sXML_content ) );

            xIStm = pStorage->OpenStream( aContentStmName, STREAM_READ | STREAM_NOCREATE );

            if( xIStm.Is() )
            {
                xIStm->SetBufferSize( 16 * 1024 );
                aParserInput.aInputStream = new utl::OInputStreamWrapper( *xIStm );
            }
            else
            {
                DBG_ERROR( "could not open Content stream" );
                return FALSE;
            }
        }
        else
        {
            uno::Reference< uno::XInterface > xPipe;

            mrMedium.GetInStream()->Seek( 0 );

            xSource = mrMedium.GetDataSource();
            DBG_ASSERT( xSource.is(), "got no data source from medium" );

            if( !xSource.is() )
                return sal_False;

            xPipe = xServiceFactory->createInstance( OUString::createFromAscii( "com.sun.star.io.Pipe" ) );
            DBG_ASSERT( xPipe.is(), "com.sun.star.io.Pipe service missing" );

            if( !xPipe.is() )
                return sal_False;

            xSource->setOutputStream( uno::Reference< io::XOutputStream >( xPipe, uno::UNO_QUERY ) );
            aParserInput.aInputStream = uno::Reference< io::XInputStream >( xPipe, uno::UNO_QUERY );
        }

        if( aParserInput.aInputStream.is() )
        {
            SvXMLGraphicHelper*                             pGraphicHelper;
            uno::Reference< container::XIndexContainer >    xGrfContainer;
            uno::Reference< xml::sax::XParser >             xParser( xXMLParser, uno::UNO_QUERY );

            if( pStorage )
            {
                pGraphicHelper = SvXMLGraphicHelper::Create( *pStorage, GRAPHICHELPER_MODE_READ );
                xGrfContainer = pGraphicHelper;
            }

            xParser->setDocumentHandler( new SdXMLImport( mxLocalModel, xGrfContainer,
                                                          bLoadDoc, nStyleFamilyMask,
                                                          mbShowProgress, IsDraw() ) );

            if( !pStorage )
                uno::Reference< io::XActiveDataControl >( xSource, uno::UNO_QUERY )->start();

            xParser->parseStream( aParserInput );

            if( pStorage )
                SvXMLGraphicHelper::Destroy( pGraphicHelper );

            bRet = TRUE;
        }
    }
    catch( xml::sax::SAXParseException )
    {
    }
    catch( xml::sax::SAXException )
    {
    }
    catch( io::IOException )
    {
    }

    return bRet;
}

// -----------------------------------------------------------------------------

BOOL SdXMLWrapper::Export()
{
    BOOL bRet = FALSE;

    if( !mxLocalModel.is() )
    {
        DBG_ERROR("Got NO Model in XMLExport");
        return FALSE;
    }

    uno::Reference< lang::XServiceInfo > xServiceInfo( mxLocalModel, uno::UNO_QUERY );

    if( !xServiceInfo.is() || !xServiceInfo->supportsService( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.drawing.DrawingDocument" ) ) ) )
    {
        DBG_ERROR( "Model is no DrawingDocument in XMLExport" );
        return FALSE;
    }

    uno::Reference< lang::XMultiServiceFactory> xServiceFactory( ::comphelper::getProcessServiceFactory() );

    if( !xServiceFactory.is() )
    {
        DBG_ERROR( "got no service manager" );
        return FALSE;
    }

    uno::Reference< uno::XInterface > xWriter( xServiceFactory->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.xml.sax.Writer" ) ) ) );

    if( !xWriter.is() )
    {
        DBG_ERROR( "com.sun.star.xml.sax.Writer service missing" );
        return FALSE;
    }

    SvStorage* pStorage = mrMedium.GetOutputStorage();

    if( pStorage )
    {
        SvStorageStreamRef  xOStm( pStorage->OpenStream( String( RTL_CONSTASCII_USTRINGPARAM( "Content" ) ),
                                                         STREAM_READ | STREAM_WRITE | STREAM_TRUNC ) );

        if( !xOStm.Is() || xOStm->GetError() )
        {
            DBG_ERROR( "Could not create output stream" );
            return FALSE;
        }

        uno::Reference< io::XActiveDataSource >     xSrc( xWriter, uno::UNO_QUERY );
        uno::Reference<xml::sax::XDocumentHandler>  xHandler( xWriter, uno::UNO_QUERY );

        xSrc->setOutputStream( new ::utl::OOutputStreamWrapper( *xOStm ) );

        try
        {
            SvXMLGraphicHelper* pGraphicHelper = SvXMLGraphicHelper::Create( *pStorage, GRAPHICHELPER_MODE_WRITE, FALSE );
            SdXMLExport         aExp( mxLocalModel, mrMedium.GetName(), xHandler, pGraphicHelper, mbShowProgress, IsDraw() );

            bRet = ( 0 == aExp.exportDoc( IsDraw() ? sXML_drawing : sXML_impress ) );

            SvXMLGraphicHelper::Destroy( pGraphicHelper );
        }
        catch( xml::sax::SAXParseException )
        {
        }
        catch( xml::sax::SAXException )
        {
        }
        catch( io::IOException )
        {
        }
    }

    return bRet;
}
<|endoftext|>


<commit_before>/// \file libuobject/main.cc

#include <libport/cstdio>
#include <libport/unistd.h>
#include <cerrno>

#include <iostream>
#include <list>
#include <sstream>

#include <libport/cli.hh>
#include <libport/containers.hh>
#include <libport/foreach.hh>
#include <libport/lexical-cast.hh>
#include <libport/package-info.hh>
#include <libport/program-name.hh>
#include <libport/sysexits.hh>

#include <urbi/package-info.hh>
#include <urbi/uexternal.hh>
#include <urbi/umain.hh>
#include <urbi/uobject.hh>
#include <urbi/usyncclient.hh>
#include <libuobject/remoteucontextimpl.hh>
using libport::program_name;

namespace urbi
{
    static impl::RemoteUContextImpl* defaultContext;

  UCallbackAction
  debug(const UMessage& msg)
  {
    msg.client.printf("DEBUG: got a message: %s\n",
                      string_cast(msg).c_str());
    return URBI_CONTINUE;
  }

  UCallbackAction
  static
  endProgram(const UMessage& msg)
  {
    msg.client.printf("ERROR: got a disconnection message: %s\n",
                      string_cast(msg).c_str());
    exit(1);
    return URBI_CONTINUE; //stupid gcc
  }

  static
  void
  usage()
  {
    std::cout <<
      "usage:\n" << libport::program_name() << " [OPTION]...\n"
      "\n"
      "Options:\n"
      "  -b, --buffer SIZE     input buffer size"
		 << " [" << UAbstractClient::URBI_BUFLEN << "]\n"
      "  -h, --help            display this message and exit\n"
      "  -H, --host ADDR       server host name"
                << " [" << UClient::DEFAULT_HOST << "]\n"
      "      --server          put remote in server mode\n"
      "  -p, --port PORT       tcp port URBI will listen to"
		 << " [" << UAbstractClient::URBI_PORT << "]\n"
      "  -r, --port-file FILE  file containing the port to listen to\n"
      "  -v, --version         print version information and exit\n"
      "  -d, --disconnect      exit program if disconnected(defaults)\n"
      "  -s, --stay-alive      do not exit program if disconnected\n"
		 << libport::exit (EX_OK);
  }

  static
  void
  version()
  {
    std::cout << urbi::package_info() << std::endl
              << libport::exit (EX_OK);
  }

  int
  initialize(const std::string& host, int port, size_t buflen,
	     bool exitOnDisconnect, bool server)
  {
    std::cerr << program_name()
	      << ": " << urbi::package_info() << std::endl
	      << program_name()
	      << ": Remote Component Running on "
	      << host << " " << port << std::endl;
              USyncClient::options o;
              o.server(server);
              new USyncClient(host, port, buflen, o);
    defaultContext = new impl::RemoteUContextImpl(
              dynamic_cast<USyncClient*>(getDefaultClient()));
    if (exitOnDisconnect)
    {
      if (!getDefaultClient() || getDefaultClient()->error())
	std::cerr << "ERROR: failed to connect, exiting..." << std::endl
		  << libport::exit(1);
      getDefaultClient()->setClientErrorCallback(callback(&endProgram));
    }
   if (!getDefaultClient() || getDefaultClient()->error())
      return 1;

#ifdef LIBURBIDEBUG
    getDefaultClient()->setWildcardCallback(callback(&debug));
#else
    getDefaultClient()->setErrorCallback(callback(&debug));
#endif

    // Wait for client to be connected if in server mode.
    while (getDefaultClient()
           && !getDefaultClient()->error()
           && !getDefaultClient()->init())
      usleep(20000);

    // Waiting for connectionID.
    while (getDefaultClient()
           && getDefaultClient()->connectionID() == "")
      usleep(5000);
    defaultContext->init();
   //baseURBIStarter::init();
    // Send a ';' since UObject likely sent a serie of piped commands.
    URBI_SEND_COMMAND("");
    return 0;
  }

  namespace
  {
    static
    void
    argument_with_option(const char* longopt,
                         char shortopt,
                         const std::string& val)
    {
      std::cerr
        << program_name()
        << ": warning: arguments without options are deprecated"
        << std::endl
        << "use `-" << shortopt << ' ' << val << '\''
        << " or `--" << longopt << ' ' << val << "' instead"
        << std::endl
        << "Try `" << program_name() << " --help' for more information."
        << std::endl;
    }

  }

  int
  main(const libport::cli_args_type& args, bool block, bool)
  {
    std::string host = UClient::DEFAULT_HOST;
    bool exitOnDisconnect = true;
    int port = UAbstractClient::URBI_PORT;
    bool server = false;
    size_t buflen = UAbstractClient::URBI_BUFLEN;

    // The number of the next (non-option) argument.
    unsigned argp = 1;
    for (unsigned i = 1; i < args.size(); ++i)
    {
      const std::string& arg = args[i];
      if (arg == "--buffer" || arg == "-b")
	buflen = libport::convert_argument<size_t>(args, i++);
      else if (arg == "--disconnect" || arg == "-d")
	exitOnDisconnect = true;
      else if (arg == "--stay-alive" || arg == "-s")
	exitOnDisconnect = false;
      else if (arg == "--help" || arg == "-h")
	usage();
      else if (arg == "--host" || arg == "-H")
	host = libport::convert_argument<std::string>(args, i++);
      else if (arg == "--port" || arg == "-p")
	port = libport::convert_argument<unsigned>(args, i++);
      else if (arg == "--port-file" || arg == "-r")
	port =
          (libport::file_contents_get<int>
           (libport::convert_argument<const char*>(args, i++)));
      else if (arg == "--server")
	server = true;
      else if (arg == "--version" || arg == "-v")
	version();
      else if (arg[0] == '-')
	libport::invalid_option(arg);
      else
	// A genuine argument.
	switch (argp++)
	{
	  case 1:
            argument_with_option("host", 'H', args[i]);
	    host = args[i];
	    break;
	  case 2:
            argument_with_option("port", 'p', args[i]);
	    port = libport::convert_argument<unsigned> ("port", args[i].c_str());
	    break;
	  default:
	    std::cerr << "unexpected argument: " << arg << std::endl
		      << libport::exit(EX_USAGE);
	}
    }

   initialize(host, port, buflen, exitOnDisconnect, server);

   if (block)
     while (true)
       usleep(30000000);
    return 0;
  }

}
<commit_msg>Urbi-launch: accept --file in remote mode.<commit_after>/// \file libuobject/main.cc

#include <libport/cstdio>
#include <libport/unistd.h>
#include <cerrno>

#include <iostream>
#include <list>
#include <sstream>

#include <libport/cli.hh>
#include <libport/containers.hh>
#include <libport/foreach.hh>
#include <libport/lexical-cast.hh>
#include <libport/package-info.hh>
#include <libport/program-name.hh>
#include <libport/sysexits.hh>

#include <urbi/package-info.hh>
#include <urbi/uexternal.hh>
#include <urbi/umain.hh>
#include <urbi/uobject.hh>
#include <urbi/usyncclient.hh>
#include <libuobject/remoteucontextimpl.hh>
using libport::program_name;

namespace urbi
{
    static impl::RemoteUContextImpl* defaultContext;

  UCallbackAction
  debug(const UMessage& msg)
  {
    msg.client.printf("DEBUG: got a message: %s\n",
                      string_cast(msg).c_str());
    return URBI_CONTINUE;
  }

  UCallbackAction
  static
  endProgram(const UMessage& msg)
  {
    msg.client.printf("ERROR: got a disconnection message: %s\n",
                      string_cast(msg).c_str());
    exit(1);
    return URBI_CONTINUE; //stupid gcc
  }

  static
  void
  usage()
  {
    std::cout <<
      "usage:\n" << libport::program_name() << " [OPTION]...\n"
      "\n"
      "Options:\n"
      "  -b, --buffer SIZE     input buffer size"
		 << " [" << UAbstractClient::URBI_BUFLEN << "]\n"
      "  -h, --help            display this message and exit\n"
      "  -H, --host ADDR       server host name"
                << " [" << UClient::DEFAULT_HOST << "]\n"
      "      --server          put remote in server mode\n"
      "  -p, --port PORT       tcp port URBI will listen to"
		 << " [" << UAbstractClient::URBI_PORT << "]\n"
      "  -r, --port-file FILE  file containing the port to listen to\n"
      "  -v, --version         print version information and exit\n"
      "  -d, --disconnect      exit program if disconnected(defaults)\n"
      "  -s, --stay-alive      do not exit program if disconnected\n"
		 << libport::exit (EX_OK);
  }

  static
  void
  version()
  {
    std::cout << urbi::package_info() << std::endl
              << libport::exit (EX_OK);
  }

  typedef std::vector<std::string> files_type;
  int
  initialize(const std::string& host, int port, size_t buflen,
	     bool exitOnDisconnect, bool server, const files_type& files)
  {
    std::cerr << program_name()
	      << ": " << urbi::package_info() << std::endl
	      << program_name()
	      << ": Remote Component Running on "
	      << host << " " << port << std::endl;
              USyncClient::options o;
              o.server(server);
              new USyncClient(host, port, buflen, o);
    defaultContext = new impl::RemoteUContextImpl(
              dynamic_cast<USyncClient*>(getDefaultClient()));
    if (exitOnDisconnect)
    {
      if (!getDefaultClient() || getDefaultClient()->error())
	std::cerr << "ERROR: failed to connect, exiting..." << std::endl
		  << libport::exit(1);
      getDefaultClient()->setClientErrorCallback(callback(&endProgram));
    }
   if (!getDefaultClient() || getDefaultClient()->error())
      return 1;

#ifdef LIBURBIDEBUG
    getDefaultClient()->setWildcardCallback(callback(&debug));
#else
    getDefaultClient()->setErrorCallback(callback(&debug));
#endif

    // Wait for client to be connected if in server mode.
    while (getDefaultClient()
           && !getDefaultClient()->error()
           && !getDefaultClient()->init())
      usleep(20000);

    // Waiting for connectionID.
    while (getDefaultClient()
           && getDefaultClient()->connectionID() == "")
      usleep(5000);
    defaultContext->init();
   //baseURBIStarter::init();
    // Send a ';' since UObject likely sent a serie of piped commands.
    URBI_SEND_COMMAND("");
    // Load initialization files.
    foreach (const std::string& file, files)
      getDefaultClient()->sendFile(file);
    return 0;
  }

  namespace
  {
    static
    void
    argument_with_option(const char* longopt,
                         char shortopt,
                         const std::string& val)
    {
      std::cerr
        << program_name()
        << ": warning: arguments without options are deprecated"
        << std::endl
        << "use `-" << shortopt << ' ' << val << '\''
        << " or `--" << longopt << ' ' << val << "' instead"
        << std::endl
        << "Try `" << program_name() << " --help' for more information."
        << std::endl;
    }

  }

  int
  main(const libport::cli_args_type& args, bool block, bool)
  {
    std::string host = UClient::DEFAULT_HOST;
    bool exitOnDisconnect = true;
    int port = UAbstractClient::URBI_PORT;
    bool server = false;
    size_t buflen = UAbstractClient::URBI_BUFLEN;
    // Files to load
    files_type files;

    // The number of the next (non-option) argument.
    unsigned argp = 1;
    for (unsigned i = 1; i < args.size(); ++i)
    {
      const std::string& arg = args[i];
      if (arg == "--buffer" || arg == "-b")
	buflen = libport::convert_argument<size_t>(args, i++);
      else if (arg == "--disconnect" || arg == "-d")
	exitOnDisconnect = true;
      else if (arg == "--file" || arg == "-f")
        files.push_back(libport::convert_argument<const char*>(args, i++));
      else if (arg == "--stay-alive" || arg == "-s")
	exitOnDisconnect = false;
      else if (arg == "--help" || arg == "-h")
	usage();
      else if (arg == "--host" || arg == "-H")
	host = libport::convert_argument<std::string>(args, i++);
      else if (arg == "--port" || arg == "-p")
	port = libport::convert_argument<unsigned>(args, i++);
      else if (arg == "--port-file" || arg == "-r")
	port =
          (libport::file_contents_get<int>
           (libport::convert_argument<const char*>(args, i++)));
      else if (arg == "--server")
	server = true;
      else if (arg == "--version" || arg == "-v")
	version();
      else if (arg[0] == '-')
	libport::invalid_option(arg);
      else
	// A genuine argument.
	switch (argp++)
	{
	  case 1:
            argument_with_option("host", 'H', args[i]);
	    host = args[i];
	    break;
	  case 2:
            argument_with_option("port", 'p', args[i]);
	    port = libport::convert_argument<unsigned> ("port", args[i].c_str());
	    break;
	  default:
	    std::cerr << "unexpected argument: " << arg << std::endl
		      << libport::exit(EX_USAGE);
	}
    }

    initialize(host, port, buflen, exitOnDisconnect, server, files);

    if (block)
      while (true)
        usleep(30000000);
    return 0;
  }

}
<|endoftext|>