<commit_before>/**
 * @file llfloatervoiceeffect.cpp
 * @brief Selection and preview of voice effect.
 *
 * $LicenseInfo:firstyear=2010&license=viewergpl$
 *
 * Copyright (c) 2002-2009, Linden Research, Inc.
 *
 * Second Life Viewer Source Code
 * The source code in this file ("Source Code") is provided by Linden Lab
 * to you under the terms of the GNU General Public License, version 2.0
 * ("GPL"), unless you have obtained a separate licensing agreement
 * ("Other License"), formally executed by you and Linden Lab.  Terms of
 * the GPL can be found in doc/GPL-license.txt in this distribution, or
 * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
 *
 * There are special exceptions to the terms and conditions of the GPL as
 * it is applied to this Source Code. View the full text of the exception
 * in the file doc/FLOSS-exception.txt in this software distribution, or
 * online at
 * http://secondlifegrid.net/programs/open_source/licensing/flossexception
 *
 * By copying, modifying or distributing this software, you acknowledge
 * that you have read and understood your obligations described above,
 * and agree to abide by those obligations.
 *
 * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
 * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
 * COMPLETENESS OR PERFORMANCE.
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"

#include "llfloatervoiceeffect.h"

#include "llscrolllistctrl.h"
#include "lltrans.h"
#include "llweb.h"

LLFloaterVoiceEffect::LLFloaterVoiceEffect(const LLSD& key)
	: LLFloater(key)
{
	mCommitCallbackRegistrar.add("VoiceEffect.Record",	boost::bind(&LLFloaterVoiceEffect::onClickRecord, this));
	mCommitCallbackRegistrar.add("VoiceEffect.Play",	boost::bind(&LLFloaterVoiceEffect::onClickPlay, this));
	mCommitCallbackRegistrar.add("VoiceEffect.Stop",	boost::bind(&LLFloaterVoiceEffect::onClickStop, this));
	mCommitCallbackRegistrar.add("VoiceEffect.Add",		boost::bind(&LLFloaterVoiceEffect::onClickAdd, this));
//	mCommitCallbackRegistrar.add("VoiceEffect.Activate", boost::bind(&LLFloaterVoiceEffect::onClickActivate, this));
}

// virtual
LLFloaterVoiceEffect::~LLFloaterVoiceEffect()
{
	if(LLVoiceClient::instanceExists())
	{
		LLVoiceEffectInterface* effect_interface = LLVoiceClient::instance().getVoiceEffectInterface();
		if (effect_interface)
		{
			effect_interface->removeObserver(this);
		}
	}
}

// virtual
BOOL LLFloaterVoiceEffect::postBuild()
{
	setDefaultBtn("record_btn");
	getChild<LLButton>("record_btn")->setFocus(true);

	mVoiceEffectList = getChild<LLScrollListCtrl>("voice_effect_list");
	if (mVoiceEffectList)
	{
		mVoiceEffectList->setCommitCallback(boost::bind(&LLFloaterVoiceEffect::onClickPlay, this));
//		mVoiceEffectList->setDoubleClickCallback(boost::bind(&LLFloaterVoiceEffect::onClickActivate, this));
	}

	LLVoiceEffectInterface* effect_interface = LLVoiceClient::instance().getVoiceEffectInterface();
	if (effect_interface)
	{
		effect_interface->addObserver(this);

		// Disconnect from the current voice channel ready to record a voice sample for previewing
		effect_interface->enablePreviewBuffer(true);
	}

	refreshEffectList();
	updateControls();

	return TRUE;
}

// virtual
void LLFloaterVoiceEffect::onClose(bool app_quitting)
{
	LLVoiceEffectInterface* effect_interface = LLVoiceClient::instance().getVoiceEffectInterface();
	if (effect_interface)
	{
		effect_interface->enablePreviewBuffer(false);
	}
}

void LLFloaterVoiceEffect::refreshEffectList()
{
	if (!mVoiceEffectList)
	{
		return;
	}

	LLVoiceEffectInterface* effect_interface = LLVoiceClient::instance().getVoiceEffectInterface();
	if (!effect_interface)
	{
		mVoiceEffectList->setEnabled(false);
		return;
	}

	LL_DEBUGS("Voice")<< "Rebuilding voice effect list."<< LL_ENDL;

	// Preserve selected items and scroll position
	S32 scroll_pos = mVoiceEffectList->getScrollPos();
	uuid_vec_t selected_items;
	std::vector<LLScrollListItem*> items = mVoiceEffectList->getAllSelected();
	for(std::vector<LLScrollListItem*>::const_iterator it = items.begin(); it != items.end(); it++)
	{
		selected_items.push_back((*it)->getUUID());
	}

	mVoiceEffectList->deleteAllItems();

	{
		// Add the "No Voice Effect" entry
		LLSD element;

		element["id"] = LLUUID::null;
		element["columns"][0]["column"] = "name";
		element["columns"][0]["value"] = getString("no_voice_effect");
		element["columns"][0]["font"]["name"] = "SANSSERIF";
		element["columns"][0]["font"]["style"] = "ITALIC";

		LLScrollListItem* sl_item = mVoiceEffectList->addElement(element, ADD_BOTTOM);
		// *HACK: Copied from llfloatergesture.cpp : ["font"]["style"] does not affect font style :(
		if(sl_item)
		{
			((LLScrollListText*)sl_item->getColumn(0))->setFontStyle(LLFontGL::BOLD);
		}
	}

	const voice_effect_list_t& template_list = effect_interface->getVoiceEffectTemplateList();
	if (!template_list.empty())
	{
		for (voice_effect_list_t::const_iterator it = template_list.begin(); it != template_list.end(); ++it)
		{
			const LLUUID& effect_id = it->second;
			std::string effect_name = it->first;

			LLSD effect_properties = effect_interface->getVoiceEffectProperties(effect_id);

			// Tag the active effect.
			if (effect_id == LLVoiceClient::instance().getVoiceEffectDefault())
			{
				effect_name += " " + getString("active_voice_effect");
			}

			LLDate expiry_date = effect_properties["expiry_date"].asDate();
			bool is_template_only = effect_properties["template_only"].asBoolean();
			bool is_new = effect_properties["is_new"].asBoolean();

			std::string font_style = "NORMAL";
			if (!is_template_only)
			{
				font_style = "BOLD";
			}
			LLSD element;
			element["id"] = effect_id;

			element["columns"][0]["column"] = "name";
			element["columns"][0]["value"] = effect_name;
			element["columns"][0]["font"]["name"] = "SANSSERIF";
			element["columns"][0]["font"]["style"] = font_style;

			element["columns"][1]["column"] = "new";
			element["columns"][1]["value"] = is_new ? getString("new_voice_effect") : "";
			element["columns"][1]["font"]["name"] = "SANSSERIF";
			element["columns"][1]["font"]["style"] = font_style;

			element["columns"][2]["column"] = "expires";
			if (!is_template_only)
			{
				element["columns"][2]["value"] = expiry_date;
			}
			else {
				element["columns"][2]["value"] = "";
			}
			element["columns"][2]["font"]["name"] = "SANSSERIF";
			element["columns"][2]["font"]["style"] = font_style;

			LLScrollListItem* sl_item = mVoiceEffectList->addElement(element, ADD_BOTTOM);
			// *HACK: Copied from llfloatergesture.cpp : ["font"]["style"] does not affect font style :(
			if(sl_item)
			{
				LLFontGL::StyleFlags style = is_template_only ? LLFontGL::NORMAL : LLFontGL::BOLD;
				((LLScrollListText*)sl_item->getColumn(0))->setFontStyle(style);
			}
		}
	}

	// Re-select items that were selected before, and restore the scroll position
	for(uuid_vec_t::iterator it = selected_items.begin(); it != selected_items.end(); it++)
	{
		mVoiceEffectList->selectByID(*it);
	}
	mVoiceEffectList->setScrollPos(scroll_pos);
	mVoiceEffectList->setEnabled(true);
}

void LLFloaterVoiceEffect::updateControls()
{
	bool recording = false;
	bool playing = false;

	LLVoiceEffectInterface* effect_interface = LLVoiceClient::instance().getVoiceEffectInterface();
	if (effect_interface)
	{
		recording = effect_interface->isPreviewRecording();
		playing = effect_interface->isPreviewPlaying();
	}

	getChild<LLButton>("record_btn")->setVisible(!recording);
	getChild<LLButton>("record_stop_btn")->setVisible(recording);
}

// virtual
void LLFloaterVoiceEffect::onVoiceEffectChanged(bool effect_list_updated)
{
	if (effect_list_updated)
	{
		refreshEffectList();
	}
	updateControls();
}

void LLFloaterVoiceEffect::onClickRecord()
{
	LL_DEBUGS("Voice") << "Record clicked" << LL_ENDL;
	LLVoiceEffectInterface* effect_interface = LLVoiceClient::instance().getVoiceEffectInterface();
	if (effect_interface)
	{
		effect_interface->recordPreviewBuffer();
	}
	updateControls();
}

void LLFloaterVoiceEffect::onClickPlay()
{
	LL_DEBUGS("Voice") << "Play clicked" << LL_ENDL;
	if (!mVoiceEffectList)
	{
		return;
	}

	const LLUUID& effect_id = mVoiceEffectList->getCurrentID();

	LLVoiceEffectInterface* effect_interface = LLVoiceClient::instance().getVoiceEffectInterface();
	if (effect_interface)
	{
		effect_interface->playPreviewBuffer(effect_id);
	}
	updateControls();
}

void LLFloaterVoiceEffect::onClickStop()
{
	LL_DEBUGS("Voice") << "Stop clicked" << LL_ENDL;
	LLVoiceEffectInterface* effect_interface = LLVoiceClient::instance().getVoiceEffectInterface();
	if (effect_interface)
	{
		effect_interface->stopPreviewBuffer();
	}
	updateControls();
}

void LLFloaterVoiceEffect::onClickAdd()
{
	// Open the voice morphing info web page
	LLWeb::loadURL(LLTrans::getString("voice_morphing_url"));
}

//void LLFloaterVoiceEffect::onClickActivate()
//{
//	LLVoiceEffectInterface* effect_interface = LLVoiceClient::instance().getVoiceEffectInterface();
//	if (effect_interface && mVoiceEffectList)
//	{
//		effect_interface->setVoiceEffect(mVoiceEffectList->getCurrentID());
//	}
//}

<commit_msg>EXT-7138 WIP More tidying up after the removal of the play button in the voice effect preview.<commit_after>/**
 * @file llfloatervoiceeffect.cpp
 * @brief Selection and preview of voice effect.
 *
 * $LicenseInfo:firstyear=2010&license=viewergpl$
 *
 * Copyright (c) 2002-2009, Linden Research, Inc.
 *
 * Second Life Viewer Source Code
 * The source code in this file ("Source Code") is provided by Linden Lab
 * to you under the terms of the GNU General Public License, version 2.0
 * ("GPL"), unless you have obtained a separate licensing agreement
 * ("Other License"), formally executed by you and Linden Lab.  Terms of
 * the GPL can be found in doc/GPL-license.txt in this distribution, or
 * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
 *
 * There are special exceptions to the terms and conditions of the GPL as
 * it is applied to this Source Code. View the full text of the exception
 * in the file doc/FLOSS-exception.txt in this software distribution, or
 * online at
 * http://secondlifegrid.net/programs/open_source/licensing/flossexception
 *
 * By copying, modifying or distributing this software, you acknowledge
 * that you have read and understood your obligations described above,
 * and agree to abide by those obligations.
 *
 * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
 * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
 * COMPLETENESS OR PERFORMANCE.
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"

#include "llfloatervoiceeffect.h"

#include "llscrolllistctrl.h"
#include "lltrans.h"
#include "llweb.h"

LLFloaterVoiceEffect::LLFloaterVoiceEffect(const LLSD& key)
	: LLFloater(key)
{
	mCommitCallbackRegistrar.add("VoiceEffect.Record",	boost::bind(&LLFloaterVoiceEffect::onClickRecord, this));
	mCommitCallbackRegistrar.add("VoiceEffect.Play",	boost::bind(&LLFloaterVoiceEffect::onClickPlay, this));
	mCommitCallbackRegistrar.add("VoiceEffect.Stop",	boost::bind(&LLFloaterVoiceEffect::onClickStop, this));
	mCommitCallbackRegistrar.add("VoiceEffect.Add",		boost::bind(&LLFloaterVoiceEffect::onClickAdd, this));
//	mCommitCallbackRegistrar.add("VoiceEffect.Activate", boost::bind(&LLFloaterVoiceEffect::onClickActivate, this));
}

// virtual
LLFloaterVoiceEffect::~LLFloaterVoiceEffect()
{
	if(LLVoiceClient::instanceExists())
	{
		LLVoiceEffectInterface* effect_interface = LLVoiceClient::instance().getVoiceEffectInterface();
		if (effect_interface)
		{
			effect_interface->removeObserver(this);
		}
	}
}

// virtual
BOOL LLFloaterVoiceEffect::postBuild()
{
	setDefaultBtn("record_btn");
	getChild<LLButton>("record_btn")->setFocus(true);

	mVoiceEffectList = getChild<LLScrollListCtrl>("voice_effect_list");
	if (mVoiceEffectList)
	{
		mVoiceEffectList->setCommitCallback(boost::bind(&LLFloaterVoiceEffect::onClickPlay, this));
//		mVoiceEffectList->setDoubleClickCallback(boost::bind(&LLFloaterVoiceEffect::onClickActivate, this));
	}

	LLVoiceEffectInterface* effect_interface = LLVoiceClient::instance().getVoiceEffectInterface();
	if (effect_interface)
	{
		effect_interface->addObserver(this);

		// Disconnect from the current voice channel ready to record a voice sample for previewing
		effect_interface->enablePreviewBuffer(true);
	}

	refreshEffectList();
	updateControls();

	return TRUE;
}

// virtual
void LLFloaterVoiceEffect::onClose(bool app_quitting)
{
	LLVoiceEffectInterface* effect_interface = LLVoiceClient::instance().getVoiceEffectInterface();
	if (effect_interface)
	{
		effect_interface->enablePreviewBuffer(false);
	}
}

void LLFloaterVoiceEffect::refreshEffectList()
{
	if (!mVoiceEffectList)
	{
		return;
	}

	LLVoiceEffectInterface* effect_interface = LLVoiceClient::instance().getVoiceEffectInterface();
	if (!effect_interface)
	{
		mVoiceEffectList->setEnabled(false);
		return;
	}

	LL_DEBUGS("Voice")<< "Rebuilding voice effect list."<< LL_ENDL;

	// Preserve selected items and scroll position
	S32 scroll_pos = mVoiceEffectList->getScrollPos();
	uuid_vec_t selected_items;
	std::vector<LLScrollListItem*> items = mVoiceEffectList->getAllSelected();
	for(std::vector<LLScrollListItem*>::const_iterator it = items.begin(); it != items.end(); it++)
	{
		selected_items.push_back((*it)->getUUID());
	}

	mVoiceEffectList->deleteAllItems();

	{
		// Add the "No Voice Effect" entry
		LLSD element;

		element["id"] = LLUUID::null;
		element["columns"][0]["column"] = "name";
		element["columns"][0]["value"] = getString("no_voice_effect");
		element["columns"][0]["font"]["name"] = "SANSSERIF";
		element["columns"][0]["font"]["style"] = "ITALIC";

		LLScrollListItem* sl_item = mVoiceEffectList->addElement(element, ADD_BOTTOM);
		// *HACK: Copied from llfloatergesture.cpp : ["font"]["style"] does not affect font style :(
		if(sl_item)
		{
			((LLScrollListText*)sl_item->getColumn(0))->setFontStyle(LLFontGL::BOLD);
		}
	}

	const voice_effect_list_t& template_list = effect_interface->getVoiceEffectTemplateList();
	if (!template_list.empty())
	{
		for (voice_effect_list_t::const_iterator it = template_list.begin(); it != template_list.end(); ++it)
		{
			const LLUUID& effect_id = it->second;
			std::string effect_name = it->first;

			LLSD effect_properties = effect_interface->getVoiceEffectProperties(effect_id);

			// Tag the active effect.
			if (effect_id == LLVoiceClient::instance().getVoiceEffectDefault())
			{
				effect_name += " " + getString("active_voice_effect");
			}

			LLDate expiry_date = effect_properties["expiry_date"].asDate();
			bool is_template_only = effect_properties["template_only"].asBoolean();
			bool is_new = effect_properties["is_new"].asBoolean();

			std::string font_style = "NORMAL";
			if (!is_template_only)
			{
				font_style = "BOLD";
			}
			LLSD element;
			element["id"] = effect_id;

			element["columns"][0]["column"] = "name";
			element["columns"][0]["value"] = effect_name;
			element["columns"][0]["font"]["name"] = "SANSSERIF";
			element["columns"][0]["font"]["style"] = font_style;

			element["columns"][1]["column"] = "new";
			element["columns"][1]["value"] = is_new ? getString("new_voice_effect") : "";
			element["columns"][1]["font"]["name"] = "SANSSERIF";
			element["columns"][1]["font"]["style"] = font_style;

			element["columns"][2]["column"] = "expires";
			if (!is_template_only)
			{
				element["columns"][2]["value"] = expiry_date;
			}
			else {
				element["columns"][2]["value"] = "";
			}
			element["columns"][2]["font"]["name"] = "SANSSERIF";
			element["columns"][2]["font"]["style"] = font_style;

			LLScrollListItem* sl_item = mVoiceEffectList->addElement(element, ADD_BOTTOM);
			// *HACK: Copied from llfloatergesture.cpp : ["font"]["style"] does not affect font style :(
			if(sl_item)
			{
				LLFontGL::StyleFlags style = is_template_only ? LLFontGL::NORMAL : LLFontGL::BOLD;
				((LLScrollListText*)sl_item->getColumn(0))->setFontStyle(style);
			}
		}
	}

	// Re-select items that were selected before, and restore the scroll position
	for(uuid_vec_t::iterator it = selected_items.begin(); it != selected_items.end(); it++)
	{
		mVoiceEffectList->selectByID(*it);
	}
	mVoiceEffectList->setScrollPos(scroll_pos);
	mVoiceEffectList->setEnabled(true);
}

void LLFloaterVoiceEffect::updateControls()
{
	bool recording = false;

	LLVoiceEffectInterface* effect_interface = LLVoiceClient::instance().getVoiceEffectInterface();
	if (effect_interface)
	{
		recording = effect_interface->isPreviewRecording();
	}

	getChild<LLButton>("record_btn")->setVisible(!recording);
	getChild<LLButton>("record_stop_btn")->setVisible(recording);
}

// virtual
void LLFloaterVoiceEffect::onVoiceEffectChanged(bool effect_list_updated)
{
	if (effect_list_updated)
	{
		refreshEffectList();
	}
	updateControls();
}

void LLFloaterVoiceEffect::onClickRecord()
{
	LL_DEBUGS("Voice") << "Record clicked" << LL_ENDL;
	LLVoiceEffectInterface* effect_interface = LLVoiceClient::instance().getVoiceEffectInterface();
	if (effect_interface)
	{
		effect_interface->recordPreviewBuffer();
	}
	updateControls();
}

void LLFloaterVoiceEffect::onClickPlay()
{
	LL_DEBUGS("Voice") << "Play clicked" << LL_ENDL;
	if (!mVoiceEffectList)
	{
		return;
	}

	const LLUUID& effect_id = mVoiceEffectList->getCurrentID();

	LLVoiceEffectInterface* effect_interface = LLVoiceClient::instance().getVoiceEffectInterface();
	if (effect_interface)
	{
		effect_interface->playPreviewBuffer(effect_id);
	}
	updateControls();
}

void LLFloaterVoiceEffect::onClickStop()
{
	LL_DEBUGS("Voice") << "Stop clicked" << LL_ENDL;
	LLVoiceEffectInterface* effect_interface = LLVoiceClient::instance().getVoiceEffectInterface();
	if (effect_interface)
	{
		effect_interface->stopPreviewBuffer();
	}
	updateControls();
}

void LLFloaterVoiceEffect::onClickAdd()
{
	// Open the voice morphing info web page
	LLWeb::loadURL(LLTrans::getString("voice_morphing_url"));
}

//void LLFloaterVoiceEffect::onClickActivate()
//{
//	LLVoiceEffectInterface* effect_interface = LLVoiceClient::instance().getVoiceEffectInterface();
//	if (effect_interface && mVoiceEffectList)
//	{
//		effect_interface->setVoiceEffect(mVoiceEffectList->getCurrentID());
//	}
//}

<|endoftext|>


<commit_before>#include "blackhole/detail/sink/asynchronous.hpp"

#include <cmath>
#include <condition_variable>
#include <mutex>

namespace blackhole {
inline namespace v1 {
namespace experimental {
namespace sink {
namespace {

auto exp2(std::size_t factor) -> std::size_t {
    if (factor > 20) {
        throw std::invalid_argument("factor should fit in [0; 20] range");
    }

    return static_cast<std::size_t>(std::exp2(factor));
}

}  // namespace

class drop_overflow_policy_t : public overflow_policy_t {
    typedef overflow_policy_t::action_t action_t;

public:
    /// Drops on overlow.
    virtual auto overflow() -> action_t {
        return action_t::drop;
    }

    /// Does nothing on wakeup.
    virtual auto wakeup() -> void {}
};

class wait_overflow_policy_t : public overflow_policy_t {
    typedef overflow_policy_t::action_t action_t;

    mutable std::mutex mutex;
    std::condition_variable cv;

public:
    virtual auto overflow() -> action_t {
        std::unique_lock<std::mutex> lock(mutex);
        cv.wait(lock);
        return action_t::retry;
    }

    virtual auto wakeup() -> void {
        cv.notify_one();
    }
};

asynchronous_t::asynchronous_t(std::unique_ptr<sink_t> wrapped, std::size_t factor) :
    queue(exp2(factor)),
    stopped(false),
    wrapped(std::move(wrapped)),
    overflow_policy(new wait_overflow_policy_t),
    thread(std::bind(&asynchronous_t::run, this))
{}

asynchronous_t::~asynchronous_t() {
    stopped.store(true);
    thread.join();
}

auto asynchronous_t::emit(const record_t& record, const string_view& message) -> void {
    while (true) {
        // TODO: Uncomment.
        // switch (filter->filter(record, message)) {
        // case filter_t::accept:
        // case filter_t::neutral:
        //     break;
        // case filter_t::reject:
        //     return;
        // }

        const auto enqueued = queue.enqueue_with([&](value_type& value) {
            value = {recordbuf_t(record), message.to_string()};
        });

        if (enqueued) {
            // TODO: underflow_policy->wakeup();
            return;
        } else {
            switch (overflow_policy->overflow()) {
            case overflow_policy_t::action_t::retry:
                continue;
            case overflow_policy_t::action_t::drop:
                return;
            }
        }
    }
}

auto asynchronous_t::run() -> void {
    while (true) {
        value_type result;
        const auto dequeued = queue.dequeue_with([&](value_type& value) {
            result = std::move(value);
        });

        if (stopped && !dequeued) {
            return;
        }

        if (dequeued) {
            try {
                wrapped->emit(result.record.into_view(), result.message);
                overflow_policy->wakeup();
            } catch (...) {
                throw;
                // TODO: exception_policy->process();
            }
        } else {
            ::usleep(1000);
            // TODO: underflow_policy->underflow(); [wait for enqueue, sleep].
        }
    }
}

}  // namespace sink
}  // namespace experimental
}  // namespace v1
}  // namespace blackhole
<commit_msg>fix: fixed potential deadlock<commit_after>#include "blackhole/detail/sink/asynchronous.hpp"

#include <cmath>
#include <condition_variable>
#include <mutex>

namespace blackhole {
inline namespace v1 {
namespace experimental {
namespace sink {
namespace {

auto exp2(std::size_t factor) -> std::size_t {
    if (factor > 20) {
        throw std::invalid_argument("factor should fit in [0; 20] range");
    }

    return static_cast<std::size_t>(std::exp2(factor));
}

}  // namespace

class drop_overflow_policy_t : public overflow_policy_t {
    typedef overflow_policy_t::action_t action_t;

public:
    /// Drops on overlow.
    virtual auto overflow() -> action_t {
        return action_t::drop;
    }

    /// Does nothing on wakeup.
    virtual auto wakeup() -> void {}
};

class wait_overflow_policy_t : public overflow_policy_t {
    typedef overflow_policy_t::action_t action_t;

    mutable std::mutex mutex;
    std::condition_variable cv;

public:
    virtual auto overflow() -> action_t {
        std::unique_lock<std::mutex> lock(mutex);
        cv.wait_for(lock, std::chrono::milliseconds(1));
        return action_t::retry;
    }

    virtual auto wakeup() -> void {
        cv.notify_one();
    }
};

asynchronous_t::asynchronous_t(std::unique_ptr<sink_t> wrapped, std::size_t factor) :
    queue(exp2(factor)),
    stopped(false),
    wrapped(std::move(wrapped)),
    overflow_policy(new wait_overflow_policy_t),
    thread(std::bind(&asynchronous_t::run, this))
{}

asynchronous_t::~asynchronous_t() {
    stopped.store(true);
    thread.join();
}

auto asynchronous_t::emit(const record_t& record, const string_view& message) -> void {
    while (true) {
        // TODO: Uncomment.
        // switch (filter->filter(record, message)) {
        // case filter_t::accept:
        // case filter_t::neutral:
        //     break;
        // case filter_t::reject:
        //     return;
        // }

        const auto enqueued = queue.enqueue_with([&](value_type& value) {
            value = {recordbuf_t(record), message.to_string()};
        });

        if (enqueued) {
            // TODO: underflow_policy->wakeup();
            return;
        } else {
            switch (overflow_policy->overflow()) {
            case overflow_policy_t::action_t::retry:
                continue;
            case overflow_policy_t::action_t::drop:
                return;
            }
        }
    }
}

auto asynchronous_t::run() -> void {
    while (true) {
        value_type result;
        const auto dequeued = queue.dequeue_with([&](value_type& value) {
            result = std::move(value);
        });

        if (stopped && !dequeued) {
            return;
        }

        if (dequeued) {
            try {
                wrapped->emit(result.record.into_view(), result.message);
                overflow_policy->wakeup();
            } catch (...) {
                throw;
                // TODO: exception_policy->process();
            }
        } else {
            ::usleep(1000);
            // TODO: underflow_policy->underflow(); [wait for enqueue, sleep].
        }
    }
}

}  // namespace sink
}  // namespace experimental
}  // namespace v1
}  // namespace blackhole
<|endoftext|>


<commit_before>#include "../../../inc/slib/ui/scroll_view.h"
#include "../../../inc/slib/ui/core.h"

SLIB_UI_NAMESPACE_BEGIN

SLIB_DEFINE_OBJECT(ScrollView, View)

ScrollView::ScrollView()
{
	SLIB_REFERABLE_CONSTRUCTOR

	setCreatingNativeWidget(sl_true);
	setCreatingChildInstances(sl_false);
	setBorder(sl_true, UIUpdateMode::Init);

	m_flagPaging = sl_false;
	m_pageWidth = 0;
	m_pageHeight = 0;

	setHorizontalScrolling(sl_true);
	setVerticalScrolling(sl_true);
}

Ref<View> ScrollView::getContentView()
{
	return m_viewContent;
}

void ScrollView::setContentView(const Ref<slib::View>& view, UIUpdateMode mode)
{
	ObjectLocker lock(this);
	if (m_viewContent != view) {
		Ref<View> viewOld = m_viewContent;
		removeChild(viewOld, UIUpdateMode::NoRedraw);
		m_viewContent = view;
		if (view.isNotNull()) {
			view->setParent(this);
			view->setCreatingInstance(sl_true);
			view->setAttachMode(UIAttachMode::NotAttach);
			if (mode == UIUpdateMode::Init) {
				addChild(view, UIUpdateMode::Init);
			} else {
				addChild(view, UIUpdateMode::NoRedraw);
			}
			View::setContentSize(view->getWidth(), view->getHeight(), UIUpdateMode::NoRedraw);
		} else {
			View::setContentSize(0, 0, UIUpdateMode::NoRedraw);
		}
		if (mode != UIUpdateMode::Init) {
			if (isNativeWidget()) {
				if (UI::isUiThread()) {
					_setContentView_NW(view);
				} else {
					UI::dispatchToUiThread(SLIB_BIND_WEAKREF(void(), ScrollView, _setContentView_NW, this, view));
				}
			} else {
				UIPoint pt = View::getScrollPosition();
				_scrollTo(pt.x, pt.y, UIUpdateMode::NoRedraw);
				if (mode == UIUpdateMode::Redraw) {
					invalidate();
				}
			}
		}
	}
}

void ScrollView::setContentSize(sl_scroll_pos _width, sl_scroll_pos _height, UIUpdateMode mode)
{
	sl_ui_pos width = (sl_ui_pos)(_width);
	if (width < 0) {
		width = 0;
	}
	sl_ui_pos height = (sl_ui_pos)(_height);
	if (height < 0) {
		height = 0;
	}
	ObjectLocker lock(this);
	Ref<View> viewContent = m_viewContent;
	if (viewContent.isNotNull()) {
		if (mode == UIUpdateMode::Init) {
			viewContent->setSize(width, height, UIUpdateMode::Init);
		} else {
			viewContent->setSize(width, height, UIUpdateMode::NoRedraw);
		}
	}
	View::setContentSize(_width, _height, mode);
	if (isNativeWidget()) {
		_refreshContentSize_NW();
	}
}

void ScrollView::setContentSize(const ScrollPoint& size, UIUpdateMode mode)
{
	setContentSize(size.x, size.y, mode);
}

ScrollPoint ScrollView::getScrollPosition()
{
	if (isNativeWidget()) {
		return _getScrollPosition_NW();
	}
	return View::getScrollPosition();
}

ScrollPoint ScrollView::getScrollRange()
{
	if (isNativeWidget()) {
		return _getScrollRange_NW();
	}
	return View::getScrollRange();
}

void ScrollView::scrollTo(sl_scroll_pos x, sl_scroll_pos y, UIUpdateMode mode)
{
	_scrollTo(x, y, UIUpdateMode::NoRedraw);
	View::scrollTo(x, y, mode);
}

void ScrollView::scrollTo(const ScrollPoint& position, UIUpdateMode mode)
{
	scrollTo(position.x, position.y, mode);
}

sl_bool ScrollView::isPaging()
{
	return m_flagPaging;
}

void ScrollView::setPaging(sl_bool flagPaging)
{
	m_flagPaging = flagPaging;
	_updatePaging();
}

sl_ui_len ScrollView::getPageWidth()
{
	return m_pageWidth;
}

void ScrollView::setPageWidth(sl_ui_len width)
{
	m_pageWidth = width;
	_updatePaging();
}

sl_ui_len ScrollView::getPageHeight()
{
	return m_pageHeight;
}

void ScrollView::setPageHeight(sl_ui_len height)
{
	m_pageHeight = height;
	_updatePaging();
}

void ScrollView::setScrollBarsVisible(sl_bool flagHorizontal, sl_bool flagVertical, UIUpdateMode mode)
{
	View::setScrollBarsVisible(flagHorizontal, flagVertical, mode);
	_setScrollBarsVisible_NW(flagHorizontal, flagVertical);
}

void ScrollView::_updatePaging()
{
	_setPaging_NW(m_flagPaging, m_pageWidth, m_pageHeight);
}

void ScrollView::onResize(sl_ui_len width, sl_ui_len height)
{
	if (isNativeWidget()) {
		_refreshContentSize_NW();
	}
}

void ScrollView::onResizeChild(View* child, sl_ui_len width, sl_ui_len height)
{
	if (child == m_viewContent) {
		View::setContentSize(width, height);
		if (isNativeWidget()) {
			_refreshContentSize_NW();
		}
	}
}

void ScrollView::onMeasureLayout(sl_bool flagHorizontal, sl_bool flagVertical)
{
}

void ScrollView::onMakeLayout()
{
}

void ScrollView::_scrollTo(sl_scroll_pos x, sl_scroll_pos y, UIUpdateMode mode)
{
	Ref<View> view = m_viewContent;
	if (view.isNotNull()) {
		if (isNativeWidget()) {
			_scrollTo_NW(x, y);
		} else {
			sl_ui_len w = getWidth();
			sl_ui_len cw = view->getWidth();
			if (cw > w) {
				sl_ui_pos rx = cw - w;
				if (x > (sl_scroll_pos)rx) {
					x = rx;
				}
				if (x < 0) {
					x = 0;
				}
			} else {
				x = 0;
			}
			sl_ui_len h = getHeight();
			sl_ui_len ch = view->getHeight();
			if (ch > h) {
				sl_ui_pos ry = ch - h;
				if (y > (sl_scroll_pos)ry) {
					y = ry;
				}
				if (y < 0) {
					y = 0;
				}
			} else {
				y = 0;
			}
			view->setPosition((sl_ui_pos)-x, (sl_ui_pos)-y, mode);
		}
	}
}

void ScrollView::_onScroll_NW(sl_scroll_pos x, sl_scroll_pos y)
{
	View::scrollTo(x, y, UIUpdateMode::NoRedraw);
}

#if !(defined(SLIB_PLATFORM_IS_OSX)) && !(defined(SLIB_PLATFORM_IS_IOS)) && !(defined(SLIB_PLATFORM_IS_WIN32)) && !(defined(SLIB_PLATFORM_IS_ANDROID))

Ref<ViewInstance> ScrollView::createNativeWidget(ViewInstance* parent)
{
	return sl_null;
}

void ScrollView::_refreshContentSize_NW()
{
}

void ScrollView::_setContentView_NW(const Ref<View>& view)
{
}

void ScrollView::_scrollTo_NW(sl_scroll_pos x, sl_scroll_pos y)
{
}

ScrollPoint ScrollView::_getScrollPosition_NW()
{
	return ScrollPoint::zero();
}

ScrollPoint ScrollView::_getScrollRange_NW()
{
	return ScrollPoint::zero();
}

void ScrollView::_setBorder_NW(sl_bool flag)
{
}

void ScrollView::_setBackgroundColor_NW(const Color& color)
{
}

#endif

#if !(defined(SLIB_PLATFORM_IS_IOS)) && !(defined(SLIB_PLATFORM_IS_ANDROID))

void ScrollView::_setPaging_NW(sl_bool flagPaging, sl_ui_len pageWidth, sl_ui_len pageHeight)
{
}

void ScrollView::_setScrollBarsVisible_NW(sl_bool flagHorizontal, sl_bool flagVertical)
{
}

#endif

HorizontalScrollView::HorizontalScrollView()
{
	setHorizontalScrolling(sl_true);
	setVerticalScrolling(sl_false);
}

VerticalScrollView::VerticalScrollView()
{
	setHorizontalScrolling(sl_false);
	setVerticalScrolling(sl_true);
}

SLIB_UI_NAMESPACE_END
<commit_msg>setMakingLayout in scrollview<commit_after>#include "../../../inc/slib/ui/scroll_view.h"
#include "../../../inc/slib/ui/core.h"

SLIB_UI_NAMESPACE_BEGIN

SLIB_DEFINE_OBJECT(ScrollView, View)

ScrollView::ScrollView()
{
	SLIB_REFERABLE_CONSTRUCTOR

	setCreatingNativeWidget(sl_true);
	setCreatingChildInstances(sl_false);
    setMakingLayout(sl_true, UIUpdateMode::Init);
    setBorder(sl_true, UIUpdateMode::Init);

	m_flagPaging = sl_false;
	m_pageWidth = 0;
	m_pageHeight = 0;

	setHorizontalScrolling(sl_true);
	setVerticalScrolling(sl_true);

}

Ref<View> ScrollView::getContentView()
{
	return m_viewContent;
}

void ScrollView::setContentView(const Ref<slib::View>& view, UIUpdateMode mode)
{
	ObjectLocker lock(this);
	if (m_viewContent != view) {
		Ref<View> viewOld = m_viewContent;
		removeChild(viewOld, UIUpdateMode::NoRedraw);
		m_viewContent = view;
		if (view.isNotNull()) {
			view->setParent(this);
			view->setCreatingInstance(sl_true);
			view->setAttachMode(UIAttachMode::NotAttach);
			if (mode == UIUpdateMode::Init) {
				addChild(view, UIUpdateMode::Init);
			} else {
				addChild(view, UIUpdateMode::NoRedraw);
			}
			View::setContentSize(view->getWidth(), view->getHeight(), UIUpdateMode::NoRedraw);
		} else {
			View::setContentSize(0, 0, UIUpdateMode::NoRedraw);
		}
		if (mode != UIUpdateMode::Init) {
			if (isNativeWidget()) {
				if (UI::isUiThread()) {
					_setContentView_NW(view);
				} else {
					UI::dispatchToUiThread(SLIB_BIND_WEAKREF(void(), ScrollView, _setContentView_NW, this, view));
				}
			} else {
				UIPoint pt = View::getScrollPosition();
				_scrollTo(pt.x, pt.y, UIUpdateMode::NoRedraw);
				if (mode == UIUpdateMode::Redraw) {
					invalidate();
				}
			}
		}
	}
}

void ScrollView::setContentSize(sl_scroll_pos _width, sl_scroll_pos _height, UIUpdateMode mode)
{
	sl_ui_pos width = (sl_ui_pos)(_width);
	if (width < 0) {
		width = 0;
	}
	sl_ui_pos height = (sl_ui_pos)(_height);
	if (height < 0) {
		height = 0;
	}
	ObjectLocker lock(this);
	Ref<View> viewContent = m_viewContent;
	if (viewContent.isNotNull()) {
		if (mode == UIUpdateMode::Init) {
			viewContent->setSize(width, height, UIUpdateMode::Init);
		} else {
			viewContent->setSize(width, height, UIUpdateMode::NoRedraw);
		}
	}
	View::setContentSize(_width, _height, mode);
	if (isNativeWidget()) {
		_refreshContentSize_NW();
	}
}

void ScrollView::setContentSize(const ScrollPoint& size, UIUpdateMode mode)
{
	setContentSize(size.x, size.y, mode);
}

ScrollPoint ScrollView::getScrollPosition()
{
	if (isNativeWidget()) {
		return _getScrollPosition_NW();
	}
	return View::getScrollPosition();
}

ScrollPoint ScrollView::getScrollRange()
{
	if (isNativeWidget()) {
		return _getScrollRange_NW();
	}
	return View::getScrollRange();
}

void ScrollView::scrollTo(sl_scroll_pos x, sl_scroll_pos y, UIUpdateMode mode)
{
	_scrollTo(x, y, UIUpdateMode::NoRedraw);
	View::scrollTo(x, y, mode);
}

void ScrollView::scrollTo(const ScrollPoint& position, UIUpdateMode mode)
{
	scrollTo(position.x, position.y, mode);
}

sl_bool ScrollView::isPaging()
{
	return m_flagPaging;
}

void ScrollView::setPaging(sl_bool flagPaging)
{
	m_flagPaging = flagPaging;
	_updatePaging();
}

sl_ui_len ScrollView::getPageWidth()
{
	return m_pageWidth;
}

void ScrollView::setPageWidth(sl_ui_len width)
{
	m_pageWidth = width;
	_updatePaging();
}

sl_ui_len ScrollView::getPageHeight()
{
	return m_pageHeight;
}

void ScrollView::setPageHeight(sl_ui_len height)
{
	m_pageHeight = height;
	_updatePaging();
}

void ScrollView::setScrollBarsVisible(sl_bool flagHorizontal, sl_bool flagVertical, UIUpdateMode mode)
{
	View::setScrollBarsVisible(flagHorizontal, flagVertical, mode);
	_setScrollBarsVisible_NW(flagHorizontal, flagVertical);
}

void ScrollView::_updatePaging()
{
	_setPaging_NW(m_flagPaging, m_pageWidth, m_pageHeight);
}

void ScrollView::onResize(sl_ui_len width, sl_ui_len height)
{
	if (isNativeWidget()) {
		_refreshContentSize_NW();
	}
}

void ScrollView::onResizeChild(View* child, sl_ui_len width, sl_ui_len height)
{
	if (child == m_viewContent) {
		View::setContentSize(width, height);
		if (isNativeWidget()) {
			_refreshContentSize_NW();
		}
	}
}

void ScrollView::onMeasureLayout(sl_bool flagHorizontal, sl_bool flagVertical)
{
}

void ScrollView::onMakeLayout()
{
}

void ScrollView::_scrollTo(sl_scroll_pos x, sl_scroll_pos y, UIUpdateMode mode)
{
	Ref<View> view = m_viewContent;
	if (view.isNotNull()) {
		if (isNativeWidget()) {
			_scrollTo_NW(x, y);
		} else {
			sl_ui_len w = getWidth();
			sl_ui_len cw = view->getWidth();
			if (cw > w) {
				sl_ui_pos rx = cw - w;
				if (x > (sl_scroll_pos)rx) {
					x = rx;
				}
				if (x < 0) {
					x = 0;
				}
			} else {
				x = 0;
			}
			sl_ui_len h = getHeight();
			sl_ui_len ch = view->getHeight();
			if (ch > h) {
				sl_ui_pos ry = ch - h;
				if (y > (sl_scroll_pos)ry) {
					y = ry;
				}
				if (y < 0) {
					y = 0;
				}
			} else {
				y = 0;
			}
			view->setPosition((sl_ui_pos)-x, (sl_ui_pos)-y, mode);
		}
	}
}

void ScrollView::_onScroll_NW(sl_scroll_pos x, sl_scroll_pos y)
{
	View::scrollTo(x, y, UIUpdateMode::NoRedraw);
}

#if !(defined(SLIB_PLATFORM_IS_OSX)) && !(defined(SLIB_PLATFORM_IS_IOS)) && !(defined(SLIB_PLATFORM_IS_WIN32)) && !(defined(SLIB_PLATFORM_IS_ANDROID))

Ref<ViewInstance> ScrollView::createNativeWidget(ViewInstance* parent)
{
	return sl_null;
}

void ScrollView::_refreshContentSize_NW()
{
}

void ScrollView::_setContentView_NW(const Ref<View>& view)
{
}

void ScrollView::_scrollTo_NW(sl_scroll_pos x, sl_scroll_pos y)
{
}

ScrollPoint ScrollView::_getScrollPosition_NW()
{
	return ScrollPoint::zero();
}

ScrollPoint ScrollView::_getScrollRange_NW()
{
	return ScrollPoint::zero();
}

void ScrollView::_setBorder_NW(sl_bool flag)
{
}

void ScrollView::_setBackgroundColor_NW(const Color& color)
{
}

#endif

#if !(defined(SLIB_PLATFORM_IS_IOS)) && !(defined(SLIB_PLATFORM_IS_ANDROID))

void ScrollView::_setPaging_NW(sl_bool flagPaging, sl_ui_len pageWidth, sl_ui_len pageHeight)
{
}

void ScrollView::_setScrollBarsVisible_NW(sl_bool flagHorizontal, sl_bool flagVertical)
{
}

#endif

HorizontalScrollView::HorizontalScrollView()
{
	setHorizontalScrolling(sl_true);
	setVerticalScrolling(sl_false);
}

VerticalScrollView::VerticalScrollView()
{
	setHorizontalScrolling(sl_false);
	setVerticalScrolling(sl_true);
}

SLIB_UI_NAMESPACE_END
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the QtLocation module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qgeopositioninfosource.h>
#include "qgeopositioninfosource_p.h"
#include "qgeopositioninfosourcefactory.h"

#include <QFile>
#include <QPluginLoader>
#include <QStringList>
#include <QJsonObject>
#include <QCryptographicHash>
#include <QtCore/private/qfactoryloader_p.h>
#include <QtCore/private/qlibrary_p.h>

QT_BEGIN_NAMESPACE

#ifndef QT_NO_LIBRARY
Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader,
        ("org.qt-project.qt.position.sourcefactory/5.0",
         QStringLiteral("/position")))
#endif

/*!
    \class QGeoPositionInfoSource
    \inmodule QtLocation
    \ingroup QtLocation-positioning
    \since Qt Location 5.0

    \brief The QGeoPositionInfoSource class is an abstract base class for the distribution of positional updates.

    The static function QGeoPositionInfoSource::createDefaultSource() creates a default
    position source that is appropriate for the platform, if one is available.
    Otherwise, QGeoPositionInfoSource will check for available plugins that
    implement the QGeoPositionInfoSourceFactory interface.

    Users of a QGeoPositionInfoSource subclass can request the current position using
    requestUpdate(), or start and stop regular position updates using
    startUpdates() and stopUpdates(). When an update is available,
    positionUpdated() is emitted. The last known position can be accessed with
    lastKnownPosition().

    If regular position updates are required, setUpdateInterval() can be used
    to specify how often these updates should be emitted. If no interval is
    specified, updates are simply provided whenever they are available.
    For example:

    \code
        // Emit updates every 10 seconds if available
        QGeoPositionInfoSource *source = QGeoPositionInfoSource::createDefaultSource(0);
        if (source)
            source->setUpdateInterval(10000);
    \endcode

    To remove an update interval that was previously set, call
    setUpdateInterval() with a value of 0.

    Note that the position source may have a minimum value requirement for
    update intervals, as returned by minimumUpdateInterval().

    \warning On Windows CE it is not possible to detect if a device is GPS enabled.
    The default position source on a Windows CE device without GPS support will never provide any position data.
*/

/*!
    \enum QGeoPositionInfoSource::PositioningMethod
    Defines the types of positioning methods.

    \value SatellitePositioningMethods Satellite-based positioning methods such as GPS or GLONASS.
    \value NonSatellitePositioningMethods Other positioning methods such as 3GPP cell identifier or WiFi based positioning.
    \value AllPositioningMethods Satellite-based positioning methods as soon as available. Otherwise non-satellite based methods.
*/

void QGeoPositionInfoSourcePrivate::loadMeta()
{
    metaData = plugins().value(providerName);
}

void QGeoPositionInfoSourcePrivate::loadPlugin()
{
    int idx = int(metaData.value(QStringLiteral("index")).toDouble());
    if (idx < 0)
        return;
    factory = qobject_cast<QGeoPositionInfoSourceFactory *>(loader()->instance(idx));
}

QHash<QString, QJsonObject> QGeoPositionInfoSourcePrivate::plugins(bool reload)
{
    static QHash<QString, QJsonObject> plugins;
    static bool alreadyDiscovered = false;

    if (reload == true)
        alreadyDiscovered = false;

    if (!alreadyDiscovered) {
        loadPluginMetadata(plugins);
        alreadyDiscovered = true;
    }
    return plugins;
}

static bool pluginComparator(const QJsonObject &p1, const QJsonObject &p2)
{
    const QString prio = QStringLiteral("Priority");
    if (p1.contains(prio) && !p2.contains(prio))
        return true;
    if (!p1.contains(prio) && p2.contains(prio))
        return false;
    if (p1.value(prio).isDouble() && !p2.value(prio).isDouble())
        return true;
    if (!p1.value(prio).isDouble() && p2.value(prio).isDouble())
        return false;
    return (p1.value(prio).toDouble() > p2.value(prio).toDouble());
}

QList<QJsonObject> QGeoPositionInfoSourcePrivate::pluginsSorted()
{
    QList<QJsonObject> list = plugins().values();
    qStableSort(list.begin(), list.end(), pluginComparator);
    return list;
}

void QGeoPositionInfoSourcePrivate::loadPluginMetadata(QHash<QString, QJsonObject> &plugins)
{
    QFactoryLoader *l = loader();
    QList<QJsonObject> meta = l->metaData();
    for (int i = 0; i < meta.size(); ++i) {
        QJsonObject obj = meta.at(i).value(QStringLiteral("MetaData")).toObject();
        obj.insert(QStringLiteral("index"), i);
        plugins.insertMulti(obj.value(QStringLiteral("Provider")).toString(), obj);
    }
}

/*!
    Creates a position source with the specified \a parent.
*/

QGeoPositionInfoSource::QGeoPositionInfoSource(QObject *parent)
        : QObject(parent),
        d(new QGeoPositionInfoSourcePrivate)
{
    d->interval = 0;
    d->methods = 0;
}

/*!
    Destroys the position source.
*/
QGeoPositionInfoSource::~QGeoPositionInfoSource()
{
    delete d;
}

/*!
    \property QGeoPositionInfoSource::sourceName
    \brief This property holds the unique name of the position source
           implementation in use.

    This is the same name that can be passed to createSource() in order to
    create a new instance of a particular position source implementation.
*/
QString QGeoPositionInfoSource::sourceName() const
{
    return d->metaData.value(QStringLiteral("Provider")).toString();
}

/*!
    \property QGeoPositionInfoSource::updateInterval
    \brief This property holds the requested interval in milliseconds between each update.

    If the update interval is not set (or is set to 0) the
    source will provide updates as often as necessary.

    If the update interval is set, the source will provide updates at an
    interval as close to the requested interval as possible. If the requested
    interval is less than the minimumUpdateInterval(),
    the minimum interval is used instead.

    Changes to the update interval will happen as soon as is practical, however the
    time the change takes may vary between implementations.  Whether or not the elapsed
    time from the previous interval is counted as part of the new interval is also
    implementation dependent.

    The default value for this property is 0.

    Note: Subclass implementations must call the base implementation of
    setUpdateInterval() so that updateInterval() returns the correct value.
*/
void QGeoPositionInfoSource::setUpdateInterval(int msec)
{
    d->interval = msec;
}

int QGeoPositionInfoSource::updateInterval() const
{
    return d->interval;
}

/*!
    Sets the preferred positioning methods for this source to \a methods.

    If \a methods includes a method that is not supported by the source, the
    unsupported method will be ignored.

    If \a methods does not include any methods supported by the source, the
    preferred methods will be set to the set of methods which the source supports.

    \b {Note:} When reimplementing this method, subclasses must call the
    base method implementation to ensure preferredPositioningMethods() returns the correct value.

    \sa supportedPositioningMethods()
*/
void QGeoPositionInfoSource::setPreferredPositioningMethods(PositioningMethods methods)
{
    d->methods = methods & supportedPositioningMethods();
    if (d->methods == 0) {
        d->methods = supportedPositioningMethods();
    }
}

/*!
    Returns the positioning methods set by setPreferredPositioningMethods().
*/
QGeoPositionInfoSource::PositioningMethods QGeoPositionInfoSource::preferredPositioningMethods() const
{
    return d->methods;
}

/*!
    Creates and returns a position source with the given \a parent that
    reads from the system's default sources of location data, or the plugin
    with the highest available priority.

    Returns 0 if the system has no default position source, no valid plugins
    could be found or the user does not have the permission to access the current position.
*/
QGeoPositionInfoSource *QGeoPositionInfoSource::createDefaultSource(QObject *parent)
{
    QGeoPositionInfoSourcePrivate *d = new QGeoPositionInfoSourcePrivate;

    QList<QJsonObject> plugins = QGeoPositionInfoSourcePrivate::pluginsSorted();
    foreach (const QJsonObject &obj, plugins) {
        if (obj.value(QStringLiteral("Position")).isBool()
                && obj.value(QStringLiteral("Position")).toBool()) {
            d->metaData = obj;
            d->loadPlugin();
            QGeoPositionInfoSource *s = d->factory->positionInfoSource(parent);
            if (s) {
                s->d->metaData = d->metaData;
                delete d;
                return s;
            }
        }
    }

    delete d;
    return 0;
}

/*!
    Creates and returns a position source with the given \a parent,
    by loading the plugin named \a sourceName.

    Returns 0 if the plugin cannot be found.
*/
QGeoPositionInfoSource *QGeoPositionInfoSource::createSource(const QString &sourceName, QObject *parent)
{
    QGeoPositionInfoSourcePrivate *d = new QGeoPositionInfoSourcePrivate;
    QHash<QString, QJsonObject> plugins = QGeoPositionInfoSourcePrivate::plugins();
    if (plugins.contains(sourceName)) {
        d->metaData = plugins.value(sourceName);
        d->loadPlugin();
        QGeoPositionInfoSource *src = d->factory->positionInfoSource(parent);
        if (src) {
            src->d->metaData = d->metaData;
            delete d;
            return src;
        }
    }

    delete d;
    return 0;
}

/*!
    Returns a list of available source plugins. This includes any default backend
    plugin for the current platform.
*/
QStringList QGeoPositionInfoSource::availableSources()
{
    QStringList plugins;
    QHash<QString, QJsonObject> meta = QGeoPositionInfoSourcePrivate::plugins();
    foreach (const QString &name, meta.keys()) {
        if (meta.value(name).value(QStringLiteral("Position")).isBool()
                && meta.value(name).value(QStringLiteral("Position")).toBool()) {
            plugins << name;
        }
    }

    return plugins;
}

/*!
    \fn QGeoPositionInfo QGeoPositionInfoSource::lastKnownPosition(bool fromSatellitePositioningMethodsOnly = false) const = 0;

    Returns an update containing the last known position, or a null update
    if none is available.

    If \a fromSatellitePositioningMethodsOnly is true, this returns the last
    known position received from a satellite positioning method; if none
    is available, a null update is returned.
*/

/*!
    \fn virtual PositioningMethods QGeoPositionInfoSource::supportedPositioningMethods() const = 0;

    Returns the positioning methods available to this source.

    \sa setPreferredPositioningMethods()
*/

/*!
    \property QGeoPositionInfoSource::minimumUpdateInterval
    \brief This property holds the minimum time (in milliseconds) required to retrieve a position update.

    This is the minimum value accepted by setUpdateInterval() and
    requestUpdate().
*/

/*!
    \fn virtual void QGeoPositionInfoSource::startUpdates() = 0;

    Starts emitting updates at regular intervals as specified by setUpdateInterval().

    If setUpdateInterval() has not been called, the source will emit updates
    as soon as they become available.

    An updateTimout() signal will be emitted if this QGeoPositionInfoSource subclass determines
    that it will not be able to provide regular updates.  This could happen if a satellite fix is
    lost or if a hardware error is detected.  Position updates will recommence if the data becomes
    available later on.  The updateTimout() signal will not be emitted again until after the
    periodic updates resume.
*/

/*!
    \fn virtual void QGeoPositionInfoSource::stopUpdates() = 0;

    Stops emitting updates at regular intervals.
*/

/*!
    \fn virtual void QGeoPositionInfoSource::requestUpdate(int timeout = 0);

    Attempts to get the current position and emit positionUpdated() with
    this information. If the current position cannot be found within the given \a timeout
    (in milliseconds) or if \a timeout is less than the value returned by
    minimumUpdateInterval(), updateTimeout() is emitted.

    If the timeout is zero, the timeout defaults to a reasonable timeout
    period as appropriate for the source.

    This does nothing if another update request is in progress. However
    it can be called even if startUpdates() has already been called and
    regular updates are in progress.

    If the source uses multiple positioning methods, it tries to get the
    current position from the most accurate positioning method within the
    given timeout.
*/

/*!
     \fn virtual QGeoPositionInfoSource::Error QGeoPositionInfoSource::error() const;

     Returns the type of error that last occurred.

*/

/*!
    \fn void QGeoPositionInfoSource::positionUpdated(const QGeoPositionInfo &update);

    If startUpdates() or requestUpdate() is called, this signal is emitted
    when an update becomes available.

    The \a update value holds the value of the new update.
*/

/*!
    \fn void QGeoPositionInfoSource::updateTimeout();

    If requestUpdate() was called, this signal will be emitted if the current position could not
    be retrieved within the specified timeout.

    If startUpdates() has been called, this signal will be emitted if this QGeoPositionInfoSource
    subclass determines that it will not be able to provide further regular updates.  This signal
    will not be emitted again until after the regular updates resume.
*/

/*!
    \fn void QGeoPositionInfoSource::error(QGeoPositionInfoSource::Error positioningError)

    This signal is emitted after an error occurred. The \a positioningError
    parameter describes the type of error that occurred.

*/

/*!
    \enum QGeoPositionInfoSource::Error

    The Error enumeration represents the errors which can occur.

    \value AccessError The connection setup to the remote positioning backend failed because the
        application lacked the required privileges.
    \value ClosedError  The remote positioning backend closed the connection, which happens for example in case
        the user is switching location services to off. This object becomes invalid and should be deleted.
        A call to createDefaultSource() can be used to create a new source later on.
    \value UnknownSourceError An unidentified error occurred.
 */

#include "moc_qgeopositioninfosource.cpp"

QT_END_NAMESPACE
<commit_msg>Q_GLOBAL_STATIC's use of noexcept makes QStringLiteral not work<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the QtLocation module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qgeopositioninfosource.h>
#include "qgeopositioninfosource_p.h"
#include "qgeopositioninfosourcefactory.h"

#include <QFile>
#include <QPluginLoader>
#include <QStringList>
#include <QJsonObject>
#include <QCryptographicHash>
#include <QtCore/private/qfactoryloader_p.h>
#include <QtCore/private/qlibrary_p.h>

QT_BEGIN_NAMESPACE

#ifndef QT_NO_LIBRARY
Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader,
        ("org.qt-project.qt.position.sourcefactory/5.0",
         QLatin1String("/position")))
#endif

/*!
    \class QGeoPositionInfoSource
    \inmodule QtLocation
    \ingroup QtLocation-positioning
    \since Qt Location 5.0

    \brief The QGeoPositionInfoSource class is an abstract base class for the distribution of positional updates.

    The static function QGeoPositionInfoSource::createDefaultSource() creates a default
    position source that is appropriate for the platform, if one is available.
    Otherwise, QGeoPositionInfoSource will check for available plugins that
    implement the QGeoPositionInfoSourceFactory interface.

    Users of a QGeoPositionInfoSource subclass can request the current position using
    requestUpdate(), or start and stop regular position updates using
    startUpdates() and stopUpdates(). When an update is available,
    positionUpdated() is emitted. The last known position can be accessed with
    lastKnownPosition().

    If regular position updates are required, setUpdateInterval() can be used
    to specify how often these updates should be emitted. If no interval is
    specified, updates are simply provided whenever they are available.
    For example:

    \code
        // Emit updates every 10 seconds if available
        QGeoPositionInfoSource *source = QGeoPositionInfoSource::createDefaultSource(0);
        if (source)
            source->setUpdateInterval(10000);
    \endcode

    To remove an update interval that was previously set, call
    setUpdateInterval() with a value of 0.

    Note that the position source may have a minimum value requirement for
    update intervals, as returned by minimumUpdateInterval().

    \warning On Windows CE it is not possible to detect if a device is GPS enabled.
    The default position source on a Windows CE device without GPS support will never provide any position data.
*/

/*!
    \enum QGeoPositionInfoSource::PositioningMethod
    Defines the types of positioning methods.

    \value SatellitePositioningMethods Satellite-based positioning methods such as GPS or GLONASS.
    \value NonSatellitePositioningMethods Other positioning methods such as 3GPP cell identifier or WiFi based positioning.
    \value AllPositioningMethods Satellite-based positioning methods as soon as available. Otherwise non-satellite based methods.
*/

void QGeoPositionInfoSourcePrivate::loadMeta()
{
    metaData = plugins().value(providerName);
}

void QGeoPositionInfoSourcePrivate::loadPlugin()
{
    int idx = int(metaData.value(QStringLiteral("index")).toDouble());
    if (idx < 0)
        return;
    factory = qobject_cast<QGeoPositionInfoSourceFactory *>(loader()->instance(idx));
}

QHash<QString, QJsonObject> QGeoPositionInfoSourcePrivate::plugins(bool reload)
{
    static QHash<QString, QJsonObject> plugins;
    static bool alreadyDiscovered = false;

    if (reload == true)
        alreadyDiscovered = false;

    if (!alreadyDiscovered) {
        loadPluginMetadata(plugins);
        alreadyDiscovered = true;
    }
    return plugins;
}

static bool pluginComparator(const QJsonObject &p1, const QJsonObject &p2)
{
    const QString prio = QStringLiteral("Priority");
    if (p1.contains(prio) && !p2.contains(prio))
        return true;
    if (!p1.contains(prio) && p2.contains(prio))
        return false;
    if (p1.value(prio).isDouble() && !p2.value(prio).isDouble())
        return true;
    if (!p1.value(prio).isDouble() && p2.value(prio).isDouble())
        return false;
    return (p1.value(prio).toDouble() > p2.value(prio).toDouble());
}

QList<QJsonObject> QGeoPositionInfoSourcePrivate::pluginsSorted()
{
    QList<QJsonObject> list = plugins().values();
    qStableSort(list.begin(), list.end(), pluginComparator);
    return list;
}

void QGeoPositionInfoSourcePrivate::loadPluginMetadata(QHash<QString, QJsonObject> &plugins)
{
    QFactoryLoader *l = loader();
    QList<QJsonObject> meta = l->metaData();
    for (int i = 0; i < meta.size(); ++i) {
        QJsonObject obj = meta.at(i).value(QStringLiteral("MetaData")).toObject();
        obj.insert(QStringLiteral("index"), i);
        plugins.insertMulti(obj.value(QStringLiteral("Provider")).toString(), obj);
    }
}

/*!
    Creates a position source with the specified \a parent.
*/

QGeoPositionInfoSource::QGeoPositionInfoSource(QObject *parent)
        : QObject(parent),
        d(new QGeoPositionInfoSourcePrivate)
{
    d->interval = 0;
    d->methods = 0;
}

/*!
    Destroys the position source.
*/
QGeoPositionInfoSource::~QGeoPositionInfoSource()
{
    delete d;
}

/*!
    \property QGeoPositionInfoSource::sourceName
    \brief This property holds the unique name of the position source
           implementation in use.

    This is the same name that can be passed to createSource() in order to
    create a new instance of a particular position source implementation.
*/
QString QGeoPositionInfoSource::sourceName() const
{
    return d->metaData.value(QStringLiteral("Provider")).toString();
}

/*!
    \property QGeoPositionInfoSource::updateInterval
    \brief This property holds the requested interval in milliseconds between each update.

    If the update interval is not set (or is set to 0) the
    source will provide updates as often as necessary.

    If the update interval is set, the source will provide updates at an
    interval as close to the requested interval as possible. If the requested
    interval is less than the minimumUpdateInterval(),
    the minimum interval is used instead.

    Changes to the update interval will happen as soon as is practical, however the
    time the change takes may vary between implementations.  Whether or not the elapsed
    time from the previous interval is counted as part of the new interval is also
    implementation dependent.

    The default value for this property is 0.

    Note: Subclass implementations must call the base implementation of
    setUpdateInterval() so that updateInterval() returns the correct value.
*/
void QGeoPositionInfoSource::setUpdateInterval(int msec)
{
    d->interval = msec;
}

int QGeoPositionInfoSource::updateInterval() const
{
    return d->interval;
}

/*!
    Sets the preferred positioning methods for this source to \a methods.

    If \a methods includes a method that is not supported by the source, the
    unsupported method will be ignored.

    If \a methods does not include any methods supported by the source, the
    preferred methods will be set to the set of methods which the source supports.

    \b {Note:} When reimplementing this method, subclasses must call the
    base method implementation to ensure preferredPositioningMethods() returns the correct value.

    \sa supportedPositioningMethods()
*/
void QGeoPositionInfoSource::setPreferredPositioningMethods(PositioningMethods methods)
{
    d->methods = methods & supportedPositioningMethods();
    if (d->methods == 0) {
        d->methods = supportedPositioningMethods();
    }
}

/*!
    Returns the positioning methods set by setPreferredPositioningMethods().
*/
QGeoPositionInfoSource::PositioningMethods QGeoPositionInfoSource::preferredPositioningMethods() const
{
    return d->methods;
}

/*!
    Creates and returns a position source with the given \a parent that
    reads from the system's default sources of location data, or the plugin
    with the highest available priority.

    Returns 0 if the system has no default position source, no valid plugins
    could be found or the user does not have the permission to access the current position.
*/
QGeoPositionInfoSource *QGeoPositionInfoSource::createDefaultSource(QObject *parent)
{
    QGeoPositionInfoSourcePrivate *d = new QGeoPositionInfoSourcePrivate;

    QList<QJsonObject> plugins = QGeoPositionInfoSourcePrivate::pluginsSorted();
    foreach (const QJsonObject &obj, plugins) {
        if (obj.value(QStringLiteral("Position")).isBool()
                && obj.value(QStringLiteral("Position")).toBool()) {
            d->metaData = obj;
            d->loadPlugin();
            QGeoPositionInfoSource *s = d->factory->positionInfoSource(parent);
            if (s) {
                s->d->metaData = d->metaData;
                delete d;
                return s;
            }
        }
    }

    delete d;
    return 0;
}

/*!
    Creates and returns a position source with the given \a parent,
    by loading the plugin named \a sourceName.

    Returns 0 if the plugin cannot be found.
*/
QGeoPositionInfoSource *QGeoPositionInfoSource::createSource(const QString &sourceName, QObject *parent)
{
    QGeoPositionInfoSourcePrivate *d = new QGeoPositionInfoSourcePrivate;
    QHash<QString, QJsonObject> plugins = QGeoPositionInfoSourcePrivate::plugins();
    if (plugins.contains(sourceName)) {
        d->metaData = plugins.value(sourceName);
        d->loadPlugin();
        QGeoPositionInfoSource *src = d->factory->positionInfoSource(parent);
        if (src) {
            src->d->metaData = d->metaData;
            delete d;
            return src;
        }
    }

    delete d;
    return 0;
}

/*!
    Returns a list of available source plugins. This includes any default backend
    plugin for the current platform.
*/
QStringList QGeoPositionInfoSource::availableSources()
{
    QStringList plugins;
    QHash<QString, QJsonObject> meta = QGeoPositionInfoSourcePrivate::plugins();
    foreach (const QString &name, meta.keys()) {
        if (meta.value(name).value(QStringLiteral("Position")).isBool()
                && meta.value(name).value(QStringLiteral("Position")).toBool()) {
            plugins << name;
        }
    }

    return plugins;
}

/*!
    \fn QGeoPositionInfo QGeoPositionInfoSource::lastKnownPosition(bool fromSatellitePositioningMethodsOnly = false) const = 0;

    Returns an update containing the last known position, or a null update
    if none is available.

    If \a fromSatellitePositioningMethodsOnly is true, this returns the last
    known position received from a satellite positioning method; if none
    is available, a null update is returned.
*/

/*!
    \fn virtual PositioningMethods QGeoPositionInfoSource::supportedPositioningMethods() const = 0;

    Returns the positioning methods available to this source.

    \sa setPreferredPositioningMethods()
*/

/*!
    \property QGeoPositionInfoSource::minimumUpdateInterval
    \brief This property holds the minimum time (in milliseconds) required to retrieve a position update.

    This is the minimum value accepted by setUpdateInterval() and
    requestUpdate().
*/

/*!
    \fn virtual void QGeoPositionInfoSource::startUpdates() = 0;

    Starts emitting updates at regular intervals as specified by setUpdateInterval().

    If setUpdateInterval() has not been called, the source will emit updates
    as soon as they become available.

    An updateTimout() signal will be emitted if this QGeoPositionInfoSource subclass determines
    that it will not be able to provide regular updates.  This could happen if a satellite fix is
    lost or if a hardware error is detected.  Position updates will recommence if the data becomes
    available later on.  The updateTimout() signal will not be emitted again until after the
    periodic updates resume.
*/

/*!
    \fn virtual void QGeoPositionInfoSource::stopUpdates() = 0;

    Stops emitting updates at regular intervals.
*/

/*!
    \fn virtual void QGeoPositionInfoSource::requestUpdate(int timeout = 0);

    Attempts to get the current position and emit positionUpdated() with
    this information. If the current position cannot be found within the given \a timeout
    (in milliseconds) or if \a timeout is less than the value returned by
    minimumUpdateInterval(), updateTimeout() is emitted.

    If the timeout is zero, the timeout defaults to a reasonable timeout
    period as appropriate for the source.

    This does nothing if another update request is in progress. However
    it can be called even if startUpdates() has already been called and
    regular updates are in progress.

    If the source uses multiple positioning methods, it tries to get the
    current position from the most accurate positioning method within the
    given timeout.
*/

/*!
     \fn virtual QGeoPositionInfoSource::Error QGeoPositionInfoSource::error() const;

     Returns the type of error that last occurred.

*/

/*!
    \fn void QGeoPositionInfoSource::positionUpdated(const QGeoPositionInfo &update);

    If startUpdates() or requestUpdate() is called, this signal is emitted
    when an update becomes available.

    The \a update value holds the value of the new update.
*/

/*!
    \fn void QGeoPositionInfoSource::updateTimeout();

    If requestUpdate() was called, this signal will be emitted if the current position could not
    be retrieved within the specified timeout.

    If startUpdates() has been called, this signal will be emitted if this QGeoPositionInfoSource
    subclass determines that it will not be able to provide further regular updates.  This signal
    will not be emitted again until after the regular updates resume.
*/

/*!
    \fn void QGeoPositionInfoSource::error(QGeoPositionInfoSource::Error positioningError)

    This signal is emitted after an error occurred. The \a positioningError
    parameter describes the type of error that occurred.

*/

/*!
    \enum QGeoPositionInfoSource::Error

    The Error enumeration represents the errors which can occur.

    \value AccessError The connection setup to the remote positioning backend failed because the
        application lacked the required privileges.
    \value ClosedError  The remote positioning backend closed the connection, which happens for example in case
        the user is switching location services to off. This object becomes invalid and should be deleted.
        A call to createDefaultSource() can be used to create a new source later on.
    \value UnknownSourceError An unidentified error occurred.
 */

#include "moc_qgeopositioninfosource.cpp"

QT_END_NAMESPACE
<|endoftext|>


<commit_before>/*
 * Copyright 2018 The Cartographer Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// Publishes a frozen nav_msgs/OccupancyGrid map from serialized submaps.

#include <map>
#include <string>

#include "cartographer/io/proto_stream.h"
#include "cartographer/io/proto_stream_deserializer.h"
#include "cartographer/io/submap_painter.h"
#include "cartographer/mapping/2d/probability_grid.h"
#include "cartographer/mapping/2d/submap_2d.h"
#include "cartographer/mapping/3d/submap_3d.h"
#include "cartographer/mapping/proto/pose_graph.pb.h"
#include "cartographer/mapping/proto/serialization.pb.h"
#include "cartographer/mapping/proto/submap.pb.h"
#include "cartographer/mapping/proto/trajectory_builder_options.pb.h"
#include "cartographer_ros/msg_conversion.h"
#include "cartographer_ros/node_constants.h"
#include "cartographer_ros/ros_log_sink.h"
#include "cartographer_ros/ros_map.h"
#include "cartographer_ros/submap.h"
#include "gflags/gflags.h"
#include "glog/logging.h"
#include "nav_msgs/OccupancyGrid.h"
#include "ros/ros.h"

DEFINE_string(pbstream_filename, "",
              "Filename of a pbstream to draw a map from.");
DEFINE_string(map_topic, "map", "Name of the published map topic.");
DEFINE_string(map_frame_id, "map", "Frame ID of the published map.");
DEFINE_double(resolution, 0.05, "Resolution of a grid cell in the drawn map.");

namespace cartographer_ros {
namespace {

void Run(const std::string& pbstream_filename, const std::string& map_topic,
         const std::string& map_frame_id, const double resolution) {
  ::cartographer::io::ProtoStreamReader reader(pbstream_filename);
  ::cartographer::io::ProtoStreamDeserializer deserializer(&reader);

  LOG(INFO) << "Loading submap slices from serialized data.";
  std::map<::cartographer::mapping::SubmapId, ::cartographer::io::SubmapSlice>
      submap_slices;
  ::cartographer::mapping::proto::SerializedData proto;
  while (deserializer.ReadNextSerializedData(&proto)) {
    if (proto.has_submap()) {
      const auto& submap = proto.submap();
      const ::cartographer::mapping::SubmapId id{
          submap.submap_id().trajectory_id(),
          submap.submap_id().submap_index()};
      const ::cartographer::transform::Rigid3d global_submap_pose =
          ::cartographer::transform::ToRigid3(deserializer.pose_graph()
                                                  .trajectory(id.trajectory_id)
                                                  .submap(id.submap_index)
                                                  .pose());
      FillSubmapSlice(global_submap_pose, submap, &submap_slices[id]);
    }
  }
  CHECK(reader.eof());

  ::ros::NodeHandle node_handle("");
  ::ros::Publisher pub = node_handle.advertise<nav_msgs::OccupancyGrid>(
      map_topic, kLatestOnlyPublisherQueueSize, true /*latched */);

  LOG(INFO) << "Generating combined map image from submap slices.";
  const auto painted_slices =
      ::cartographer::io::PaintSubmapSlices(submap_slices, resolution);
  std::unique_ptr<nav_msgs::OccupancyGrid> msg_ptr = CreateOccupancyGridMsg(
      painted_slices, resolution, FLAGS_map_frame_id, ros::Time::now());

  LOG(INFO) << "Publishing occupancy grid topic " << map_topic
            << " (frame_id: " << map_frame_id
            << ", resolution:" << std::to_string(resolution) << ").";
  pub.publish(*msg_ptr);
  ::ros::spin();
  ::ros::shutdown();
}

}  // namespace
}  // namespace cartographer_ros

int main(int argc, char** argv) {
  FLAGS_alsologtostderr = true;
  google::InitGoogleLogging(argv[0]);
  google::ParseCommandLineFlags(&argc, &argv, true);

  CHECK(!FLAGS_pbstream_filename.empty()) << "-pbstream_filename is missing.";

  ::ros::init(argc, argv, "cartographer_pbstream_map_publisher");
  ::ros::start();

  cartographer_ros::ScopedRosLogSink ros_log_sink;

  ::cartographer_ros::Run(FLAGS_pbstream_filename, FLAGS_map_topic,
                          FLAGS_map_frame_id, FLAGS_resolution);
}
<commit_msg>Discard proto data in pbstream_map_publisher via RAII. (#912)<commit_after>/*
 * Copyright 2018 The Cartographer Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// Publishes a frozen nav_msgs/OccupancyGrid map from serialized submaps.

#include <map>
#include <string>

#include "cartographer/io/proto_stream.h"
#include "cartographer/io/proto_stream_deserializer.h"
#include "cartographer/io/submap_painter.h"
#include "cartographer/mapping/2d/probability_grid.h"
#include "cartographer/mapping/2d/submap_2d.h"
#include "cartographer/mapping/3d/submap_3d.h"
#include "cartographer/mapping/proto/pose_graph.pb.h"
#include "cartographer/mapping/proto/serialization.pb.h"
#include "cartographer/mapping/proto/submap.pb.h"
#include "cartographer/mapping/proto/trajectory_builder_options.pb.h"
#include "cartographer_ros/msg_conversion.h"
#include "cartographer_ros/node_constants.h"
#include "cartographer_ros/ros_log_sink.h"
#include "cartographer_ros/ros_map.h"
#include "cartographer_ros/submap.h"
#include "gflags/gflags.h"
#include "glog/logging.h"
#include "nav_msgs/OccupancyGrid.h"
#include "ros/ros.h"

DEFINE_string(pbstream_filename, "",
              "Filename of a pbstream to draw a map from.");
DEFINE_string(map_topic, "map", "Name of the published map topic.");
DEFINE_string(map_frame_id, "map", "Frame ID of the published map.");
DEFINE_double(resolution, 0.05, "Resolution of a grid cell in the drawn map.");

namespace cartographer_ros {
namespace {

std::unique_ptr<nav_msgs::OccupancyGrid> LoadOccupancyGridMsg(
    const std::string& pbstream_filename, const double resolution) {
  ::cartographer::io::ProtoStreamReader reader(pbstream_filename);
  ::cartographer::io::ProtoStreamDeserializer deserializer(&reader);

  LOG(INFO) << "Loading submap slices from serialized data.";
  std::map<::cartographer::mapping::SubmapId, ::cartographer::io::SubmapSlice>
      submap_slices;
  ::cartographer::mapping::proto::SerializedData proto;
  while (deserializer.ReadNextSerializedData(&proto)) {
    if (proto.has_submap()) {
      const auto& submap = proto.submap();
      const ::cartographer::mapping::SubmapId id{
          submap.submap_id().trajectory_id(),
          submap.submap_id().submap_index()};
      const ::cartographer::transform::Rigid3d global_submap_pose =
          ::cartographer::transform::ToRigid3(deserializer.pose_graph()
                                                  .trajectory(id.trajectory_id)
                                                  .submap(id.submap_index)
                                                  .pose());
      FillSubmapSlice(global_submap_pose, submap, &submap_slices[id]);
    }
  }
  CHECK(reader.eof());

  LOG(INFO) << "Generating combined map image from submap slices.";
  const auto painted_slices =
      ::cartographer::io::PaintSubmapSlices(submap_slices, resolution);
  return CreateOccupancyGridMsg(painted_slices, resolution, FLAGS_map_frame_id,
                                ros::Time::now());
}

void Run(const std::string& pbstream_filename, const std::string& map_topic,
         const std::string& map_frame_id, const double resolution) {
  std::unique_ptr<nav_msgs::OccupancyGrid> msg_ptr =
      LoadOccupancyGridMsg(pbstream_filename, resolution);

  ::ros::NodeHandle node_handle("");
  ::ros::Publisher pub = node_handle.advertise<nav_msgs::OccupancyGrid>(
      map_topic, kLatestOnlyPublisherQueueSize, true /*latched */);

  LOG(INFO) << "Publishing occupancy grid topic " << map_topic
            << " (frame_id: " << map_frame_id
            << ", resolution:" << std::to_string(resolution) << ").";
  pub.publish(*msg_ptr);
  ::ros::spin();
  ::ros::shutdown();
}

}  // namespace
}  // namespace cartographer_ros

int main(int argc, char** argv) {
  FLAGS_alsologtostderr = true;
  google::InitGoogleLogging(argv[0]);
  google::ParseCommandLineFlags(&argc, &argv, true);

  CHECK(!FLAGS_pbstream_filename.empty()) << "-pbstream_filename is missing.";

  ::ros::init(argc, argv, "cartographer_pbstream_map_publisher");
  ::ros::start();

  cartographer_ros::ScopedRosLogSink ros_log_sink;

  ::cartographer_ros::Run(FLAGS_pbstream_filename, FLAGS_map_topic,
                          FLAGS_map_frame_id, FLAGS_resolution);
}
<|endoftext|>


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

#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/values.h"
#include "chrome/browser/extensions/extension_icon_manager.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_resource.h"
#include "chrome/common/json_value_serializer.h"
#include "content/browser/browser_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/skia_util.h"

// Our test class that takes care of managing the necessary threads for loading
// extension icons, and waiting for those loads to happen.
class ExtensionIconManagerTest : public testing::Test {
 public:
  ExtensionIconManagerTest() :
      unwaited_image_loads_(0),
      waiting_(false),
      ui_thread_(BrowserThread::UI, &ui_loop_),
      file_thread_(BrowserThread::FILE),
      io_thread_(BrowserThread::IO) {}

  virtual ~ExtensionIconManagerTest() {}

  void ImageLoadObserved() {
    unwaited_image_loads_++;
    if (waiting_) {
      MessageLoop::current()->Quit();
    }
  }

  void WaitForImageLoad() {
    if (unwaited_image_loads_ == 0) {
      waiting_ = true;
      MessageLoop::current()->Run();
      waiting_ = false;
    }
    ASSERT_GT(unwaited_image_loads_, 0);
    unwaited_image_loads_--;
  }

 private:
  virtual void SetUp() {
    file_thread_.Start();
    io_thread_.Start();
  }

  // The number of observed image loads that have not been waited for.
  int unwaited_image_loads_;

  // Whether we are currently waiting for an image load.
  bool waiting_;

  MessageLoop ui_loop_;
  BrowserThread ui_thread_;
  BrowserThread file_thread_;
  BrowserThread io_thread_;

  DISALLOW_COPY_AND_ASSIGN(ExtensionIconManagerTest);
};

// This is a specialization of ExtensionIconManager, with a special override to
// call back to the test when an icon has completed loading.
class TestIconManager : public ExtensionIconManager {
 public:
  explicit TestIconManager(ExtensionIconManagerTest* test) : test_(test) {}
  virtual ~TestIconManager() {}

  // Implements the ImageLoadingTracker::Observer interface, and calls through
  // to the base class' implementation. Then it lets the test know that an
  // image load was observed.
  virtual void OnImageLoaded(SkBitmap* image, ExtensionResource resource,
                             int index) {
    ExtensionIconManager::OnImageLoaded(image, resource, index);
    test_->ImageLoadObserved();
  }

 private:
  ExtensionIconManagerTest* test_;

  DISALLOW_COPY_AND_ASSIGN(TestIconManager);
};

// Returns the default icon that ExtensionIconManager gives when an extension
// doesn't have an icon.
SkBitmap GetDefaultIcon() {
  std::string dummy_id;
  EXPECT_TRUE(Extension::GenerateId(std::string("whatever"), &dummy_id));
  ExtensionIconManager manager;
  return manager.GetIcon(dummy_id);
}

// Tests loading an icon for an extension, removing it, then re-loading it.
TEST_F(ExtensionIconManagerTest, LoadRemoveLoad) {
  SkBitmap default_icon = GetDefaultIcon();

  FilePath test_dir;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_dir));
  FilePath manifest_path = test_dir.AppendASCII(
      "extensions/image_loading_tracker/app.json");

  JSONFileValueSerializer serializer(manifest_path);
  scoped_ptr<DictionaryValue> manifest(
      static_cast<DictionaryValue*>(serializer.Deserialize(NULL, NULL)));
  ASSERT_TRUE(manifest.get() != NULL);

  scoped_refptr<Extension> extension(Extension::Create(
      manifest_path.DirName(), Extension::INVALID, *manifest.get(),
      false, true, NULL));
  ASSERT_TRUE(extension.get());
  TestIconManager icon_manager(this);

  // Load the icon and grab the bitmap.
  icon_manager.LoadIcon(extension.get());
  WaitForImageLoad();
  SkBitmap first_icon = icon_manager.GetIcon(extension->id());
  EXPECT_FALSE(gfx::BitmapsAreEqual(first_icon, default_icon));

  // Remove the icon from the manager.
  icon_manager.RemoveIcon(extension->id());

  // Now re-load the icon - we should get the same result bitmap (and not the
  // default icon).
  icon_manager.LoadIcon(extension.get());
  WaitForImageLoad();
  SkBitmap second_icon = icon_manager.GetIcon(extension->id());
  EXPECT_FALSE(gfx::BitmapsAreEqual(second_icon, default_icon));

  EXPECT_TRUE(gfx::BitmapsAreEqual(first_icon, second_icon));
}
<commit_msg>Fix clang error after r77740<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/values.h"
#include "chrome/browser/extensions/extension_icon_manager.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_resource.h"
#include "chrome/common/json_value_serializer.h"
#include "content/browser/browser_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/skia_util.h"

// Our test class that takes care of managing the necessary threads for loading
// extension icons, and waiting for those loads to happen.
class ExtensionIconManagerTest : public testing::Test {
 public:
  ExtensionIconManagerTest() :
      unwaited_image_loads_(0),
      waiting_(false),
      ui_thread_(BrowserThread::UI, &ui_loop_),
      file_thread_(BrowserThread::FILE),
      io_thread_(BrowserThread::IO) {}

  virtual ~ExtensionIconManagerTest() {}

  void ImageLoadObserved() {
    unwaited_image_loads_++;
    if (waiting_) {
      MessageLoop::current()->Quit();
    }
  }

  void WaitForImageLoad() {
    if (unwaited_image_loads_ == 0) {
      waiting_ = true;
      MessageLoop::current()->Run();
      waiting_ = false;
    }
    ASSERT_GT(unwaited_image_loads_, 0);
    unwaited_image_loads_--;
  }

 private:
  virtual void SetUp() {
    file_thread_.Start();
    io_thread_.Start();
  }

  // The number of observed image loads that have not been waited for.
  int unwaited_image_loads_;

  // Whether we are currently waiting for an image load.
  bool waiting_;

  MessageLoop ui_loop_;
  BrowserThread ui_thread_;
  BrowserThread file_thread_;
  BrowserThread io_thread_;

  DISALLOW_COPY_AND_ASSIGN(ExtensionIconManagerTest);
};

// This is a specialization of ExtensionIconManager, with a special override to
// call back to the test when an icon has completed loading.
class TestIconManager : public ExtensionIconManager {
 public:
  explicit TestIconManager(ExtensionIconManagerTest* test) : test_(test) {}
  virtual ~TestIconManager() {}

  // Implements the ImageLoadingTracker::Observer interface, and calls through
  // to the base class' implementation. Then it lets the test know that an
  // image load was observed.
  virtual void OnImageLoaded(SkBitmap* image, const ExtensionResource& resource,
                             int index) {
    ExtensionIconManager::OnImageLoaded(image, resource, index);
    test_->ImageLoadObserved();
  }

 private:
  ExtensionIconManagerTest* test_;

  DISALLOW_COPY_AND_ASSIGN(TestIconManager);
};

// Returns the default icon that ExtensionIconManager gives when an extension
// doesn't have an icon.
SkBitmap GetDefaultIcon() {
  std::string dummy_id;
  EXPECT_TRUE(Extension::GenerateId(std::string("whatever"), &dummy_id));
  ExtensionIconManager manager;
  return manager.GetIcon(dummy_id);
}

// Tests loading an icon for an extension, removing it, then re-loading it.
TEST_F(ExtensionIconManagerTest, LoadRemoveLoad) {
  SkBitmap default_icon = GetDefaultIcon();

  FilePath test_dir;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_dir));
  FilePath manifest_path = test_dir.AppendASCII(
      "extensions/image_loading_tracker/app.json");

  JSONFileValueSerializer serializer(manifest_path);
  scoped_ptr<DictionaryValue> manifest(
      static_cast<DictionaryValue*>(serializer.Deserialize(NULL, NULL)));
  ASSERT_TRUE(manifest.get() != NULL);

  scoped_refptr<Extension> extension(Extension::Create(
      manifest_path.DirName(), Extension::INVALID, *manifest.get(),
      false, true, NULL));
  ASSERT_TRUE(extension.get());
  TestIconManager icon_manager(this);

  // Load the icon and grab the bitmap.
  icon_manager.LoadIcon(extension.get());
  WaitForImageLoad();
  SkBitmap first_icon = icon_manager.GetIcon(extension->id());
  EXPECT_FALSE(gfx::BitmapsAreEqual(first_icon, default_icon));

  // Remove the icon from the manager.
  icon_manager.RemoveIcon(extension->id());

  // Now re-load the icon - we should get the same result bitmap (and not the
  // default icon).
  icon_manager.LoadIcon(extension.get());
  WaitForImageLoad();
  SkBitmap second_icon = icon_manager.GetIcon(extension->id());
  EXPECT_FALSE(gfx::BitmapsAreEqual(second_icon, default_icon));

  EXPECT_TRUE(gfx::BitmapsAreEqual(first_icon, second_icon));
}
<|endoftext|>


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

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigation) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("webnavigation/api")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationEvents1) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("webnavigation/navigation1")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationEvents2) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("webnavigation/navigation2")) << message_;
}
<commit_msg>Disable ExtensionApiTest.WebNavigationEvents1, flakily exceeds test timeout<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigation) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("webnavigation/api")) << message_;
}

// Disabled, flakily exceeds timeout, http://crbug.com/72165.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_WebNavigationEvents1) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("webnavigation/navigation1")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationEvents2) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("webnavigation/navigation2")) << message_;
}
<|endoftext|>