<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "branchadddialog.h"
#include "ui_branchadddialog.h"

#include <utils/hostosinfo.h>

#include <QPushButton>
#include <QValidator>

namespace Git {
namespace Internal {

/*!
 * \brief The BranchNameValidator class validates the corresponding string as
 * a valid Git branch name.
 *
 * The class does this by a couple of rules that are applied on the string.
 *
 */
class BranchNameValidator : public QValidator
{
public:
    BranchNameValidator(const QStringList &localBranches, QObject *parent = 0) :
        QValidator(parent),
        m_invalidChars(QLatin1String(
                                   "\\s"          // no whitespace
                                   "|~"         // no "~"
                                   "|\\^"       // no "^"
                                   "|\\["       // no "["
                                   "|\\.\\."    // no ".."
                                   "|/\\."      // no slashdot
                                   "|:"         // no ":"
                                   "|@\\{"      // no "@{" sequence
                                   "|\\\\"      // no backslash
                                   "|//"    // no double slash
                                   "|^[/-]"  // no leading slash or dash
                                   )),
        m_localBranches(localBranches)
    {
    }

    ~BranchNameValidator() {}

    State validate(QString &input, int &pos) const
    {
        Q_UNUSED(pos)

        // NoGos

        if (input.contains(m_invalidChars))
            return Invalid;

        // "Intermediate" patterns, may change to Acceptable when user edits further:

        if (input.endsWith(QLatin1String(".lock"))) //..may not end with ".lock"
            return Intermediate;

        if (input.endsWith(QLatin1Char('.'))) // no dot at the end (but allowed in the middle)
            return Intermediate;

        if (input.endsWith(QLatin1Char('/'))) // no slash at the end (but allowed in the middle)
            return Intermediate;

        if (m_localBranches.contains(input, Utils::HostOsInfo::isWindowsHost()
                                     ? Qt::CaseInsensitive : Qt::CaseSensitive)) {
            return Intermediate;
        }

        // is a valid branch name
        return Acceptable;
    }

private:
    const QRegExp m_invalidChars;
    QStringList m_localBranches;
};

BranchAddDialog::BranchAddDialog(const QStringList &localBranches, bool addBranch, QWidget *parent) :
    QDialog(parent),
    m_ui(new Ui::BranchAddDialog)
{
    m_ui->setupUi(this);
    setWindowTitle(addBranch ? tr("Add Branch") : tr("Rename Branch"));
    m_ui->branchNameEdit->setValidator(new BranchNameValidator(localBranches, this));
    connect(m_ui->branchNameEdit, SIGNAL(textChanged(QString)), this, SLOT(updateButtonStatus()));
}

BranchAddDialog::~BranchAddDialog()
{
    delete m_ui;
}

void BranchAddDialog::setBranchName(const QString &n)
{
    m_ui->branchNameEdit->setText(n);
    m_ui->branchNameEdit->selectAll();
}

QString BranchAddDialog::branchName() const
{
    return m_ui->branchNameEdit->text();
}

void BranchAddDialog::setTrackedBranchName(const QString &name, bool remote)
{
    m_ui->trackingCheckBox->setVisible(true);
    if (!name.isEmpty()) {
        m_ui->trackingCheckBox->setText(remote ? tr("Track remote branch \'%1\'").arg(name) :
                                                 tr("Track local branch \'%1\'").arg(name));
        m_ui->trackingCheckBox->setChecked(remote);
    } else {
        m_ui->trackingCheckBox->setVisible(false);
        m_ui->trackingCheckBox->setChecked(false);
    }
}

bool BranchAddDialog::track()
{
    return m_ui->trackingCheckBox->isChecked();
}

/*! Updates the ok button enabled state of the dialog according to the validity of the branch name. */
void BranchAddDialog::updateButtonStatus()
{
    m_ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(m_ui->branchNameEdit->hasAcceptableInput());
}

} // namespace Internal
} // namespace Git
<commit_msg>Git: Fix comment indentation in BranchAddDialog<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "branchadddialog.h"
#include "ui_branchadddialog.h"

#include <utils/hostosinfo.h>

#include <QPushButton>
#include <QValidator>

namespace Git {
namespace Internal {

/*!
 * \brief The BranchNameValidator class validates the corresponding string as
 * a valid Git branch name.
 *
 * The class does this by a couple of rules that are applied on the string.
 *
 */
class BranchNameValidator : public QValidator
{
public:
    BranchNameValidator(const QStringList &localBranches, QObject *parent = 0) :
        QValidator(parent),
        m_invalidChars(QLatin1String(
                                   "\\s"     // no whitespace
                                   "|~"      // no "~"
                                   "|\\^"    // no "^"
                                   "|\\["    // no "["
                                   "|\\.\\." // no ".."
                                   "|/\\."   // no slashdot
                                   "|:"      // no ":"
                                   "|@\\{"   // no "@{" sequence
                                   "|\\\\"   // no backslash
                                   "|//"     // no double slash
                                   "|^[/-]"  // no leading slash or dash
                                   )),
        m_localBranches(localBranches)
    {
    }

    ~BranchNameValidator() {}

    State validate(QString &input, int &pos) const
    {
        Q_UNUSED(pos)

        // NoGos

        if (input.contains(m_invalidChars))
            return Invalid;

        // "Intermediate" patterns, may change to Acceptable when user edits further:

        if (input.endsWith(QLatin1String(".lock"))) //..may not end with ".lock"
            return Intermediate;

        if (input.endsWith(QLatin1Char('.'))) // no dot at the end (but allowed in the middle)
            return Intermediate;

        if (input.endsWith(QLatin1Char('/'))) // no slash at the end (but allowed in the middle)
            return Intermediate;

        if (m_localBranches.contains(input, Utils::HostOsInfo::isWindowsHost()
                                     ? Qt::CaseInsensitive : Qt::CaseSensitive)) {
            return Intermediate;
        }

        // is a valid branch name
        return Acceptable;
    }

private:
    const QRegExp m_invalidChars;
    QStringList m_localBranches;
};

BranchAddDialog::BranchAddDialog(const QStringList &localBranches, bool addBranch, QWidget *parent) :
    QDialog(parent),
    m_ui(new Ui::BranchAddDialog)
{
    m_ui->setupUi(this);
    setWindowTitle(addBranch ? tr("Add Branch") : tr("Rename Branch"));
    m_ui->branchNameEdit->setValidator(new BranchNameValidator(localBranches, this));
    connect(m_ui->branchNameEdit, SIGNAL(textChanged(QString)), this, SLOT(updateButtonStatus()));
}

BranchAddDialog::~BranchAddDialog()
{
    delete m_ui;
}

void BranchAddDialog::setBranchName(const QString &n)
{
    m_ui->branchNameEdit->setText(n);
    m_ui->branchNameEdit->selectAll();
}

QString BranchAddDialog::branchName() const
{
    return m_ui->branchNameEdit->text();
}

void BranchAddDialog::setTrackedBranchName(const QString &name, bool remote)
{
    m_ui->trackingCheckBox->setVisible(true);
    if (!name.isEmpty()) {
        m_ui->trackingCheckBox->setText(remote ? tr("Track remote branch \'%1\'").arg(name) :
                                                 tr("Track local branch \'%1\'").arg(name));
        m_ui->trackingCheckBox->setChecked(remote);
    } else {
        m_ui->trackingCheckBox->setVisible(false);
        m_ui->trackingCheckBox->setChecked(false);
    }
}

bool BranchAddDialog::track()
{
    return m_ui->trackingCheckBox->isChecked();
}

/*! Updates the ok button enabled state of the dialog according to the validity of the branch name. */
void BranchAddDialog::updateButtonStatus()
{
    m_ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(m_ui->branchNameEdit->hasAcceptableInput());
}

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


<commit_before>#include "xbl_manager.h"
#include "halley/support/logger.h"
#include "halley/text/halleystring.h"
#include <winrt/Windows.UI.Core.h>
#include <winrt/Windows.Gaming.XboxLive.Storage.h>
#include "xsapi/services.h"
#include "halley/concurrency/concurrent.h"

#include <winrt/Windows.System.UserProfile.h>

using namespace Halley;

template <typename T>
T from_cx(Platform::Object^ from)
{
    T to{ nullptr };

    winrt::check_hresult(reinterpret_cast<::IUnknown*>(from)
        ->QueryInterface(winrt::guid_of<T>(),
            reinterpret_cast<void**>(winrt::put_abi(to))));

    return to;
}

template <typename T>
T^ to_cx(winrt::Windows::Foundation::IUnknown const& from)
{
    return safe_cast<T^>(reinterpret_cast<Platform::Object^>(winrt::get_abi(from)));
}

XBLManager::XBLManager()
{

}

XBLManager::~XBLManager()
{
	deInit();
}

void XBLManager::init()
{
	signIn();
}

void XBLManager::deInit()
{
}

void XBLManager::signIn()
{
	using namespace xbox::services::system;
	xboxUser = std::make_shared<xbox_live_user>(nullptr);
	auto dispatcher = to_cx<Platform::Object>(winrt::Windows::UI::Core::CoreWindow::GetForCurrentThread().Dispatcher());

	xboxUser->signin_silently(dispatcher).then([=] (xbox::services::xbox_live_result<sign_in_result> result) -> winrt::Windows::Foundation::IAsyncAction
	{
		if (result.err()) {
			Logger::logError(String("Error signing in to Xbox Live: ") + result.err_message());
		} else {
			bool loggedIn = false;
			switch (result.payload().status()) {
			case success:
				loggedIn = true;
				break;

			case user_interaction_required:
				xboxUser->signin(dispatcher).then([&](xbox::services::xbox_live_result<sign_in_result> loudResult)
                {
                    if (!loudResult.err()) {
                        auto resPayload = loudResult.payload();
                        switch (resPayload.status()) {
                        case success:
                            loggedIn = true;
                            break;
                        case user_cancel:
                            break;
                        }
                    }
                }, concurrency::task_continuation_context::use_current());
				break;
			}

			if (loggedIn) {
				xboxLiveContext = std::make_shared<xbox::services::xbox_live_context>(xboxUser);

				xbox_live_user::add_sign_out_completed_handler([this](const sign_out_completed_event_args&)
				{
					xboxUser.reset();
					xboxLiveContext.reset();
				});
			}
		}

		co_await getConnectedStorage();
		Logger::logInfo("Storage thread done.");
	});
}

winrt::Windows::Foundation::IAsyncAction XBLManager::getConnectedStorage()
{
	using namespace winrt::Windows::Gaming::XboxLive::Storage;

	auto windowsUser = co_await winrt::Windows::System::User::FindAllAsync();

	//auto user = from_cx<winrt::Windows::System::User>(windowsUser.First());
	GameSaveProviderGetResult result = co_await GameSaveProvider::GetForUserAsync(*windowsUser.First(), xboxLiveContext->application_config()->scid());

	if (result.Status() == GameSaveErrorStatus::Ok) {
		gameSaveProvider = result.Value();
		Logger::logInfo("Got game save provider");
	}
}
<commit_msg>aaaaaaaaahhh<commit_after>#include "xbl_manager.h"
#include "halley/support/logger.h"
#include "halley/text/halleystring.h"
#include <winrt/Windows.UI.Core.h>
#include <winrt/Windows.Gaming.XboxLive.Storage.h>
#include "xsapi/services.h"
#include "halley/concurrency/concurrent.h"

#include <winrt/Windows.System.UserProfile.h>

using namespace Halley;

template <typename T>
T from_cx(Platform::Object^ from)
{
    T to{ nullptr };

    winrt::check_hresult(reinterpret_cast<::IUnknown*>(from)
        ->QueryInterface(winrt::guid_of<T>(),
            reinterpret_cast<void**>(winrt::put_abi(to))));

    return to;
}

template <typename T>
T^ to_cx(winrt::Windows::Foundation::IUnknown const& from)
{
    return safe_cast<T^>(reinterpret_cast<Platform::Object^>(winrt::get_abi(from)));
}

XBLManager::XBLManager()
{

}

XBLManager::~XBLManager()
{
	deInit();
}

void XBLManager::init()
{
	signIn();
}

void XBLManager::deInit()
{
}

void XBLManager::signIn()
{
	using namespace xbox::services::system;
	xboxUser = std::make_shared<xbox_live_user>(nullptr);
	auto dispatcher = to_cx<Platform::Object>(winrt::Windows::UI::Core::CoreWindow::GetForCurrentThread().Dispatcher());

	xboxUser->signin_silently(dispatcher).then([=] (xbox::services::xbox_live_result<sign_in_result> result) -> winrt::Windows::Foundation::IAsyncAction
	{
		if (result.err()) {
			Logger::logError(String("Error signing in to Xbox Live: ") + result.err_message());
		} else {
			bool loggedIn = false;
			switch (result.payload().status()) {
			case success:
				loggedIn = true;
				break;

			case user_interaction_required:
				xboxUser->signin(dispatcher).then([&](xbox::services::xbox_live_result<sign_in_result> loudResult)
                {
                    if (!loudResult.err()) {
                        auto resPayload = loudResult.payload();
                        switch (resPayload.status()) {
                        case success:
                            loggedIn = true;
                            break;
                        case user_cancel:
                            break;
                        }
                    }
                }, concurrency::task_continuation_context::use_current());
				break;
			}

			if (loggedIn) {
				xboxLiveContext = std::make_shared<xbox::services::xbox_live_context>(xboxUser);

				xbox_live_user::add_sign_out_completed_handler([this](const sign_out_completed_event_args&)
				{
					xboxUser.reset();
					xboxLiveContext.reset();
				});
			}
		}

		co_await getConnectedStorage();
		Logger::logInfo("Storage thread done.");
	});
}

winrt::Windows::Foundation::IAsyncAction XBLManager::getConnectedStorage()
{
	using namespace winrt::Windows::Gaming::XboxLive::Storage;

	auto windowsUser = co_await winrt::Windows::System::User::FindAllAsync();

	//auto user = from_cx<winrt::Windows::System::User>(windowsUser.First());
	GameSaveProviderGetResult result = co_await GameSaveProvider::GetForUserAsync(*windowsUser.First(), xboxLiveContext->application_config()->scid());

	if (result.Status() == GameSaveErrorStatus::Ok) {
		gameSaveProvider = result.Value();
		Logger::logInfo("Got game save provider");

		auto container = gameSaveProvider.get().CreateContainer(L"save");

		auto dataWriter = winrt::Windows::Storage::Streams::DataWriter();
		//dataWriter.WriteBytes()
		auto buffer = dataWriter.DetachBuffer();
		auto updates = std::map<winrt::hstring, winrt::Windows::Storage::Streams::IBuffer>();
		//auto view = winrt::param::async_map_view<winrt::hstring, winrt::Windows::Storage::Streams::IBuffer>(updates);

		//container.SubmitUpdatesAsync(view);
	}
}
<|endoftext|>


<commit_before>/**
 * @file
 *
 * @brief Source for yamlsmith plugin
 *
 * @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
 *
 */

// -- Imports ------------------------------------------------------------------------------------------------------------------------------

#include <fstream>
#include <iostream>

#include "yamlsmith.hpp"

#include <kdb.hpp>
#include <kdbease.h>
#include <kdberrors.h>

using std::endl;
using std::ofstream;
using std::string;

using ckdb::Key;
using ckdb::KeySet;

using ckdb::elektraKeyGetRelativeName;
using ckdb::keyNew;

using CppKey = kdb::Key;
using CppKeySet = kdb::KeySet;
using NameIterator = kdb::NameIterator;

// -- Functions ----------------------------------------------------------------------------------------------------------------------------

namespace
{

/**
 * @brief This function returns a key set containing the contract of the plugin.
 *
 * @return A contract describing the functionality of this plugin
 */
CppKeySet contractYamlsmith ()
{
	return CppKeySet (30, keyNew ("system/elektra/modules/yamlsmith", KEY_VALUE, "yamlsmith plugin waits for your orders", KEY_END),
			  keyNew ("system/elektra/modules/yamlsmith/exports", KEY_END),
			  keyNew ("system/elektra/modules/yamlsmith/exports/get", KEY_FUNC, elektraYamlsmithGet, KEY_END),
			  keyNew ("system/elektra/modules/yamlsmith/exports/set", KEY_FUNC, elektraYamlsmithSet, KEY_END),
#include ELEKTRA_README (yamlsmith)
			  keyNew ("system/elektra/modules/yamlsmith/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END);
}

/**
 * @brief This class provides additional functionality for the keys.
 */
class CppKeyPlus : public CppKey
{
public:
	/**
	 * @copydoc Key::Key(Key &)
	 */
	CppKeyPlus (kdb::Key const & other) : CppKey (other)
	{
	}

	/**
	 * @brief This function returns a `NameIterator` starting at the first level that is not part of `parent`.
	 *
	 * @pre This key must be a child of `parent`.
	 *
	 * @param parent This key specifies the part of the name iterator that will not be part of the return value of this function.
	 *
	 * @returns A relative iterator that starts with the first part of the name of `key` not contained in `parent`.
	 */
	NameIterator relativeKeyIterator (Key const & parent)
	{
		auto parentIterator = parent.begin ();
		auto keyIterator = this->begin ();
		while (parentIterator != parent.end () && keyIterator != this->end ())
		{
			parentIterator++;
			keyIterator++;
		}
		return keyIterator;
	}
};

/**
 * @brief This class provides additional functionality for the key set class.
 */
class CppKeySetPlus : public CppKeySet
{
public:
	/**
	 * @copydoc KeySet::KeySet(ckdb::KeySet)
	 */
	CppKeySetPlus (ckdb::KeySet * keys) : CppKeySet (keys)
	{
	}

	/**
	 * @brief Collect leaf keys (keys without any key below) for this key set.
	 *
	 * @return A key set containing all leaf keys
	 */
	CppKeySet leaves ()
	{
		CppKeySet leaves;

		auto current = this->begin ();
		if (current == this->end ()) return leaves;

		CppKey previous = *current;
		while (++current != this->end ())
		{
			bool isLeaf = !current->isBelow (previous);
			if (isLeaf)
			{
				leaves.append (previous);
			}

			previous = *current;
		}
		// The last key is always a leaf
		leaves.append (previous);

		return leaves;
	}
};

} // end namespace

extern "C" {
// ====================
// = Plugin Interface =
// ====================

/** @see elektraDocGet */
int elektraYamlsmithGet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned, Key * parentKey)
{
	CppKey parent{ parentKey };
	CppKeySet keys{ returned };

	if (parent.getName () == "system/elektra/modules/yamlsmith")
	{
		keys.append (contractYamlsmith ());
		parent.release ();
		keys.release ();

		return ELEKTRA_PLUGIN_STATUS_SUCCESS;
	}

	parent.release ();

	return ELEKTRA_PLUGIN_STATUS_NO_UPDATE;
}

/** @see elektraDocSet */
int elektraYamlsmithSet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned, Key * parentKey)
{
	CppKey parent{ parentKey };
	CppKeySetPlus keys{ returned };

	ofstream file{ parent.getString () };
	if (file.is_open ())
	{
		for (auto key : keys.leaves ())
		{
			string indent;
			CppKeyPlus plus{ *key };
			auto relative = plus.relativeKeyIterator (parent);
			while (relative != plus.end ())
			{
				file << indent << *relative << ":" << endl;
				relative++;
				indent += "  ";
			}
			file << indent << plus.getString () << endl;
		}
	}
	else
	{
		ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_COULD_NOT_OPEN, parent.getKey (), "Unable to open file “%s”",
				    parent.getString ().c_str ());
	}

	parent.release ();
	keys.release ();

	return ELEKTRA_PLUGIN_STATUS_SUCCESS;
}

Plugin * ELEKTRA_PLUGIN_EXPORT (yamlsmith)
{
	return elektraPluginExport ("yamlsmith", ELEKTRA_PLUGIN_GET, &elektraYamlsmithGet, ELEKTRA_PLUGIN_SET, &elektraYamlsmithSet,
				    ELEKTRA_PLUGIN_END);
}

} // end extern "C"
<commit_msg>YAML Smith: Use function for relative iterator<commit_after>/**
 * @file
 *
 * @brief Source for yamlsmith plugin
 *
 * @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
 *
 */

// -- Imports ------------------------------------------------------------------------------------------------------------------------------

#include <fstream>
#include <iostream>

#include "yamlsmith.hpp"

#include <kdb.hpp>
#include <kdbease.h>
#include <kdberrors.h>

using std::endl;
using std::ofstream;
using std::string;

using ckdb::Key;
using ckdb::KeySet;

using ckdb::elektraKeyGetRelativeName;
using ckdb::keyNew;

using CppKey = kdb::Key;
using CppKeySet = kdb::KeySet;
using NameIterator = kdb::NameIterator;

// -- Functions ----------------------------------------------------------------------------------------------------------------------------

namespace
{

/**
 * @brief This function returns a key set containing the contract of the plugin.
 *
 * @return A contract describing the functionality of this plugin
 */
CppKeySet contractYamlsmith ()
{
	return CppKeySet (30, keyNew ("system/elektra/modules/yamlsmith", KEY_VALUE, "yamlsmith plugin waits for your orders", KEY_END),
			  keyNew ("system/elektra/modules/yamlsmith/exports", KEY_END),
			  keyNew ("system/elektra/modules/yamlsmith/exports/get", KEY_FUNC, elektraYamlsmithGet, KEY_END),
			  keyNew ("system/elektra/modules/yamlsmith/exports/set", KEY_FUNC, elektraYamlsmithSet, KEY_END),
#include ELEKTRA_README (yamlsmith)
			  keyNew ("system/elektra/modules/yamlsmith/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END);
}

/**
 * @brief This function returns a `NameIterator` starting at the first level that is not part of `parent`.
 *
 * @pre The parameter `key` must be a child of `parent`.
 *
 * @param key This is the key for which this function returns a relative iterator.
 * @param parent This key specifies the part of the name iterator that will not be part of the return value of this function.
 *
 * @returns A relative iterator that starts with the first part of the name of `key` not contained in `parent`.
 */
NameIterator relativeKeyIterator (CppKey const & key, CppKey const & parent)
{
	auto parentIterator = parent.begin ();
	auto keyIterator = key.begin ();
	while (parentIterator != parent.end () && keyIterator != key.end ())
	{
		parentIterator++;
		keyIterator++;
	}
	return keyIterator;
}

/**
 * @brief This class provides additional functionality for the key set class.
 */
class CppKeySetPlus : public CppKeySet
{
public:
	/**
	 * @copydoc KeySet::KeySet(ckdb::KeySet)
	 */
	CppKeySetPlus (ckdb::KeySet * keys) : CppKeySet (keys)
	{
	}

	/**
	 * @brief Collect leaf keys (keys without any key below) for this key set.
	 *
	 * @return A key set containing all leaf keys
	 */
	CppKeySet leaves ()
	{
		CppKeySet leaves;

		auto current = this->begin ();
		if (current == this->end ()) return leaves;

		CppKey previous = *current;
		while (++current != this->end ())
		{
			bool isLeaf = !current->isBelow (previous);
			if (isLeaf)
			{
				leaves.append (previous);
			}

			previous = *current;
		}
		// The last key is always a leaf
		leaves.append (previous);

		return leaves;
	}
};

} // end namespace

extern "C" {
// ====================
// = Plugin Interface =
// ====================

/** @see elektraDocGet */
int elektraYamlsmithGet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned, Key * parentKey)
{
	CppKey parent{ parentKey };
	CppKeySet keys{ returned };

	if (parent.getName () == "system/elektra/modules/yamlsmith")
	{
		keys.append (contractYamlsmith ());
		parent.release ();
		keys.release ();

		return ELEKTRA_PLUGIN_STATUS_SUCCESS;
	}

	parent.release ();

	return ELEKTRA_PLUGIN_STATUS_NO_UPDATE;
}

/** @see elektraDocSet */
int elektraYamlsmithSet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned, Key * parentKey)
{
	CppKey parent{ parentKey };
	CppKeySetPlus keys{ returned };

	ofstream file{ parent.getString () };
	if (file.is_open ())
	{
		for (auto key : keys.leaves ())
		{
			string indent;
			auto relative = relativeKeyIterator (*key, parent);
			while (relative != key.end ())
			{
				file << indent << *relative << ":" << endl;
				relative++;
				indent += "  ";
			}
			file << indent << key.getString () << endl;
		}
	}
	else
	{
		ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_COULD_NOT_OPEN, parent.getKey (), "Unable to open file “%s”",
				    parent.getString ().c_str ());
	}

	parent.release ();
	keys.release ();

	return ELEKTRA_PLUGIN_STATUS_SUCCESS;
}

Plugin * ELEKTRA_PLUGIN_EXPORT (yamlsmith)
{
	return elektraPluginExport ("yamlsmith", ELEKTRA_PLUGIN_GET, &elektraYamlsmithGet, ELEKTRA_PLUGIN_SET, &elektraYamlsmithSet,
				    ELEKTRA_PLUGIN_END);
}

} // end extern "C"
<|endoftext|>


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

#ifndef SD_PRESENTATION_VIEW_SHELL_BASE_HXX
#define SD_PRESENTATION_VIEW_SHELL_BASE_HXX

#include "ViewShellBase.hxx"

namespace sd {

/** This class exists to be able to register another factory that
    creates the view shell for the presentation.
*/
class PresentationViewShellBase
    : public ViewShellBase
{
public:
    TYPEINFO();
    SFX_DECL_VIEWFACTORY(PresentationViewShellBase);

    /** This constructor is used by the view factory of the SFX
        macros.
    */
    PresentationViewShellBase (SfxViewFrame *pFrame, SfxViewShell* pOldShell);
    virtual ~PresentationViewShellBase (void);

    /** We delete the ViewTabBar that is not needed for the presentation.
    */
    virtual void LateInit (void);
};

} // end of namespace sd

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

#ifndef SD_PRESENTATION_VIEW_SHELL_BASE_HXX
#define SD_PRESENTATION_VIEW_SHELL_BASE_HXX

#include "ViewShellBase.hxx"

namespace sd {

/** This class exists to be able to register another factory that
    creates the view shell for the presentation.
*/
class PresentationViewShellBase
    : public ViewShellBase
{
public:
    TYPEINFO();
    SFX_DECL_VIEWFACTORY(PresentationViewShellBase);

    /** This constructor is used by the view factory of the SFX
        macros.
    */
    PresentationViewShellBase (SfxViewFrame *pFrame, SfxViewShell* pOldShell);
    virtual ~PresentationViewShellBase (void);

    /** We delete the ViewTabBar that is not needed for the presentation.
    */
    virtual void LateInit (void);
};

} // end of namespace sd

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: BResultSetMetaData.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 05:23:40 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_ADABAS_BRESULTSETMETADATA_HXX_
#include "adabas/BResultSetMetaData.hxx"
#endif
#ifndef _CONNECTIVITY_ADABAS_CATALOG_HXX_
#include "adabas/BCatalog.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_
#include <com/sun/star/sdbc/DataType.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif

using namespace com::sun::star::sdbc;
using namespace com::sun::star::uno;
using namespace connectivity::adabas;
using namespace connectivity;

OAdabasResultSetMetaData::OAdabasResultSetMetaData(odbc::OConnection*   _pConnection, SQLHANDLE _pStmt,const ::vos::ORef<OSQLColumns>& _rSelectColumns )
: OAdabasResultSetMetaData_BASE(_pConnection,_pStmt)
,m_aSelectColumns(_rSelectColumns)
{
}
// -----------------------------------------------------------------------------
OAdabasResultSetMetaData::OAdabasResultSetMetaData(odbc::OConnection*   _pConnection, SQLHANDLE _pStmt ,const ::std::vector<sal_Int32> & _vMapping)
: OAdabasResultSetMetaData_BASE(_pConnection,_pStmt,_vMapping)
{
}
// -------------------------------------------------------------------------
OAdabasResultSetMetaData::~OAdabasResultSetMetaData()
{
}
// -----------------------------------------------------------------------------
sal_Int32 SAL_CALL OAdabasResultSetMetaData::getColumnType( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    sal_Int32 nType = OAdabasResultSetMetaData_BASE::getColumnType( column);
    // special handling for float values which could be doubles
    ::rtl::OUString sTypeName;
    OAdabasCatalog::correctColumnProperties(getPrecision(column),nType,sTypeName);

    return nType;
}
// -----------------------------------------------------------------------------
sal_Int32 SAL_CALL OAdabasResultSetMetaData::isNullable( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    sal_Int32 nValue = 0;
    sal_Bool bFound = sal_False;
    if ( m_aSelectColumns.isValid() && column > 0 && column <= m_aSelectColumns->size() )
        bFound = (*m_aSelectColumns)[column-1]->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISNULLABLE)) >>= nValue;

    if ( !bFound )
        nValue = getNumColAttrib(column,SQL_DESC_NULLABLE);
    return nValue;
}
// -------------------------------------------------------------------------

<commit_msg>INTEGRATION: CWS warnings01 (1.6.30); FILE MERGED 2005/11/07 14:43:02 fs 1.6.30.1: #i57457# warning-free code<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: BResultSetMetaData.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 01:10:30 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_ADABAS_BRESULTSETMETADATA_HXX_
#include "adabas/BResultSetMetaData.hxx"
#endif
#ifndef _CONNECTIVITY_ADABAS_CATALOG_HXX_
#include "adabas/BCatalog.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_
#include <com/sun/star/sdbc/DataType.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif

using namespace com::sun::star::sdbc;
using namespace com::sun::star::uno;
using namespace connectivity::adabas;
using namespace connectivity;

OAdabasResultSetMetaData::OAdabasResultSetMetaData(odbc::OConnection*   _pConnection, SQLHANDLE _pStmt,const ::vos::ORef<OSQLColumns>& _rSelectColumns )
: OAdabasResultSetMetaData_BASE(_pConnection,_pStmt)
,m_aSelectColumns(_rSelectColumns)
{
}
// -----------------------------------------------------------------------------
OAdabasResultSetMetaData::OAdabasResultSetMetaData(odbc::OConnection*   _pConnection, SQLHANDLE _pStmt ,const ::std::vector<sal_Int32> & _vMapping)
: OAdabasResultSetMetaData_BASE(_pConnection,_pStmt,_vMapping)
{
}
// -------------------------------------------------------------------------
OAdabasResultSetMetaData::~OAdabasResultSetMetaData()
{
}
// -----------------------------------------------------------------------------
sal_Int32 SAL_CALL OAdabasResultSetMetaData::getColumnType( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    sal_Int32 nType = OAdabasResultSetMetaData_BASE::getColumnType( column);
    // special handling for float values which could be doubles
    ::rtl::OUString sTypeName;
    OAdabasCatalog::correctColumnProperties(getPrecision(column),nType,sTypeName);

    return nType;
}
// -----------------------------------------------------------------------------
sal_Int32 SAL_CALL OAdabasResultSetMetaData::isNullable( sal_Int32 column ) throw(SQLException, RuntimeException)
{
    sal_Int32 nValue = 0;
    sal_Bool bFound = sal_False;
    if ( m_aSelectColumns.isValid() && column > 0 && column <= (sal_Int32)m_aSelectColumns->size() )
        bFound = (*m_aSelectColumns)[column-1]->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISNULLABLE)) >>= nValue;

    if ( !bFound )
        nValue = getNumColAttrib(column,SQL_DESC_NULLABLE);
    return nValue;
}
// -------------------------------------------------------------------------

<|endoftext|>


<commit_before>// Copyright (C) 2013 Jérôme Leclercq
// This file is part of the "Nazara Engine - Audio module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Audio/Loaders/sndfile.hpp>
#include <Nazara/Audio/Audio.hpp>
#include <Nazara/Audio/SoundBuffer.hpp>
#include <Nazara/Core/Endianness.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/File.hpp>
#include <Nazara/Core/InputStream.hpp>
#include <Nazara/Core/MemoryStream.hpp>
#include <sndfile/sndfile.h>
#include <Nazara/Audio/Debug.hpp>

namespace
{
	sf_count_t GetSize(void* user_data)
	{
        NzInputStream* stream = static_cast<NzInputStream*>(user_data);
		return stream->GetSize();
	}

    sf_count_t Read(void* ptr, sf_count_t count, void* user_data)
    {
        NzInputStream* stream = static_cast<NzInputStream*>(user_data);
        return stream->Read(ptr, count);
    }

    sf_count_t Seek(sf_count_t offset, int whence, void* user_data)
    {
        NzInputStream* stream = static_cast<NzInputStream*>(user_data);
        switch (whence)
        {
			case SEEK_CUR:
				stream->Read(nullptr, offset);
				break;

			case SEEK_END:
				stream->SetCursorPos(stream->GetSize() + offset); // L'offset est négatif ici
				break;

			case SEEK_SET:
				stream->SetCursorPos(offset);
				break;

			default:
				NazaraInternalError("Seek mode not handled");
        }

        return stream->GetCursorPos();
    }

    sf_count_t Tell(void* user_data)
    {
        NzInputStream* stream = reinterpret_cast<NzInputStream*>(user_data);
        return stream->GetCursorPos();
    }

	static SF_VIRTUAL_IO callbacks = {GetSize, Seek, Read, nullptr, Tell};

	bool NzLoader_sndfile_Check(NzInputStream& stream, const NzSoundBufferParams& parameters)
	{
		NazaraUnused(parameters);

		SF_INFO info;
		SNDFILE* file = sf_open_virtual(&callbacks, SFM_READ, &info, &stream);
		if (file)
		{
			sf_close(file);
			return true;
		}
		else
			return false;
	}

	bool NzLoader_sndfile_Load(NzSoundBuffer* soundBuffer, NzInputStream& stream, const NzSoundBufferParams& parameters)
	{
		NazaraUnused(parameters);

		SF_INFO infos;
		SNDFILE* file = sf_open_virtual(&callbacks, SFM_READ, &infos, &stream);
		if (!file)
		{
			NazaraError("Failed to load sound file: " + NzString(sf_strerror(file)));
			return false;
		}

		nzAudioFormat format = NzAudio::GetAudioFormat(infos.channels);
		if (format == nzAudioFormat_Unknown)
		{
			NazaraError("Channel count not handled");
			sf_close(file);

			return false;
		}

		// https://github.com/LaurentGomila/SFML/issues/271
		// http://www.mega-nerd.com/libsndfile/command.html#SFC_SET_SCALE_FLOAT_INT_READ
		///FIXME: Seulement le Vorbis ?
		if (infos.format & SF_FORMAT_VORBIS)
			sf_command(file, SFC_SET_SCALE_FLOAT_INT_READ, nullptr, SF_TRUE);

		unsigned int sampleCount = infos.frames*infos.channels;
		nzInt16* samples = new nzInt16[sampleCount];
		if (sf_read_short(file, samples, sampleCount) != sampleCount)
		{
			NazaraError("Failed to read samples");

			delete[] samples;
			sf_close(file);

			return false;
		}

		if (!soundBuffer->Create(format, infos.frames*infos.channels, infos.samplerate, samples))
		{
			NazaraError("Failed to create sound buffer");

			delete[] samples;
			sf_close(file);

			return false;
		}

		delete[] samples;

		return true;
	}
}

void NzLoaders_sndfile_Register()
{
	NzSoundBufferLoader::RegisterLoader("aiff,au,avr,caf,flac,htk,ircam,mat4,mat5,mpc2k,nist,ogg,paf,pvf,raw,rf64,sd2,sds,svx,voc,w64,wav,wve",
	                                    NzLoader_sndfile_Check, NzLoader_sndfile_Load);
}

void NzLoaders_sndfile_Unregister()
{
	NzSoundBufferLoader::UnregisterLoader("aiff,au,avr,caf,flac,htk,ircam,mat4,mat5,mpc2k,nist,ogg,paf,pvf,raw,rf64,sd2,sds,svx,voc,w64,wav,wve",
	                                      NzLoader_sndfile_Check, NzLoader_sndfile_Load);
}
<commit_msg>Fixed audio module not building<commit_after>// Copyright (C) 2013 Jérôme Leclercq
// This file is part of the "Nazara Engine - Audio module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Audio/Loaders/sndfile.hpp>
#include <Nazara/Audio/Audio.hpp>
#include <Nazara/Audio/SoundBuffer.hpp>
#include <Nazara/Core/Endianness.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/File.hpp>
#include <Nazara/Core/InputStream.hpp>
#include <Nazara/Core/MemoryStream.hpp>
#include <sndfile/sndfile.h>
#include <Nazara/Audio/Debug.hpp>

namespace
{
	sf_count_t GetSize(void* user_data)
	{
        NzInputStream* stream = static_cast<NzInputStream*>(user_data);
		return stream->GetSize();
	}

    sf_count_t Read(void* ptr, sf_count_t count, void* user_data)
    {
        NzInputStream* stream = static_cast<NzInputStream*>(user_data);
        return stream->Read(ptr, count);
    }

    sf_count_t Seek(sf_count_t offset, int whence, void* user_data)
    {
        NzInputStream* stream = static_cast<NzInputStream*>(user_data);
        switch (whence)
        {
			case SEEK_CUR:
				stream->Read(nullptr, offset);
				break;

			case SEEK_END:
				stream->SetCursorPos(stream->GetSize() + offset); // L'offset est négatif ici
				break;

			case SEEK_SET:
				stream->SetCursorPos(offset);
				break;

			default:
				NazaraInternalError("Seek mode not handled");
        }

        return stream->GetCursorPos();
    }

    sf_count_t Tell(void* user_data)
    {
        NzInputStream* stream = reinterpret_cast<NzInputStream*>(user_data);
        return stream->GetCursorPos();
    }

	static SF_VIRTUAL_IO callbacks = {GetSize, Seek, Read, nullptr, Tell};

	bool IsSupported(const NzString& extension)
	{
		static std::set<NzString> supportedExtensions = {
			"aiff", "au", "avr", "caf", "flac", "htk", "ircam", "mat4", "mat5", "mpc2k",
			"nist","ogg", "pvf", "raw", "rf64", "sd2", "sds", "svx", "voc", "w64", "wav", "wve"
		};

		return supportedExtensions.find(extension) != supportedExtensions.end();
	}

	bool Check(NzInputStream& stream, const NzSoundBufferParams& parameters)
	{
		NazaraUnused(parameters);

		SF_INFO info;
		SNDFILE* file = sf_open_virtual(&callbacks, SFM_READ, &info, &stream);
		if (file)
		{
			sf_close(file);
			return true;
		}
		else
			return false;
	}

	bool Load(NzSoundBuffer* soundBuffer, NzInputStream& stream, const NzSoundBufferParams& parameters)
	{
		NazaraUnused(parameters);

		SF_INFO infos;
		SNDFILE* file = sf_open_virtual(&callbacks, SFM_READ, &infos, &stream);
		if (!file)
		{
			NazaraError("Failed to load sound file: " + NzString(sf_strerror(file)));
			return false;
		}

		nzAudioFormat format = NzAudio::GetAudioFormat(infos.channels);
		if (format == nzAudioFormat_Unknown)
		{
			NazaraError("Channel count not handled");
			sf_close(file);

			return false;
		}

		// https://github.com/LaurentGomila/SFML/issues/271
		// http://www.mega-nerd.com/libsndfile/command.html#SFC_SET_SCALE_FLOAT_INT_READ
		///FIXME: Seulement le Vorbis ?
		if (infos.format & SF_FORMAT_VORBIS)
			sf_command(file, SFC_SET_SCALE_FLOAT_INT_READ, nullptr, SF_TRUE);

		unsigned int sampleCount = infos.frames*infos.channels;
		nzInt16* samples = new nzInt16[sampleCount];
		if (sf_read_short(file, samples, sampleCount) != sampleCount)
		{
			NazaraError("Failed to read samples");

			delete[] samples;
			sf_close(file);

			return false;
		}

		if (!soundBuffer->Create(format, infos.frames*infos.channels, infos.samplerate, samples))
		{
			NazaraError("Failed to create sound buffer");

			delete[] samples;
			sf_close(file);

			return false;
		}

		delete[] samples;

		return true;
	}
}

void NzLoaders_sndfile_Register()
{
	NzSoundBufferLoader::RegisterLoader(IsSupported, Check, Load);
}

void NzLoaders_sndfile_Unregister()
{
	NzSoundBufferLoader::UnregisterLoader(IsSupported, Check, Load);
}
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2011 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id: datasource_cache.cpp 23 2005-03-22 22:16:34Z pavlenko $

// mapnik
#include <mapnik/datasource_cache.hpp>

#include <mapnik/config_error.hpp>

// boost
#include <boost/version.hpp>
#include <boost/make_shared.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/algorithm/string.hpp>

// ltdl
#include <ltdl.h>

// stl
#include <algorithm>
#include <iostream>
#include <stdexcept>

namespace mapnik
{

bool is_input_plugin (std::string const& filename)
{
    return boost::algorithm::ends_with(filename,std::string(".input"));
}

datasource_cache::datasource_cache()
{
    if (lt_dlinit()) throw std::runtime_error("lt_dlinit() failed");
}

datasource_cache::~datasource_cache()
{
    lt_dlexit();
}

std::map<std::string,boost::shared_ptr<PluginInfo> > datasource_cache::plugins_;
bool datasource_cache::registered_=false;
std::vector<std::string> datasource_cache::plugin_directories_;

datasource_ptr datasource_cache::create(const parameters& params, bool bind)
{
    boost::optional<std::string> type = params.get<std::string>("type");
    if ( ! type)
    {
        throw config_error(std::string("Could not create datasource. Required ") +
                           "parameter 'type' is missing");
    }

#ifdef MAPNIK_THREADSAFE
    mutex::scoped_lock lock(mutex_);
#endif
    datasource_ptr ds;
    std::map<std::string,boost::shared_ptr<PluginInfo> >::iterator itr=plugins_.find(*type);
    if ( itr == plugins_.end() )
    {
        throw config_error(std::string("Could not create datasource. No plugin ") +
                           "found for type '" + * type + "' (searched in: " + plugin_directories() + ")");
    }
    if ( ! itr->second->handle())
    {
        throw std::runtime_error(std::string("Cannot load library: ") +
                                 lt_dlerror());
    }
    // http://www.mr-edd.co.uk/blog/supressing_gcc_warnings
    #ifdef __GNUC__
    __extension__
    #endif
    create_ds* create_datasource =
        reinterpret_cast<create_ds*>(lt_dlsym(itr->second->handle(), "create"));

    if ( ! create_datasource)
    {
        throw std::runtime_error(std::string("Cannot load symbols: ") +
                                 lt_dlerror());
    }
#ifdef MAPNIK_DEBUG
    std::clog << "size = " << params.size() << "\n";
    parameters::const_iterator i = params.begin();
    for (;i!=params.end();++i)
    {
        std::clog << i->first << "=" << i->second << "\n";
    }
#endif
    ds=datasource_ptr(create_datasource(params, bind), datasource_deleter());

#ifdef MAPNIK_DEBUG
    std::clog<<"datasource="<<ds<<" type="<<type<<std::endl;
#endif
    return ds;
}

bool datasource_cache::insert(const std::string& type,const lt_dlhandle module)
{
    return plugins_.insert(make_pair(type,boost::make_shared<PluginInfo>
                                     (type,module))).second;
}

std::string datasource_cache::plugin_directories()
{
    return boost::algorithm::join(plugin_directories_,", ");
}

std::vector<std::string> datasource_cache::plugin_names ()
{
    std::vector<std::string> names;
    std::map<std::string,boost::shared_ptr<PluginInfo> >::const_iterator itr;
    for (itr = plugins_.begin();itr!=plugins_.end();++itr)
    {
        names.push_back(itr->first);
    }
    return names;
}

void datasource_cache::register_datasources(const std::string& str)
{
#ifdef MAPNIK_THREADSAFE
    mutex::scoped_lock lock(mapnik::singleton<mapnik::datasource_cache,
                            mapnik::CreateStatic>::mutex_);
#endif
    boost::filesystem::path path(str);
    plugin_directories_.push_back(str);
    boost::filesystem::directory_iterator end_itr;

    if (exists(path) && is_directory(path))
    {
        for (boost::filesystem::directory_iterator itr(path);itr!=end_itr;++itr )
        {

#if BOOST_VERSION < 103400
            if (!is_directory( *itr )  && is_input_plugin(itr->leaf()))
#else
#if (BOOST_FILESYSTEM_VERSION == 3)
            if (!is_directory( *itr )  && is_input_plugin(itr->path().filename().string()))
#else // v2
            if (!is_directory( *itr )  && is_input_plugin(itr->path().leaf()))
#endif
#endif
            {
                try
                {
#ifdef LIBTOOL_SUPPORTS_ADVISE
                    /* Note: the below was added as a workaround pre http://trac.mapnik.org/ticket/790
                       It could now be removed, but also is not doing any harm AFAICT.
                    */

                    // with ltdl >=2.2 we can actually pass RTDL_GLOBAL to dlopen via the
                    // ltdl advise trick which is required on linux unless plugins are directly
                    // linked to libmapnik (and deps) at build time. The only other approach is to
                    // set the dlopen flags in the calling process (like in the python bindings)

                    // clear errors
                    lt_dlerror();

                    lt_dlhandle module = 0;
                    lt_dladvise advise;
                    int ret;

                    ret = lt_dlinit();
                    if (ret != 0) {
                        std::clog << "Datasource loader: could not intialize dynamic loading: " << lt_dlerror() << "\n";
                    }

                    ret = lt_dladvise_init(&advise);
                    if (ret != 0) {
                        std::clog << "Datasource loader: could not intialize dynamic loading: " << lt_dlerror() << "\n";
                    }

                    ret = lt_dladvise_global(&advise);
                    if (ret != 0) {
                        std::clog << "Datasource loader: could not intialize dynamic loading of global symbols: " << lt_dlerror() << "\n";
                    }
#if (BOOST_FILESYSTEM_VERSION == 3)
                    module = lt_dlopenadvise (itr->path().string().c_str(), advise);
#else // v2
                    module = lt_dlopenadvise (itr->string().c_str(), advise);
#endif

                    lt_dladvise_destroy(&advise);
#else

#if (BOOST_FILESYSTEM_VERSION == 3)
                    lt_dlhandle module = lt_dlopen(itr->path().string().c_str());
#else // v2
                    lt_dlhandle module = lt_dlopen(itr->string().c_str());
#endif

#endif
                    if (module)
                    {
                        // http://www.mr-edd.co.uk/blog/supressing_gcc_warnings
                        #ifdef __GNUC__
                        __extension__
                        #endif
                        datasource_name* ds_name =
                            reinterpret_cast<datasource_name*>(lt_dlsym(module, "datasource_name"));
                        if (ds_name && insert(ds_name(),module))
                        {
#ifdef MAPNIK_DEBUG
                            std::clog << "Datasource loader: registered: " << ds_name() << std::endl;
#endif
                            registered_=true;
                        }
                        else
                        {
                            std::clog << "Problem loading plugin library '" << itr->path().string() << "' (plugin is lacking compatible interface" << std::endl;
                        }
                    }
                    else
                    {
#if (BOOST_FILESYSTEM_VERSION == 3)
                        std::clog << "Problem loading plugin library: " << itr->path().string()
                                  << " (dlopen failed - plugin likely has an unsatisfied dependency or incompatible ABI)" << std::endl;
#else // v2
                        std::clog << "Problem loading plugin library: " << itr->string()
                                  << " (dlopen failed - plugin likely has an unsatisfied dependency or incompatible ABI)" << std::endl;
#endif
                    }
                }
                catch (...) {}
            }
        }
    }
}

}
<commit_msg>only warn if plugin has no declared name - to avoid warnings on double registration of valid plugins<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2011 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id: datasource_cache.cpp 23 2005-03-22 22:16:34Z pavlenko $

// mapnik
#include <mapnik/datasource_cache.hpp>

#include <mapnik/config_error.hpp>

// boost
#include <boost/version.hpp>
#include <boost/make_shared.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/algorithm/string.hpp>

// ltdl
#include <ltdl.h>

// stl
#include <algorithm>
#include <iostream>
#include <stdexcept>

namespace mapnik
{

bool is_input_plugin (std::string const& filename)
{
    return boost::algorithm::ends_with(filename,std::string(".input"));
}

datasource_cache::datasource_cache()
{
    if (lt_dlinit()) throw std::runtime_error("lt_dlinit() failed");
}

datasource_cache::~datasource_cache()
{
    lt_dlexit();
}

std::map<std::string,boost::shared_ptr<PluginInfo> > datasource_cache::plugins_;
bool datasource_cache::registered_=false;
std::vector<std::string> datasource_cache::plugin_directories_;

datasource_ptr datasource_cache::create(const parameters& params, bool bind)
{
    boost::optional<std::string> type = params.get<std::string>("type");
    if ( ! type)
    {
        throw config_error(std::string("Could not create datasource. Required ") +
                           "parameter 'type' is missing");
    }

#ifdef MAPNIK_THREADSAFE
    mutex::scoped_lock lock(mutex_);
#endif
    datasource_ptr ds;
    std::map<std::string,boost::shared_ptr<PluginInfo> >::iterator itr=plugins_.find(*type);
    if ( itr == plugins_.end() )
    {
        throw config_error(std::string("Could not create datasource. No plugin ") +
                           "found for type '" + * type + "' (searched in: " + plugin_directories() + ")");
    }
    if ( ! itr->second->handle())
    {
        throw std::runtime_error(std::string("Cannot load library: ") +
                                 lt_dlerror());
    }
    // http://www.mr-edd.co.uk/blog/supressing_gcc_warnings
    #ifdef __GNUC__
    __extension__
    #endif
    create_ds* create_datasource =
        reinterpret_cast<create_ds*>(lt_dlsym(itr->second->handle(), "create"));

    if ( ! create_datasource)
    {
        throw std::runtime_error(std::string("Cannot load symbols: ") +
                                 lt_dlerror());
    }
#ifdef MAPNIK_DEBUG
    std::clog << "size = " << params.size() << "\n";
    parameters::const_iterator i = params.begin();
    for (;i!=params.end();++i)
    {
        std::clog << i->first << "=" << i->second << "\n";
    }
#endif
    ds=datasource_ptr(create_datasource(params, bind), datasource_deleter());

#ifdef MAPNIK_DEBUG
    std::clog<<"datasource="<<ds<<" type="<<type<<std::endl;
#endif
    return ds;
}

bool datasource_cache::insert(const std::string& type,const lt_dlhandle module)
{
    return plugins_.insert(make_pair(type,boost::make_shared<PluginInfo>
                                     (type,module))).second;
}

std::string datasource_cache::plugin_directories()
{
    return boost::algorithm::join(plugin_directories_,", ");
}

std::vector<std::string> datasource_cache::plugin_names ()
{
    std::vector<std::string> names;
    std::map<std::string,boost::shared_ptr<PluginInfo> >::const_iterator itr;
    for (itr = plugins_.begin();itr!=plugins_.end();++itr)
    {
        names.push_back(itr->first);
    }
    return names;
}

void datasource_cache::register_datasources(const std::string& str)
{
#ifdef MAPNIK_THREADSAFE
    mutex::scoped_lock lock(mapnik::singleton<mapnik::datasource_cache,
                            mapnik::CreateStatic>::mutex_);
#endif
    boost::filesystem::path path(str);
    plugin_directories_.push_back(str);
    boost::filesystem::directory_iterator end_itr;

    if (exists(path) && is_directory(path))
    {
        for (boost::filesystem::directory_iterator itr(path);itr!=end_itr;++itr )
        {

#if BOOST_VERSION < 103400
            if (!is_directory( *itr )  && is_input_plugin(itr->leaf()))
#else
#if (BOOST_FILESYSTEM_VERSION == 3)
            if (!is_directory( *itr )  && is_input_plugin(itr->path().filename().string()))
#else // v2
            if (!is_directory( *itr )  && is_input_plugin(itr->path().leaf()))
#endif
#endif
            {
                try
                {
#ifdef LIBTOOL_SUPPORTS_ADVISE
                    /* Note: the below was added as a workaround pre http://trac.mapnik.org/ticket/790
                       It could now be removed, but also is not doing any harm AFAICT.
                    */

                    // with ltdl >=2.2 we can actually pass RTDL_GLOBAL to dlopen via the
                    // ltdl advise trick which is required on linux unless plugins are directly
                    // linked to libmapnik (and deps) at build time. The only other approach is to
                    // set the dlopen flags in the calling process (like in the python bindings)

                    // clear errors
                    lt_dlerror();

                    lt_dlhandle module = 0;
                    lt_dladvise advise;
                    int ret;

                    ret = lt_dlinit();
                    if (ret != 0) {
                        std::clog << "Datasource loader: could not intialize dynamic loading: " << lt_dlerror() << "\n";
                    }

                    ret = lt_dladvise_init(&advise);
                    if (ret != 0) {
                        std::clog << "Datasource loader: could not intialize dynamic loading: " << lt_dlerror() << "\n";
                    }

                    ret = lt_dladvise_global(&advise);
                    if (ret != 0) {
                        std::clog << "Datasource loader: could not intialize dynamic loading of global symbols: " << lt_dlerror() << "\n";
                    }
#if (BOOST_FILESYSTEM_VERSION == 3)
                    module = lt_dlopenadvise (itr->path().string().c_str(), advise);
#else // v2
                    module = lt_dlopenadvise (itr->string().c_str(), advise);
#endif

                    lt_dladvise_destroy(&advise);
#else

#if (BOOST_FILESYSTEM_VERSION == 3)
                    lt_dlhandle module = lt_dlopen(itr->path().string().c_str());
#else // v2
                    lt_dlhandle module = lt_dlopen(itr->string().c_str());
#endif

#endif
                    if (module)
                    {
                        // http://www.mr-edd.co.uk/blog/supressing_gcc_warnings
                        #ifdef __GNUC__
                        __extension__
                        #endif
                        datasource_name* ds_name =
                            reinterpret_cast<datasource_name*>(lt_dlsym(module, "datasource_name"));
                        if (ds_name && insert(ds_name(),module))
                        {
#ifdef MAPNIK_DEBUG
                            std::clog << "Datasource loader: registered: " << ds_name() << std::endl;
#endif
                            registered_=true;
                        }
                        else if (!ds_name)
                        {
                            std::clog << "Problem loading plugin library '" << itr->path().string() << "' (plugin is lacking compatible interface)" << std::endl;
                        }
                    }
                    else
                    {
#if (BOOST_FILESYSTEM_VERSION == 3)
                        std::clog << "Problem loading plugin library: " << itr->path().string()
                                  << " (dlopen failed - plugin likely has an unsatisfied dependency or incompatible ABI)" << std::endl;
#else // v2
                        std::clog << "Problem loading plugin library: " << itr->string()
                                  << " (dlopen failed - plugin likely has an unsatisfied dependency or incompatible ABI)" << std::endl;
#endif
                    }
                }
                catch (...) {}
            }
        }
    }
}

}
<|endoftext|>


<commit_before>/**
 * \file GeoConvert.cpp
 *
 * Copyright (c) Charles Karney (2008) <charles@karney.com>
 * http://charles.karney.info/geographic
 * and licensed under the LGPL.
 *
 * Compile with
 *
 *   g++ -g -O3 -I.. -o GeoConvert GeoConvert.cpp GeoCoords.cpp MGRS.cpp UTMUPS.cpp DMS.cpp Constants.cpp TransverseMercator.cpp PolarStereographic.cpp
 *
 **********************************************************************/

#include <iostream>
#include "GeoCoords.hpp"
#include <sstream>
#include <string>
#include <stdexcept>
#include <iomanip>

int main(int argc, char* argv[]) {
  int outputmode = 0;		// Lat/Lon; 1 = DMS; 2 = UTM/UPS; 3 = MGRS
  int prec = 0;
  int zone = -2;		// -2 = track input, -1 = standard

  for (int m = 1; m < argc; ++m) {
    std::string arg = std::string(argv[m]);
    if (arg == "-g")
      outputmode = 0;
    else if (arg == "-d")
      outputmode = 1;
    else if (arg == "-u")
      outputmode = 2;
    else if (arg == "-m")
      outputmode = 3;
    else if (arg == "-c")
      outputmode = 4;
    else if (arg == "-p") {
      std::string a = std::string(argv[++m]);
      std::istringstream str(a);
      str >> prec;
    } else if (arg == "-z") {
      std::string a = std::string(argv[++m]);
      std::istringstream str(a);
      str >> zone;
    } else if (arg == "-s")
      zone = -1;
    else {
      ( arg == "-h" ? std::cout : std::cerr )	<<
"Usage: GeoConvert [-g|-d|-u|-m|-c] [-p prec] [-z zone] [-s] [-h]\n\
$Id$\n\
\n\
Convert geographic coordinates to\n\
\n\
    -g latitude and longitude (decimal degrees), default output\n\
    -d latitude and longitude (degrees mins secs)\n\
    -u UTM or UPS\n\
    -m MGRS\n\
    -c meridian convergence and scale\n\
\n\
Geographic coordinates are given on standard input as\n\
\n\
latitude and longitude (decimal degrees or degrees minutes seconds).\n\
Latitude is given first unless hemisphere is specified, e.g.,\n\
\n\
    33.3 44.4\n\
    E44.4 N33.3\n\
    33d18'N 44d24'E\n\
\n\
UTM or UPS given as zone+hemisphere easting northing or easting northing\n\
zone+hemisphere.  The zone is absent for a UPS specification.  E.g.,\n\
\n\
    38N 444140.54 3684706.36\n\
    444140.54 3684706.36 38N\n\
    S 2173854.98 2985980.58\n\
    2173854.98 2985980.58 S\n\
\n\
MRGS is used to specify the center of a grid square, e.g.,\n\
\n\
    38SMB4484\n\
    38SMB44140847064\n\
\n\
-p prec (default 0) sets the precision relative to 1m.  This gives the\n\
number of digits after the decimal point for UTM/UPS.  The number of digits\n\
per coordinate for MGRS is 5 + prec.  For decimal degrees, the number\n\
of digits after the decimal point is 5 + prec.  For DMS (degree,\n\
minute, seconds) output, the number of digits after the decimal point\n\
in the seconds components is 1 + prec.  The minimum value of prec is -5\n\
and the maximum is 9 for UTM/UPS, 10 for decimal degrees and DMS, and 6 for\n\
MGRS.\n\
\n\
UTM/UPS and MGS are given in zone of the input if applicable, otherwise\n\
in the standard zone.\n\
\n\
-z zone sets the zone for output.  Use zone = 0 to specify a UPS (polar)\n\
zone.\n\
\n\
-s uses the standard zone\n\
\n\
For example, the point\n\
\n\
    79.9S 6.1E\n\
\n\
corresponds to 3 possible MGRS coordinates\n\
\n\
    32CMS4324728161 (standard UTM zone = 32)\n\
    31CEM6066227959 (neighboring UTM zone = 31)\n\
      BBZ1945517770 (neighboring UPS zone)\n\
\n\
then\n\
    echo 31CEM6066227959 | GeoConvert -p -3 -m       ==> 31CEM6027\n\
    echo 31CEM6066227959 | GeoConvert -p -3 -m -s    ==> 32CMS4328\n\
    echo 31CEM6066227959 | GeoConvert -p -3 -m -z 0  ==>   BBZ1917\n\
\n\
-h prints this help\n";
      return arg == "-h" ? 0 : 1;
    }
  }

  GeographicLib::GeoCoords p;
  std::string s;
  std::string os;
  int retval = 0;
  if (!(zone >= -2 && zone <= 60)) {
    std::cerr << "Illegal zone " << zone << "\n";
    return 1;
  }
  while (true) {
    std::getline(std::cin, s);
    if (!std::cin.good())
      break;
    try {
      p.Reset(s);
      if (zone != -2)
	p.SetAltZone(zone);
      switch (outputmode) {
      case 0:
	os = p.GeoRepresentation(prec);
	break;
      case 1:
	os = p.DMSRepresentation(prec);
	break;
      case 2:
	os = p.AltUTMUPSRepresentation(prec);
	break;
      case 3:
	os = p.AltMGRSRepresentation(prec);
	break;
      case 4:
	{
	  double
	    gamma = p.AltConvergence(),
	    k = p.AltScale();
	  std::ostringstream ss;
	  ss << std::fixed
	     << std::setprecision(std::max(0, std::min(8, prec) + 5)) << gamma
	     << " "
	     << std::setprecision(std::max(0, std::min(8, prec) + 7)) << k;
	  os = ss.str();
	}
      }
    }
    catch (std::out_of_range& e) {
      os = std::string("ERROR: ") + e.what();
      retval = 1;
    }
    std::cout << os << std::endl;
  }
  return retval;
}
<commit_msg>Fix include path.<commit_after>/**
 * \file GeoConvert.cpp
 *
 * Copyright (c) Charles Karney (2008) <charles@karney.com>
 * http://charles.karney.info/geographic
 * and licensed under the LGPL.
 *
 * Compile with
 *
 *   g++ -g -O3 -I.. -o GeoConvert GeoConvert.cpp GeoCoords.cpp MGRS.cpp UTMUPS.cpp DMS.cpp Constants.cpp TransverseMercator.cpp PolarStereographic.cpp
 *
 **********************************************************************/

#include <iostream>
#include <sstream>
#include <string>
#include <stdexcept>
#include <iomanip>
#include "GeoGraphicLib/GeoCoords.hpp"

int main(int argc, char* argv[]) {
  int outputmode = 0;		// Lat/Lon; 1 = DMS; 2 = UTM/UPS; 3 = MGRS
  int prec = 0;
  int zone = -2;		// -2 = track input, -1 = standard

  for (int m = 1; m < argc; ++m) {
    std::string arg = std::string(argv[m]);
    if (arg == "-g")
      outputmode = 0;
    else if (arg == "-d")
      outputmode = 1;
    else if (arg == "-u")
      outputmode = 2;
    else if (arg == "-m")
      outputmode = 3;
    else if (arg == "-c")
      outputmode = 4;
    else if (arg == "-p") {
      std::string a = std::string(argv[++m]);
      std::istringstream str(a);
      str >> prec;
    } else if (arg == "-z") {
      std::string a = std::string(argv[++m]);
      std::istringstream str(a);
      str >> zone;
    } else if (arg == "-s")
      zone = -1;
    else {
      ( arg == "-h" ? std::cout : std::cerr )	<<
"Usage: GeoConvert [-g|-d|-u|-m|-c] [-p prec] [-z zone] [-s] [-h]\n\
$Id$\n\
\n\
Convert geographic coordinates to\n\
\n\
    -g latitude and longitude (decimal degrees), default output\n\
    -d latitude and longitude (degrees mins secs)\n\
    -u UTM or UPS\n\
    -m MGRS\n\
    -c meridian convergence and scale\n\
\n\
Geographic coordinates are given on standard input as\n\
\n\
latitude and longitude (decimal degrees or degrees minutes seconds).\n\
Latitude is given first unless hemisphere is specified, e.g.,\n\
\n\
    33.3 44.4\n\
    E44.4 N33.3\n\
    33d18'N 44d24'E\n\
\n\
UTM or UPS given as zone+hemisphere easting northing or easting northing\n\
zone+hemisphere.  The zone is absent for a UPS specification.  E.g.,\n\
\n\
    38N 444140.54 3684706.36\n\
    444140.54 3684706.36 38N\n\
    S 2173854.98 2985980.58\n\
    2173854.98 2985980.58 S\n\
\n\
MRGS is used to specify the center of a grid square, e.g.,\n\
\n\
    38SMB4484\n\
    38SMB44140847064\n\
\n\
-p prec (default 0) sets the precision relative to 1m.  This gives the\n\
number of digits after the decimal point for UTM/UPS.  The number of digits\n\
per coordinate for MGRS is 5 + prec.  For decimal degrees, the number\n\
of digits after the decimal point is 5 + prec.  For DMS (degree,\n\
minute, seconds) output, the number of digits after the decimal point\n\
in the seconds components is 1 + prec.  The minimum value of prec is -5\n\
and the maximum is 9 for UTM/UPS, 10 for decimal degrees and DMS, and 6 for\n\
MGRS.\n\
\n\
UTM/UPS and MGS are given in zone of the input if applicable, otherwise\n\
in the standard zone.\n\
\n\
-z zone sets the zone for output.  Use zone = 0 to specify a UPS (polar)\n\
zone.\n\
\n\
-s uses the standard zone\n\
\n\
For example, the point\n\
\n\
    79.9S 6.1E\n\
\n\
corresponds to 3 possible MGRS coordinates\n\
\n\
    32CMS4324728161 (standard UTM zone = 32)\n\
    31CEM6066227959 (neighboring UTM zone = 31)\n\
      BBZ1945517770 (neighboring UPS zone)\n\
\n\
then\n\
    echo 31CEM6066227959 | GeoConvert -p -3 -m       ==> 31CEM6027\n\
    echo 31CEM6066227959 | GeoConvert -p -3 -m -s    ==> 32CMS4328\n\
    echo 31CEM6066227959 | GeoConvert -p -3 -m -z 0  ==>   BBZ1917\n\
\n\
-h prints this help\n";
      return arg == "-h" ? 0 : 1;
    }
  }

  GeographicLib::GeoCoords p;
  std::string s;
  std::string os;
  int retval = 0;
  if (!(zone >= -2 && zone <= 60)) {
    std::cerr << "Illegal zone " << zone << "\n";
    return 1;
  }
  while (true) {
    std::getline(std::cin, s);
    if (!std::cin.good())
      break;
    try {
      p.Reset(s);
      if (zone != -2)
	p.SetAltZone(zone);
      switch (outputmode) {
      case 0:
	os = p.GeoRepresentation(prec);
	break;
      case 1:
	os = p.DMSRepresentation(prec);
	break;
      case 2:
	os = p.AltUTMUPSRepresentation(prec);
	break;
      case 3:
	os = p.AltMGRSRepresentation(prec);
	break;
      case 4:
	{
	  double
	    gamma = p.AltConvergence(),
	    k = p.AltScale();
	  std::ostringstream ss;
	  ss << std::fixed
	     << std::setprecision(std::max(0, std::min(8, prec) + 5)) << gamma
	     << " "
	     << std::setprecision(std::max(0, std::min(8, prec) + 7)) << k;
	  os = ss.str();
	}
      }
    }
    catch (std::out_of_range& e) {
      os = std::string("ERROR: ") + e.what();
      retval = 1;
    }
    std::cout << os << std::endl;
  }
  return retval;
}
<|endoftext|>


<commit_before>/**
 * projectM -- Milkdrop-esque visualisation SDK
 * Copyright (C)2003-2004 projectM Team
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * 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
 * See 'LICENSE.txt' included within this release
 *
 */
#include "video_init.h"
#include <fcntl.h>
#include <stdlib.h>
#include <math.h>
#include <SDL/SDL.h>
#include <libprojectM/projectM.hpp>
#include "sdltoprojectM.h"

#include "ConfigFile.h"
#include <string>
#include <iostream>
#include <stdio.h>
#include <unistd.h>

#include <jack/jack.h>

#define CONFIG_FILE "/share/projectM/config.inp"

std::string read_config();

jack_port_t *input_port;
jack_client_t *client;
jack_default_audio_sample_t out[1024*1000];

#ifdef DEBUG
FILE *debugFile = NULL;
#endif

volatile enum {
	Init,
	Run,
	Exit
} client_state = Init;

SDL_Surface *screen;

projectM *globalPM = NULL;

int dumpFrame = 0;
int frameNumber = 0;

int texsize=512;
int gx=32,gy=24;
int wvw=512,wvh=512;
int fvw=1024,fvh=768;
int fps=30, fullscreen=0;

std::string read_config()
{

   int n;

   char num[512];
   FILE *in;
   FILE *out;

   char* home;
   char projectM_home[1024];
   char projectM_config[1024];

   strcpy(projectM_config, PROJECTM_PREFIX);
   strcpy(projectM_config+strlen(PROJECTM_PREFIX), CONFIG_FILE);
   projectM_config[strlen(PROJECTM_PREFIX)+strlen(CONFIG_FILE)]='\0';
   printf("dir:%s \n",projectM_config);
   home=getenv("HOME");
   strcpy(projectM_home, home);
   strcpy(projectM_home+strlen(home), "/.projectM/config.inp");
   projectM_home[strlen(home)+strlen("/.projectM/config.inp")]='\0';

 if ((in = fopen(projectM_home, "r")) != 0)
   {
     printf("reading ~/.projectM/config.inp \n");
     fclose(in);
     return std::string(projectM_home);
   }
 else
   {
     printf("trying to create ~/.projectM/config.inp \n");

     strcpy(projectM_home, home);
     strcpy(projectM_home+strlen(home), "/.projectM");
     projectM_home[strlen(home)+strlen("/.projectM")]='\0';
     mkdir(projectM_home,0755);

     strcpy(projectM_home, home);
     strcpy(projectM_home+strlen(home), "/.projectM/config.inp");
     projectM_home[strlen(home)+strlen("/.projectM/config.inp")]='\0';

     if((out = fopen(projectM_home,"w"))!=0)
       {

	 if ((in = fopen(projectM_config, "r")) != 0)
	   {

	     while(fgets(num,80,in)!=NULL)
	       {
		 fputs(num,out);
	       }
	     fclose(in);
	     fclose(out);

	     if ((in = fopen(projectM_home, "r")) != 0)
	       {
		 printf("created ~/.projectM/config.inp successfully\n");
		 fclose(in);
		 return std::string(projectM_home);
	       }
	     else{printf("This shouldn't happen, using implementation defualts\n");abort();}
	   }
	 else{printf("Cannot find projectM default config, using implementation defaults\n");abort();}
       }
     else
       {
	 printf("Cannot create ~/.projectM/config.inp, using default config file\n");
	 if ((in = fopen(projectM_config, "r")) != 0)
	   { printf("Successfully opened default config file\n");
	     fclose(in);
	     return std::string(projectM_config);}
	 else{ printf("Using implementation defaults, your system is really messed up, I'm suprised we even got this far\n");  abort();}

       }

   }

 abort();
}

void renderLoop() {

    int i;
    int x, y;
    int index;
    short pcm_data[2][512];

    while ( 1 ) {
        projectMEvent evt;
        projectMKeycode key;
        projectMModifier mod;

        /** Process SDL events */
        SDL_Event event;
        while ( SDL_PollEvent( &event ) ) {
            /** Translate into projectM codes and process */
            evt = sdl2pmEvent( event );
            key = sdl2pmKeycode( event.key.keysym.sym );
            mod = sdl2pmModifier( event.key.keysym.mod );

	    if ( evt == PROJECTM_KEYDOWN ) {

                if(key == PROJECTM_K_f)
                {
                    resize_display(fvw, fvh, fullscreen);
                    globalPM->projectM_resetGL( fvw, fvh );
                }
		else if(key == PROJECTM_K_q || key == PROJECTM_K_ESCAPE) {delete(globalPM); exit (1);}
                else  {globalPM->key_handler(evt,key,mod);}

            }
            else if ( evt == PROJECTM_VIDEORESIZE )
            {
                wvw=event.resize.w;
                wvh=event.resize.h;
                resize_display(wvw, wvh, 0);
                globalPM->projectM_resetGL(  wvw, wvh );

            }

          }

        /** Render the new frame */
        globalPM->renderFrame( );

        SDL_GL_SwapBuffers();
      }

  printf("Worker thread: Exiting\n");
  }

int
process (jack_nframes_t nframes, void *arg)
{
	jack_default_audio_sample_t *in;
	jack_transport_state_t ts = jack_transport_query(client, NULL);

	if (ts == JackTransportRolling) {

		if (client_state == Init)
			client_state = Run;

		in = (jack_default_audio_sample_t*)jack_port_get_buffer (input_port, nframes);

		//memcpy (out, in,sizeof (jack_default_audio_sample_t) * nframes);

		globalPM->pcm->addPCMfloat(in,nframes);
		//printf("%x %f\n",nframes,in[128]);

	} else if (ts == JackTransportStopped) {

		if (client_state == Run)
			client_state = Exit;
	}

	return 0;
}

void jack_shutdown (void *arg)
{
	exit (1);
}

int main( int argc, char **argv ) {
	const char **ports;
	const char *client_name;
	const char *server_name = NULL;
	jack_options_t options = JackNullOption;
	jack_status_t status;
	int i;
 char projectM_data[1024];

std::string config_file;
 config_file = read_config();

 ConfigFile config(config_file);

 int wvw = config.read<int>( "Window Width", 512 );
 int wvh = config.read<int>( "Window Height", 512 );
 int fullscreen = 0;
 if (config.read("Fullscreen", true)) fullscreen = 1;
      else fullscreen = 0;

#ifdef DEBUG
	int value;
	int rgb_size[3];
#endif

  const SDL_VideoInfo* info = NULL;
  int bpp = 0;
  /* Flags we will pass into SDL_SetVideoMode. */
  int flags = 0;

  //JACK INIT
  //----------------------------------------------
	if (argc >= 2) {		/* client name specified? */
		client_name = argv[1];
		if (argc >= 3) {	/* server name specified? */
			server_name = argv[2];
			//			options |= JackServerName;
		}
	} else {			/* use basename of argv[0] */
		client_name = strrchr(argv[0], '/');
		if (client_name == 0) {
			client_name = argv[0];
		} else {
			client_name++;
		}
	}

	/* open a client connection to the JACK server */

	client = jack_client_open (client_name, options, &status, server_name);
	if (client == NULL) {
		fprintf (stderr, "jack_client_open() failed, "
			 "status = 0x%2.0x\n", status);
		if (status & JackServerFailed) {
			fprintf (stderr, "Unable to connect to JACK server\n");
		}
		exit (1);
	}
	if (status & JackServerStarted) {
		fprintf (stderr, "JACK server started\n");
	}
	if (status & JackNameNotUnique) {
		client_name = jack_get_client_name(client);
		fprintf (stderr, "unique name `%s' assigned\n", client_name);
	}

	/* tell the JACK server to call `process()' whenever
	   there is work to be done.
	*/

	jack_set_process_callback (client, process, 0);

	/* tell the JACK server to call `jack_shutdown()' if
	   it ever shuts down, either entirely, or if it
	   just decides to stop calling us.
	*/

	jack_on_shutdown (client, jack_shutdown, 0);

	/* display the current sample rate.
	 */

	printf ("engine sample rate: %d\n",
		jack_get_sample_rate (client));

	/* create two ports */

	input_port = jack_port_register (client, "input",
					 JACK_DEFAULT_AUDIO_TYPE,
					 JackPortIsInput, 0);

	if (input_port == NULL) {
		fprintf(stderr, "no more JACK ports available\n");
		exit (1);
	}

	/* Tell the JACK server that we are ready to roll.  Our
	 * process() callback will start running now. */

	//END JACK INIT ----------------------------------
  init_display(wvw,wvh,&fvw,&fvh,fullscreen);
    /** Setup some window stuff */
    SDL_WM_SetCaption( PROJECTM_TITLE, NULL );
  globalPM = new projectM(config_file);
    /** Initialise projectM */

    //JACK BEGIN-----------------------------

	if (jack_activate (client)) {
		fprintf (stderr, "cannot activate client");
		exit (1);
	}

	/* Connect the ports.  You can't do this before the client is
	 * activated, because we can't make connections to clients
	 * that aren't running.  Note the confusing (but necessary)
	 * orientation of the driver backend ports: playback ports are
	 * "input" to the backend, and capture ports are "output" from
	 * it.
	 */

	ports = jack_get_ports (client, NULL, NULL, JackPortIsOutput);
	if (ports == NULL) {
		fprintf(stderr, "no physical capture ports\n");
		exit (1);
	}

        i=0;
        while (ports[i]!=NULL)
	 {
            printf("Connecting to Jack port %s\n",ports[i]);
	    if (jack_connect (client, ports[i], jack_port_name (input_port))) {
	      fprintf (stderr, "cannot connect input ports\n");
	    }
	      i++;
	     }

	free (ports);

	//----------------------------------END

    /** Initialise the thread */
    renderLoop();

    return 1;
}

<commit_msg>Fullscreen fix<commit_after>/**
 * projectM -- Milkdrop-esque visualisation SDK
 * Copyright (C)2003-2004 projectM Team
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * 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
 * See 'LICENSE.txt' included within this release
 *
 */
#include "video_init.h"
#include <fcntl.h>
#include <stdlib.h>
#include <math.h>
#include <SDL/SDL.h>
#include <libprojectM/projectM.hpp>
#include "sdltoprojectM.h"

#include "ConfigFile.h"
#include <string>
#include <iostream>
#include <stdio.h>
#include <unistd.h>

#include <jack/jack.h>

#define CONFIG_FILE "/share/projectM/config.inp"

std::string read_config();

jack_port_t *input_port;
jack_client_t *client;
jack_default_audio_sample_t out[1024*1000];

#ifdef DEBUG
FILE *debugFile = NULL;
#endif

volatile enum {
	Init,
	Run,
	Exit
} client_state = Init;

SDL_Surface *screen;

projectM *globalPM = NULL;

int dumpFrame = 0;
int frameNumber = 0;

int texsize=512;
int gx=32,gy=24;
int wvw=512,wvh=512;
int fvw=1024,fvh=768;
int fps=30, fullscreen=0;

std::string read_config()
{

   int n;

   char num[512];
   FILE *in;
   FILE *out;

   char* home;
   char projectM_home[1024];
   char projectM_config[1024];

   strcpy(projectM_config, PROJECTM_PREFIX);
   strcpy(projectM_config+strlen(PROJECTM_PREFIX), CONFIG_FILE);
   projectM_config[strlen(PROJECTM_PREFIX)+strlen(CONFIG_FILE)]='\0';
   printf("dir:%s \n",projectM_config);
   home=getenv("HOME");
   strcpy(projectM_home, home);
   strcpy(projectM_home+strlen(home), "/.projectM/config.inp");
   projectM_home[strlen(home)+strlen("/.projectM/config.inp")]='\0';

 if ((in = fopen(projectM_home, "r")) != 0)
   {
     printf("reading ~/.projectM/config.inp \n");
     fclose(in);
     return std::string(projectM_home);
   }
 else
   {
     printf("trying to create ~/.projectM/config.inp \n");

     strcpy(projectM_home, home);
     strcpy(projectM_home+strlen(home), "/.projectM");
     projectM_home[strlen(home)+strlen("/.projectM")]='\0';
     mkdir(projectM_home,0755);

     strcpy(projectM_home, home);
     strcpy(projectM_home+strlen(home), "/.projectM/config.inp");
     projectM_home[strlen(home)+strlen("/.projectM/config.inp")]='\0';

     if((out = fopen(projectM_home,"w"))!=0)
       {

	 if ((in = fopen(projectM_config, "r")) != 0)
	   {

	     while(fgets(num,80,in)!=NULL)
	       {
		 fputs(num,out);
	       }
	     fclose(in);
	     fclose(out);

	     if ((in = fopen(projectM_home, "r")) != 0)
	       {
		 printf("created ~/.projectM/config.inp successfully\n");
		 fclose(in);
		 return std::string(projectM_home);
	       }
	     else{printf("This shouldn't happen, using implementation defualts\n");abort();}
	   }
	 else{printf("Cannot find projectM default config, using implementation defaults\n");abort();}
       }
     else
       {
	 printf("Cannot create ~/.projectM/config.inp, using default config file\n");
	 if ((in = fopen(projectM_config, "r")) != 0)
	   { printf("Successfully opened default config file\n");
	     fclose(in);
	     return std::string(projectM_config);}
	 else{ printf("Using implementation defaults, your system is really messed up, I'm suprised we even got this far\n");  abort();}

       }

   }

 abort();
}

void renderLoop() {

    int i;
    int x, y;
    int index;
    short pcm_data[2][512];

    while ( 1 ) {
        projectMEvent evt;
        projectMKeycode key;
        projectMModifier mod;

        /** Process SDL events */
        SDL_Event event;
        while ( SDL_PollEvent( &event ) ) {
            /** Translate into projectM codes and process */
            evt = sdl2pmEvent( event );
            key = sdl2pmKeycode( event.key.keysym.sym );
            mod = sdl2pmModifier( event.key.keysym.mod );

	    if ( evt == PROJECTM_KEYDOWN ) {

                if(key == PROJECTM_K_f)
                {
		  if (++fullscreen%2)
		    {
		      resize_display(fvw, fvh, fullscreen%2);
		      globalPM->projectM_resetGL( fvw, fvh );
		    }
		  else
		    {
		      resize_display(wvw, wvh, fullscreen%2);
		      globalPM->projectM_resetGL( wvw, wvh );
		    }
                }
		else if(key == PROJECTM_K_q || key == PROJECTM_K_ESCAPE) {delete(globalPM); exit (1);}
                else  {globalPM->key_handler(evt,key,mod);}

            }
            else if ( evt == PROJECTM_VIDEORESIZE )
            {
                wvw=event.resize.w;
                wvh=event.resize.h;
                resize_display(wvw, wvh, fullscreen%2);
                globalPM->projectM_resetGL(  wvw, wvh );

            }

          }

        /** Render the new frame */
        globalPM->renderFrame( );

        SDL_GL_SwapBuffers();
      }

  printf("Worker thread: Exiting\n");
  }

int
process (jack_nframes_t nframes, void *arg)
{
	jack_default_audio_sample_t *in;
	jack_transport_state_t ts = jack_transport_query(client, NULL);

	if (ts == JackTransportRolling) {

		if (client_state == Init)
			client_state = Run;

		in = (jack_default_audio_sample_t*)jack_port_get_buffer (input_port, nframes);

		//memcpy (out, in,sizeof (jack_default_audio_sample_t) * nframes);

		globalPM->pcm->addPCMfloat(in,nframes);
		//printf("%x %f\n",nframes,in[128]);

	} else if (ts == JackTransportStopped) {

		if (client_state == Run)
			client_state = Exit;
	}

	return 0;
}

void jack_shutdown (void *arg)
{
	exit (1);
}

int main( int argc, char **argv ) {
	const char **ports;
	const char *client_name;
	const char *server_name = NULL;
	jack_options_t options = JackNullOption;
	jack_status_t status;
	int i;
 char projectM_data[1024];

std::string config_file;
 config_file = read_config();

 ConfigFile config(config_file);

 wvw = config.read<int>( "Window Width", 512 );
 wvh = config.read<int>( "Window Height", 512 );
 int fullscreen = 0;
 if (config.read("Fullscreen", true)) fullscreen = 1;
      else fullscreen = 0;

#ifdef DEBUG
	int value;
	int rgb_size[3];
#endif

  const SDL_VideoInfo* info = NULL;
  int bpp = 0;
  /* Flags we will pass into SDL_SetVideoMode. */
  int flags = 0;

  //JACK INIT
  //----------------------------------------------
	if (argc >= 2) {		/* client name specified? */
		client_name = argv[1];
		if (argc >= 3) {	/* server name specified? */
			server_name = argv[2];
			//			options |= JackServerName;
		}
	} else {			/* use basename of argv[0] */
		client_name = strrchr(argv[0], '/');
		if (client_name == 0) {
			client_name = argv[0];
		} else {
			client_name++;
		}
	}

	/* open a client connection to the JACK server */

	client = jack_client_open (client_name, options, &status, server_name);
	if (client == NULL) {
		fprintf (stderr, "jack_client_open() failed, "
			 "status = 0x%2.0x\n", status);
		if (status & JackServerFailed) {
			fprintf (stderr, "Unable to connect to JACK server\n");
		}
		exit (1);
	}
	if (status & JackServerStarted) {
		fprintf (stderr, "JACK server started\n");
	}
	if (status & JackNameNotUnique) {
		client_name = jack_get_client_name(client);
		fprintf (stderr, "unique name `%s' assigned\n", client_name);
	}

	/* tell the JACK server to call `process()' whenever
	   there is work to be done.
	*/

	jack_set_process_callback (client, process, 0);

	/* tell the JACK server to call `jack_shutdown()' if
	   it ever shuts down, either entirely, or if it
	   just decides to stop calling us.
	*/

	jack_on_shutdown (client, jack_shutdown, 0);

	/* display the current sample rate.
	 */

	printf ("engine sample rate: %d\n",
		jack_get_sample_rate (client));

	/* create two ports */

	input_port = jack_port_register (client, "input",
					 JACK_DEFAULT_AUDIO_TYPE,
					 JackPortIsInput, 0);

	if (input_port == NULL) {
		fprintf(stderr, "no more JACK ports available\n");
		exit (1);
	}

	/* Tell the JACK server that we are ready to roll.  Our
	 * process() callback will start running now. */

	//END JACK INIT ----------------------------------
  init_display(wvw,wvh,&fvw,&fvh,fullscreen);
    /** Setup some window stuff */
    SDL_WM_SetCaption( PROJECTM_TITLE, NULL );
  globalPM = new projectM(config_file);
    /** Initialise projectM */

    //JACK BEGIN-----------------------------

	if (jack_activate (client)) {
		fprintf (stderr, "cannot activate client");
		exit (1);
	}

	/* Connect the ports.  You can't do this before the client is
	 * activated, because we can't make connections to clients
	 * that aren't running.  Note the confusing (but necessary)
	 * orientation of the driver backend ports: playback ports are
	 * "input" to the backend, and capture ports are "output" from
	 * it.
	 */

	ports = jack_get_ports (client, NULL, NULL, JackPortIsOutput);
	if (ports == NULL) {
		fprintf(stderr, "no physical capture ports\n");
		exit (1);
	}

        i=0;
        while (ports[i]!=NULL)
	 {
            printf("Connecting to Jack port %s\n",ports[i]);
	    if (jack_connect (client, ports[i], jack_port_name (input_port))) {
	      fprintf (stderr, "cannot connect input ports\n");
	    }
	      i++;
	     }

	free (ports);

	//----------------------------------END

    /** Initialise the thread */
    renderLoop();

    return 1;
}

<|endoftext|>