<commit_before>/*
 * LGDictSCM.cc
 *
 * Copyright (C) 2015 OpenCog Foundation
 *
 * Author: William Ma <https://github.com/williampma>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <opencog/atomspace/AtomSpace.h>
#include <opencog/atoms/base/Link.h>
#include <opencog/atoms/base/Node.h>
#include <opencog/guile/SchemePrimitive.h>
#include <opencog/nlp/types/atom_types.h>

#include "LGDictSCM.h"
#include "LGDictReader.h"
#include "LGDictUtils.h"

using namespace opencog::nlp;
using namespace opencog;

/**
 * The constructor for LGDictSCM.
 */
LGDictSCM::LGDictSCM()
{
	static bool is_init = false;
	if (is_init) return;
	is_init = true;
	m_pDictionary = nullptr;
	scm_with_guile(init_in_guile, this);
}

/**
 * The destructor for LGDictSCM.
 */
LGDictSCM::~LGDictSCM()
{
	if (m_pDictionary)
		dictionary_delete(m_pDictionary);
}

/**
 * Init function for using with scm_with_guile.
 *
 * Creates the sureal scheme module and uses it by default.
 *
 * @param self   pointer to the LGDictSCM object
 * @return       null
 */
void* LGDictSCM::init_in_guile(void* self)
{
	scm_c_define_module("opencog nlp lg-dict", init_in_module, self);
	scm_c_use_module("opencog nlp lg-dict");
	return NULL;
}

/**
 * The main function for defining stuff in the sureal scheme module.
 *
 * @param data   pointer to the LGDictSCM object
 */
void LGDictSCM::init_in_module(void* data)
{
	LGDictSCM* self = (LGDictSCM*) data;
	self->init();
}

/**
 * The main init function for the SuRealSCM object.
 */
void LGDictSCM::init()
{
	define_scheme_primitive("lg-dict-open",
		 &LGDictSCM::do_lg_dictopen, this, "nlp lg-dict");

	define_scheme_primitive("lg-dict-close",
		 &LGDictSCM::do_lg_dictclose, this, "nlp lg-dict");

	define_scheme_primitive("lg-dict-entry",
		 &LGDictSCM::do_lg_dict_entry, this, "nlp lg-dict");

	// XXX this is deprecated.
	define_scheme_primitive("lg-get-dict-entry",
		 &LGDictSCM::do_lg_get_dict_entry, this, "nlp lg-dict");

	define_scheme_primitive("lg-conn-type-match?",
		 &LGDictSCM::do_lg_conn_type_match, this, "nlp lg-dict");
	define_scheme_primitive("lg-conn-linkable?",
		 &LGDictSCM::do_lg_conn_linkable, this, "nlp lg-dict");
}

/**
 * Implementation of the "lg-dict-open" scheme primitive.
 *
 * XXX FIXME the current API allows only one global dictionary
 * at a time.  Some future version should fix this, to allow
 * multiple dictionaries at a time, right?  This is a low-priority
 * though, it seems.
 */
void LGDictSCM::do_lg_dictopen(Handle h)
{
	if (not h->isNode()) return;

	if (m_pDictionary)
		dictionary_delete(m_pDictionary);

	const char * lang = h->getName().c_str();
	m_pDictionary = dictionary_create_lang(lang);
}

/**
 * Implementation of the "lg-dict-close" scheme primitive.
 *
 * XXX FIXME the current API allows only one global dictionary
 * at a time.  Some future version should fix this, to allow
 * multiple dictionaries at a time, right?  This is a low-priority
 * though, it seems.
 */
void LGDictSCM::do_lg_dictclose(void)
{
	if (m_pDictionary)
		dictionary_delete(m_pDictionary);
	m_pDictionary = nullptr;
}

/**
 * Implementation of the "lg-dict-entry" scheme primitive.
 *
 * The corresponding implementation for the "lg-dict-entry"
 * primitive, which accepts a WordNode as input and places
 * the LG dictionary entry into the atomspace.
 *
 * @param h   the input WordNode containing the word string
 */
void LGDictSCM::do_lg_dict_entry(Handle h)
{
	if (h->getType() != WORD_NODE) return;

	// Check if the dictionary entry is already in the atomspace.
	HandleSeq djset;
	h->getIncomingSetByType(std::back_inserter(djset), LG_DISJUNCT);

	// Avoid the disjuncts building if entries exist.
	if (not djset.empty()) return;

	if (nullptr == m_pDictionary)
		m_pDictionary = dictionary_create_default_lang();

	AtomSpace* pAS = SchemeSmob::ss_get_env_as("lg-dict-entry");
	LGDictReader reader(m_pDictionary, pAS);

	reader.getDictEntry(h->getName());
}

/**
 * Implementation of the "lg-get-dict-entry" scheme primitive.
 *
 * The corresponding implementation for the "lg-get-dict-entry"
 * primitive, which accepts a WordNode as input and output the LG
 * dictionary atom.
 *
 * XXX FIXME! This should NOT return a SetLink!  It should return
 * nothing at all; users can already get the needed data by calling
 * getIncomingSetByType() themselves.  SetLink just clogs the atomspace
 * with junk.
 *
 * @param h   the input WordNode containing the word string
 * @return    the LG dictionary atom
 */
Handle LGDictSCM::do_lg_get_dict_entry(Handle h)
{
	if (h->getType() != WORD_NODE)
		return Handle::UNDEFINED;

	// Check if the dictionary entry is already in the atomspace.
	HandleSeq djset;
	h->getIncomingSetByType(std::back_inserter(djset), LG_DISJUNCT);

	// Avoid the disjuncts building if entries exist.
	if (not djset.empty())
		return Handle(createLink(djset, SET_LINK));

	if (nullptr == m_pDictionary)
		m_pDictionary = dictionary_create_default_lang();

	AtomSpace* pAS = SchemeSmob::ss_get_env_as("lg-get-dict-entry");
	LGDictReader reader(m_pDictionary, pAS);

	djset = reader.getDictEntry(h->getName());
	return Handle(createLink(djset, SET_LINK));
}

/**
 * Implementation of the "lg-conn-type-match?" scheme primitive.
 *
 * @param h1    the first LGConnector
 * @param h2    the second LGConnector
 * @return      true if the type matches
 */
bool LGDictSCM::do_lg_conn_type_match(Handle h1, Handle h2)
{
	return lg_conn_type_match(h1, h2);
}

/**
 * Implementation of the "lg-conn-linkable?" scheme primitive.
 *
 * @param h1    the first LGConnector
 * @param h2    the second LGConnector
 * @return      true if linkable
 */
bool LGDictSCM::do_lg_conn_linkable(Handle h1, Handle h2)
{
	return lg_conn_linkable(h1, h2);
}

void opencog_nlp_lgdict_init(void)
{
	static LGDictSCM lgdict;
}
<commit_msg>Update the documentation<commit_after>/*
 * LGDictSCM.cc
 *
 * Copyright (C) 2015 OpenCog Foundation
 *
 * Author: William Ma <https://github.com/williampma>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include <opencog/atomspace/AtomSpace.h>
#include <opencog/atoms/base/Link.h>
#include <opencog/atoms/base/Node.h>
#include <opencog/guile/SchemePrimitive.h>
#include <opencog/nlp/types/atom_types.h>

#include "LGDictSCM.h"
#include "LGDictReader.h"
#include "LGDictUtils.h"

using namespace opencog::nlp;
using namespace opencog;

/**
 * The constructor for LGDictSCM.
 */
LGDictSCM::LGDictSCM()
{
	static bool is_init = false;
	if (is_init) return;
	is_init = true;
	m_pDictionary = nullptr;
	scm_with_guile(init_in_guile, this);
}

/**
 * The destructor for LGDictSCM.
 */
LGDictSCM::~LGDictSCM()
{
	if (m_pDictionary)
		dictionary_delete(m_pDictionary);
}

/**
 * Init function for using with scm_with_guile.
 *
 * Creates the sureal scheme module and uses it by default.
 *
 * @param self   pointer to the LGDictSCM object
 * @return       null
 */
void* LGDictSCM::init_in_guile(void* self)
{
	scm_c_define_module("opencog nlp lg-dict", init_in_module, self);
	scm_c_use_module("opencog nlp lg-dict");
	return NULL;
}

/**
 * The main function for defining stuff in the sureal scheme module.
 *
 * @param data   pointer to the LGDictSCM object
 */
void LGDictSCM::init_in_module(void* data)
{
	LGDictSCM* self = (LGDictSCM*) data;
	self->init();
}

/**
 * The main init function for the SuRealSCM object.
 */
void LGDictSCM::init()
{
	define_scheme_primitive("lg-dict-open",
		 &LGDictSCM::do_lg_dictopen, this, "nlp lg-dict");

	define_scheme_primitive("lg-dict-close",
		 &LGDictSCM::do_lg_dictclose, this, "nlp lg-dict");

	define_scheme_primitive("lg-dict-entry",
		 &LGDictSCM::do_lg_dict_entry, this, "nlp lg-dict");

	// XXX this is deprecated.
	define_scheme_primitive("lg-get-dict-entry",
		 &LGDictSCM::do_lg_get_dict_entry, this, "nlp lg-dict");

	define_scheme_primitive("lg-conn-type-match?",
		 &LGDictSCM::do_lg_conn_type_match, this, "nlp lg-dict");
	define_scheme_primitive("lg-conn-linkable?",
		 &LGDictSCM::do_lg_conn_linkable, this, "nlp lg-dict");
}

/**
 * Implementation of the "lg-dict-open" scheme primitive.
 *
 * XXX FIXME the current API allows only one global dictionary
 * at a time.  The correct fix is to invent a new Link type that
 * inherits from FunctionLink:
 *
 *    LgDictEntry
 *        WordNode "foobar"
 *        LgDictNode "en"
 *
 * When the above is executed, the word would be looked up, and the
 * disjuncts placed into the atomspace.  See the implementation of
 * LgParse for an example of how to do this.
 */
void LGDictSCM::do_lg_dictopen(Handle h)
{
	if (not h->isNode()) return;

	if (m_pDictionary)
		dictionary_delete(m_pDictionary);

	const char * lang = h->getName().c_str();
	m_pDictionary = dictionary_create_lang(lang);
}

/**
 * Implementation of the "lg-dict-close" scheme primitive.
 *
 * XXX FIXME the current API allows only one global dictionary
 * at a time.  Some future version should fix this, to allow
 * multiple dictionaries at a time, right?  This is a low-priority
 * though, it seems.
 */
void LGDictSCM::do_lg_dictclose(void)
{
	if (m_pDictionary)
		dictionary_delete(m_pDictionary);
	m_pDictionary = nullptr;
}

/**
 * Implementation of the "lg-dict-entry" scheme primitive.
 *
 * The corresponding implementation for the "lg-dict-entry"
 * primitive, which accepts a WordNode as input and places
 * the LG dictionary entry into the atomspace.
 *
 * @param h   the input WordNode containing the word string
 */
void LGDictSCM::do_lg_dict_entry(Handle h)
{
	if (h->getType() != WORD_NODE) return;

	// Check if the dictionary entry is already in the atomspace.
	HandleSeq djset;
	h->getIncomingSetByType(std::back_inserter(djset), LG_DISJUNCT);

	// Avoid the disjuncts building if entries exist.
	if (not djset.empty()) return;

	if (nullptr == m_pDictionary)
		m_pDictionary = dictionary_create_default_lang();

	AtomSpace* pAS = SchemeSmob::ss_get_env_as("lg-dict-entry");
	LGDictReader reader(m_pDictionary, pAS);

	reader.getDictEntry(h->getName());
}

/**
 * Implementation of the "lg-get-dict-entry" scheme primitive.
 *
 * The corresponding implementation for the "lg-get-dict-entry"
 * primitive, which accepts a WordNode as input and output the LG
 * dictionary atom.
 *
 * XXX FIXME! This should NOT return a SetLink!  It should return
 * nothing at all; users can already get the needed data by calling
 * getIncomingSetByType() themselves.  SetLink just clogs the atomspace
 * with junk.
 *
 * @param h   the input WordNode containing the word string
 * @return    the LG dictionary atom
 */
Handle LGDictSCM::do_lg_get_dict_entry(Handle h)
{
	if (h->getType() != WORD_NODE)
		return Handle::UNDEFINED;

	// Check if the dictionary entry is already in the atomspace.
	HandleSeq djset;
	h->getIncomingSetByType(std::back_inserter(djset), LG_DISJUNCT);

	// Avoid the disjuncts building if entries exist.
	if (not djset.empty())
		return Handle(createLink(djset, SET_LINK));

	if (nullptr == m_pDictionary)
		m_pDictionary = dictionary_create_default_lang();

	AtomSpace* pAS = SchemeSmob::ss_get_env_as("lg-get-dict-entry");
	LGDictReader reader(m_pDictionary, pAS);

	djset = reader.getDictEntry(h->getName());
	return Handle(createLink(djset, SET_LINK));
}

/**
 * Implementation of the "lg-conn-type-match?" scheme primitive.
 *
 * @param h1    the first LGConnector
 * @param h2    the second LGConnector
 * @return      true if the type matches
 */
bool LGDictSCM::do_lg_conn_type_match(Handle h1, Handle h2)
{
	return lg_conn_type_match(h1, h2);
}

/**
 * Implementation of the "lg-conn-linkable?" scheme primitive.
 *
 * @param h1    the first LGConnector
 * @param h2    the second LGConnector
 * @return      true if linkable
 */
bool LGDictSCM::do_lg_conn_linkable(Handle h1, Handle h2)
{
	return lg_conn_linkable(h1, h2);
}

void opencog_nlp_lgdict_init(void)
{
	static LGDictSCM lgdict;
}
<|endoftext|>


<commit_before>#include "ee/iron_source/private/IronSourceBridge.hpp"

#include <ee/ads/internal/DefaultBannerAd.hpp>
#include <ee/ads/internal/GuardedBannerAd.hpp>
#include <ee/ads/internal/GuardedFullScreenAd.hpp>
#include <ee/ads/internal/IAsyncHelper.hpp>
#include <ee/ads/internal/MediationManager.hpp>
#include <ee/core/ILogger.hpp>
#include <ee/core/IMessageBridge.hpp>
#include <ee/core/Task.hpp>
#include <ee/core/Utils.hpp>
#include <ee/nlohmann/json.hpp>

#include "ee/iron_source/private/IronSourceInterstitialAd.hpp"
#include "ee/iron_source/private/IronSourceRewardedAd.hpp"

namespace ee {
namespace iron_source {
namespace {
// clang-format off
const std::string kPrefix                = "IronSourceBridge";

const auto kInitialize                   = kPrefix + "Initialize";

const auto kGetBannerAdSize              = kPrefix + "GetBannerAdSize";
const auto kCreateBannerAd               = kPrefix + "CreateBannerAd";
const auto kDestroyBannerAd              = kPrefix + "DestroyBannerAd";

const auto kHasInterstitialAd            = kPrefix + "HasInterstitialAd";
const auto kLoadInterstitialAd           = kPrefix + "LoadInterstitialAd";
const auto kShowInterstitialAd           = kPrefix + "ShowInterstitialAd";

const auto kHasRewardedAd                = kPrefix + "HasRewardedAd";
const auto kShowRewardedAd               = kPrefix + "ShowRewardedAd";

const auto kOnInterstitialAdLoaded       = kPrefix + "OnInterstitialAdLoaded";
const auto kOnInterstitialAdFailedToLoad = kPrefix + "OnInterstitialAdFailedToLoad";
const auto kOnInterstitialAdFailedToShow = kPrefix + "OnInterstitialAdFailedToShow";
const auto kOnInterstitialAdClicked      = kPrefix + "OnInterstitialAdClicked";
const auto kOnInterstitialAdClosed       = kPrefix + "OnInterstitialAdClosed";

const auto kOnRewardedAdLoaded       = kPrefix + "OnRewardedAdLoaded";
const auto kOnRewardedAdFailedToShow = kPrefix + "OnRewardedAdFailedToShow";
const auto kOnRewardedAdClicked      = kPrefix + "OnRewardedAdClicked";
const auto kOnRewardedAdClosed       = kPrefix + "OnRewardedAdClosed";
// clang-format on
} // namespace

using Self = Bridge;

Self::Bridge(IMessageBridge& bridge, ILogger& logger,
             const Destroyer& destroyer)
    : bridge_(bridge)
    , logger_(logger)
    , destroyer_(destroyer) {
    logger_.debug("%s", __PRETTY_FUNCTION__);
    auto&& mediation = ads::MediationManager::getInstance();
    displayer_ = mediation.getAdDisplayer();
    interstitialAd_ = nullptr;
    rewardedAd_ = nullptr;

    bridge_.registerHandler(
        [this](const std::string& message) { //
            onInterstitialAdLoaded();
        },
        kOnInterstitialAdLoaded);
    bridge_.registerHandler(
        [this](const std::string& message) { //
            onInterstitialAdFailedToLoad(message);
        },
        kOnInterstitialAdFailedToLoad);
    bridge_.registerHandler(
        [this](const std::string& message) { //
            onInterstitialAdFailedToShow(message);
        },
        kOnInterstitialAdFailedToShow);
    bridge_.registerHandler(
        [this](const std::string& message) { //
            onInterstitialAdClicked();
        },
        kOnInterstitialAdClicked);
    bridge_.registerHandler(
        [this](const std::string& message) { //
            onInterstitialAdClosed();
        },
        kOnInterstitialAdClosed);

    bridge_.registerHandler(
        [this](const std::string& message) { //
            onRewardedAdLoaded();
        },
        kOnRewardedAdLoaded);
    bridge_.registerHandler(
        [this](const std::string& message) { //
            onRewardedAdFailedToShow(message);
        },
        kOnRewardedAdFailedToShow);
    bridge_.registerHandler(
        [this](const std::string& message) { //
            onRewardedAdClicked();
        },
        kOnRewardedAdClicked);
    bridge_.registerHandler(
        [this](const std::string& message) { //
            onRewardedAdClosed(core::toBool(message));
        },
        kOnRewardedAdClosed);
}

Self::~Bridge() = default;

void Self::destroy() {
    logger_.debug("%s", __PRETTY_FUNCTION__);

    bridge_.deregisterHandler(kOnInterstitialAdLoaded);
    bridge_.deregisterHandler(kOnInterstitialAdFailedToLoad);
    bridge_.deregisterHandler(kOnRewardedAdFailedToShow);
    bridge_.deregisterHandler(kOnInterstitialAdClicked);
    bridge_.deregisterHandler(kOnInterstitialAdClosed);

    bridge_.deregisterHandler(kOnRewardedAdLoaded);
    bridge_.deregisterHandler(kOnRewardedAdFailedToShow);
    bridge_.deregisterHandler(kOnRewardedAdClicked);
    bridge_.deregisterHandler(kOnRewardedAdClosed);

    destroyer_();
}

Task<bool> Self::initialize(const std::string& appKey) {
    logger_.debug("%s: appKey = %s", __PRETTY_FUNCTION__, appKey.c_str());
    auto response = co_await bridge_.callAsync(kInitialize, appKey);
    co_return core::toBool(response);
}

std::pair<int, int> Self::getBannerAdSize(BannerAdSize adSize) {
    auto response = bridge_.call(kGetBannerAdSize,
                                 std::to_string(static_cast<int>(adSize)));
    auto json = nlohmann::json::parse(response);
    int width = json["width"];
    int height = json["height"];
    return std::pair(width, height);
}

std::shared_ptr<IBannerAd> Self::createBannerAd(const std::string& adId,
                                                BannerAdSize adSize) {
    logger_.debug("%s: id = %s size = %d", __PRETTY_FUNCTION__, adId.c_str(),
                  static_cast<int>(adSize));
    if (bannerAd_) {
        return bannerAd_;
    }
    nlohmann::json json;
    json["adId"] = adId;
    json["adSize"] = static_cast<int>(adSize);
    auto response = bridge_.call(kCreateBannerAd, json.dump());
    if (not core::toBool(response)) {
        logger_.error("%s: There was an error when attempt to create an ad.",
                      __PRETTY_FUNCTION__);
        assert(false);
        return nullptr;
    }
    auto size = getBannerAdSize(adSize);
    bannerAd_ = std::make_shared<ads::GuardedBannerAd>(
        std::make_shared<ads::DefaultBannerAd>(
            "AdMobBannerAd", bridge_, logger_,
            [this, adId] { //
                destroyBannerAd(adId);
            },
            adId, size));
    return bannerAd_;
}

bool Self::destroyBannerAd(const std::string& adId) {
    logger_.debug("%s: adId = %s", __PRETTY_FUNCTION__, adId.c_str());
    if (bannerAd_ == nullptr) {
        return false;
    }
    auto&& response = bridge_.call(kDestroyBannerAd, adId);
    if (not core::toBool(response)) {
        logger_.error("%s: There was an error when attempt to destroy an ad.",
                      __PRETTY_FUNCTION__);
        assert(false);
        return false;
    }
    bannerAd_.reset();
    return true;
}

std::shared_ptr<IFullScreenAd>
Self::createInterstitialAd(const std::string& adId) {
    // adId has no usage at the moment since all ads share the same instance.
    logger_.debug("%s: adId = %s", __PRETTY_FUNCTION__, adId.c_str());
    if (sharedInterstitialAd_) {
        return sharedInterstitialAd_;
    }
    interstitialAd_ =
        std::make_shared<InterstitialAd>(logger_, displayer_, this, adId);
    sharedInterstitialAd_ =
        std::make_shared<ads::GuardedFullScreenAd>(interstitialAd_);
    return sharedInterstitialAd_;
}

bool Self::destroyInterstitialAd(const std::string& adId) {
    logger_.debug("%s: adId = %s", __PRETTY_FUNCTION__, adId.c_str());
    if (sharedInterstitialAd_ == nullptr) {
        return false;
    }
    interstitialAd_.reset();
    sharedInterstitialAd_.reset();
    return true;
}

std::shared_ptr<IFullScreenAd> Self::createRewardedAd(const std::string& adId) {
    // adId has no usage at the moment since all ads share the same instance.
    logger_.debug("%s: adId = %s", __PRETTY_FUNCTION__, adId.c_str());
    if (sharedRewardedAd_) {
        return sharedRewardedAd_;
    }
    rewardedAd_ = std::make_shared<RewardedAd>(logger_, displayer_, this, adId);
    sharedRewardedAd_ = std::make_shared<ads::GuardedFullScreenAd>(rewardedAd_);
    return sharedRewardedAd_;
}

bool Self::destroyRewardedAd(const std::string& adId) {
    logger_.debug("%s: adId = %s", __PRETTY_FUNCTION__, adId.c_str());
    if (sharedRewardedAd_ == nullptr) {
        return false;
    }
    rewardedAd_.reset();
    sharedRewardedAd_.reset();
    return true;
}

bool Self::hasInterstitialAd() const {
    auto response = bridge_.call(kHasInterstitialAd);
    return core::toBool(response);
}

void Self::loadInterstitialAd() {
    bridge_.call(kLoadInterstitialAd);
}

void Self::showInterstitialAd(const std::string& adId) {
    bridge_.call(kShowInterstitialAd, adId);
}

bool Self::hasRewardedAd() const {
    auto response = bridge_.call(kHasRewardedAd);
    return core::toBool(response);
}

void Self::showRewardedAd(const std::string& adId) {
    bridge_.call(kShowRewardedAd, adId);
}

#pragma mark - Interstitial Ad Callbacks.

void Self::onInterstitialAdLoaded() {
    logger_.debug("%s", __PRETTY_FUNCTION__);
    if (interstitialAd_) {
        interstitialAd_->onLoaded();
    } else {
        assert(false);
    }
}

void Self::onInterstitialAdFailedToLoad(const std::string& message) {
    logger_.debug("%s", __PRETTY_FUNCTION__);
    if (interstitialAd_) {
        interstitialAd_->onFailedToLoad(message);
    } else {
        assert(false);
    }
}

void Self::onInterstitialAdFailedToShow(const std::string& message) {
    if (interstitialAd_) {
        interstitialAd_->onFailedToShow(message);
    } else {
        assert(false);
    }
}

void Self::onInterstitialAdClicked() {
    if (interstitialAd_) {
        interstitialAd_->onClicked();
    } else {
        assert(false);
    }
}

void Self::onInterstitialAdClosed() {
    logger_.debug("%s", __PRETTY_FUNCTION__);
    if (interstitialAd_) {
        interstitialAd_->onClosed();
    } else {
        onMediationAdClosed(FullScreenAdResult::Completed);
    }
}

#pragma mark - Rewarded Ad Callbacks.

void Self::onRewardedAdLoaded() {
    if (rewardedAd_) {
        rewardedAd_->onLoaded();
    } else {
        // Automatically reloaded by SDK.
    }
}

void Self::onRewardedAdFailedToShow(const std::string& message) {
    if (rewardedAd_) {
        rewardedAd_->onFailedToShow(message);
    } else {
        assert(false);
    }
}

void Self::onRewardedAdClicked() {
    if (rewardedAd_) {
        rewardedAd_->onClicked();
    } else {
        assert(false);
    }
}

void Self::onRewardedAdClosed(bool rewarded) {
    logger_.debug("%s", __PRETTY_FUNCTION__);
    if (rewardedAd_) {
        rewardedAd_->onClosed(rewarded);
    } else {
        onMediationAdClosed(rewarded ? FullScreenAdResult::Completed
                                     : FullScreenAdResult::Canceled);
    }
}

#pragma mark - Mediation Ad Callbacks.

void Self::onMediationAdClosed(FullScreenAdResult result) {
    logger_.debug("%s", __PRETTY_FUNCTION__);
    if (displayer_->isProcessing()) {
        displayer_->resolve(result);
        return;
    }
    assert(false);
}
} // namespace iron_source
} // namespace ee
<commit_msg>Fix incorrect handler tag.<commit_after>#include "ee/iron_source/private/IronSourceBridge.hpp"

#include <ee/ads/internal/DefaultBannerAd.hpp>
#include <ee/ads/internal/GuardedBannerAd.hpp>
#include <ee/ads/internal/GuardedFullScreenAd.hpp>
#include <ee/ads/internal/IAsyncHelper.hpp>
#include <ee/ads/internal/MediationManager.hpp>
#include <ee/core/ILogger.hpp>
#include <ee/core/IMessageBridge.hpp>
#include <ee/core/Task.hpp>
#include <ee/core/Utils.hpp>
#include <ee/nlohmann/json.hpp>

#include "ee/iron_source/private/IronSourceInterstitialAd.hpp"
#include "ee/iron_source/private/IronSourceRewardedAd.hpp"

namespace ee {
namespace iron_source {
namespace {
// clang-format off
const std::string kPrefix                = "IronSourceBridge";

const auto kInitialize                   = kPrefix + "Initialize";

const auto kGetBannerAdSize              = kPrefix + "GetBannerAdSize";
const auto kCreateBannerAd               = kPrefix + "CreateBannerAd";
const auto kDestroyBannerAd              = kPrefix + "DestroyBannerAd";

const auto kHasInterstitialAd            = kPrefix + "HasInterstitialAd";
const auto kLoadInterstitialAd           = kPrefix + "LoadInterstitialAd";
const auto kShowInterstitialAd           = kPrefix + "ShowInterstitialAd";

const auto kHasRewardedAd                = kPrefix + "HasRewardedAd";
const auto kShowRewardedAd               = kPrefix + "ShowRewardedAd";

const auto kOnInterstitialAdLoaded       = kPrefix + "OnInterstitialAdLoaded";
const auto kOnInterstitialAdFailedToLoad = kPrefix + "OnInterstitialAdFailedToLoad";
const auto kOnInterstitialAdFailedToShow = kPrefix + "OnInterstitialAdFailedToShow";
const auto kOnInterstitialAdClicked      = kPrefix + "OnInterstitialAdClicked";
const auto kOnInterstitialAdClosed       = kPrefix + "OnInterstitialAdClosed";

const auto kOnRewardedAdLoaded       = kPrefix + "OnRewardedAdLoaded";
const auto kOnRewardedAdFailedToShow = kPrefix + "OnRewardedAdFailedToShow";
const auto kOnRewardedAdClicked      = kPrefix + "OnRewardedAdClicked";
const auto kOnRewardedAdClosed       = kPrefix + "OnRewardedAdClosed";
// clang-format on
} // namespace

using Self = Bridge;

Self::Bridge(IMessageBridge& bridge, ILogger& logger,
             const Destroyer& destroyer)
    : bridge_(bridge)
    , logger_(logger)
    , destroyer_(destroyer) {
    logger_.debug("%s", __PRETTY_FUNCTION__);
    auto&& mediation = ads::MediationManager::getInstance();
    displayer_ = mediation.getAdDisplayer();
    interstitialAd_ = nullptr;
    rewardedAd_ = nullptr;

    bridge_.registerHandler(
        [this](const std::string& message) { //
            onInterstitialAdLoaded();
        },
        kOnInterstitialAdLoaded);
    bridge_.registerHandler(
        [this](const std::string& message) { //
            onInterstitialAdFailedToLoad(message);
        },
        kOnInterstitialAdFailedToLoad);
    bridge_.registerHandler(
        [this](const std::string& message) { //
            onInterstitialAdFailedToShow(message);
        },
        kOnInterstitialAdFailedToShow);
    bridge_.registerHandler(
        [this](const std::string& message) { //
            onInterstitialAdClicked();
        },
        kOnInterstitialAdClicked);
    bridge_.registerHandler(
        [this](const std::string& message) { //
            onInterstitialAdClosed();
        },
        kOnInterstitialAdClosed);

    bridge_.registerHandler(
        [this](const std::string& message) { //
            onRewardedAdLoaded();
        },
        kOnRewardedAdLoaded);
    bridge_.registerHandler(
        [this](const std::string& message) { //
            onRewardedAdFailedToShow(message);
        },
        kOnRewardedAdFailedToShow);
    bridge_.registerHandler(
        [this](const std::string& message) { //
            onRewardedAdClicked();
        },
        kOnRewardedAdClicked);
    bridge_.registerHandler(
        [this](const std::string& message) { //
            onRewardedAdClosed(core::toBool(message));
        },
        kOnRewardedAdClosed);
}

Self::~Bridge() = default;

void Self::destroy() {
    logger_.debug("%s", __PRETTY_FUNCTION__);

    bridge_.deregisterHandler(kOnInterstitialAdLoaded);
    bridge_.deregisterHandler(kOnInterstitialAdFailedToLoad);
    bridge_.deregisterHandler(kOnRewardedAdFailedToShow);
    bridge_.deregisterHandler(kOnInterstitialAdClicked);
    bridge_.deregisterHandler(kOnInterstitialAdClosed);

    bridge_.deregisterHandler(kOnRewardedAdLoaded);
    bridge_.deregisterHandler(kOnRewardedAdFailedToShow);
    bridge_.deregisterHandler(kOnRewardedAdClicked);
    bridge_.deregisterHandler(kOnRewardedAdClosed);

    destroyer_();
}

Task<bool> Self::initialize(const std::string& appKey) {
    logger_.debug("%s: appKey = %s", __PRETTY_FUNCTION__, appKey.c_str());
    auto response = co_await bridge_.callAsync(kInitialize, appKey);
    co_return core::toBool(response);
}

std::pair<int, int> Self::getBannerAdSize(BannerAdSize adSize) {
    auto response = bridge_.call(kGetBannerAdSize,
                                 std::to_string(static_cast<int>(adSize)));
    auto json = nlohmann::json::parse(response);
    int width = json["width"];
    int height = json["height"];
    return std::pair(width, height);
}

std::shared_ptr<IBannerAd> Self::createBannerAd(const std::string& adId,
                                                BannerAdSize adSize) {
    logger_.debug("%s: id = %s size = %d", __PRETTY_FUNCTION__, adId.c_str(),
                  static_cast<int>(adSize));
    if (bannerAd_) {
        return bannerAd_;
    }
    nlohmann::json json;
    json["adId"] = adId;
    json["adSize"] = static_cast<int>(adSize);
    auto response = bridge_.call(kCreateBannerAd, json.dump());
    if (not core::toBool(response)) {
        logger_.error("%s: There was an error when attempt to create an ad.",
                      __PRETTY_FUNCTION__);
        assert(false);
        return nullptr;
    }
    auto size = getBannerAdSize(adSize);
    bannerAd_ = std::make_shared<ads::GuardedBannerAd>(
        std::make_shared<ads::DefaultBannerAd>(
            "IronSourceBannerAd", bridge_, logger_,
            [this, adId] { //
                destroyBannerAd(adId);
            },
            adId, size));
    return bannerAd_;
}

bool Self::destroyBannerAd(const std::string& adId) {
    logger_.debug("%s: adId = %s", __PRETTY_FUNCTION__, adId.c_str());
    if (bannerAd_ == nullptr) {
        return false;
    }
    auto&& response = bridge_.call(kDestroyBannerAd, adId);
    if (not core::toBool(response)) {
        logger_.error("%s: There was an error when attempt to destroy an ad.",
                      __PRETTY_FUNCTION__);
        assert(false);
        return false;
    }
    bannerAd_.reset();
    return true;
}

std::shared_ptr<IFullScreenAd>
Self::createInterstitialAd(const std::string& adId) {
    // adId has no usage at the moment since all ads share the same instance.
    logger_.debug("%s: adId = %s", __PRETTY_FUNCTION__, adId.c_str());
    if (sharedInterstitialAd_) {
        return sharedInterstitialAd_;
    }
    interstitialAd_ =
        std::make_shared<InterstitialAd>(logger_, displayer_, this, adId);
    sharedInterstitialAd_ =
        std::make_shared<ads::GuardedFullScreenAd>(interstitialAd_);
    return sharedInterstitialAd_;
}

bool Self::destroyInterstitialAd(const std::string& adId) {
    logger_.debug("%s: adId = %s", __PRETTY_FUNCTION__, adId.c_str());
    if (sharedInterstitialAd_ == nullptr) {
        return false;
    }
    interstitialAd_.reset();
    sharedInterstitialAd_.reset();
    return true;
}

std::shared_ptr<IFullScreenAd> Self::createRewardedAd(const std::string& adId) {
    // adId has no usage at the moment since all ads share the same instance.
    logger_.debug("%s: adId = %s", __PRETTY_FUNCTION__, adId.c_str());
    if (sharedRewardedAd_) {
        return sharedRewardedAd_;
    }
    rewardedAd_ = std::make_shared<RewardedAd>(logger_, displayer_, this, adId);
    sharedRewardedAd_ = std::make_shared<ads::GuardedFullScreenAd>(rewardedAd_);
    return sharedRewardedAd_;
}

bool Self::destroyRewardedAd(const std::string& adId) {
    logger_.debug("%s: adId = %s", __PRETTY_FUNCTION__, adId.c_str());
    if (sharedRewardedAd_ == nullptr) {
        return false;
    }
    rewardedAd_.reset();
    sharedRewardedAd_.reset();
    return true;
}

bool Self::hasInterstitialAd() const {
    auto response = bridge_.call(kHasInterstitialAd);
    return core::toBool(response);
}

void Self::loadInterstitialAd() {
    bridge_.call(kLoadInterstitialAd);
}

void Self::showInterstitialAd(const std::string& adId) {
    bridge_.call(kShowInterstitialAd, adId);
}

bool Self::hasRewardedAd() const {
    auto response = bridge_.call(kHasRewardedAd);
    return core::toBool(response);
}

void Self::showRewardedAd(const std::string& adId) {
    bridge_.call(kShowRewardedAd, adId);
}

#pragma mark - Interstitial Ad Callbacks.

void Self::onInterstitialAdLoaded() {
    logger_.debug("%s", __PRETTY_FUNCTION__);
    if (interstitialAd_) {
        interstitialAd_->onLoaded();
    } else {
        assert(false);
    }
}

void Self::onInterstitialAdFailedToLoad(const std::string& message) {
    logger_.debug("%s", __PRETTY_FUNCTION__);
    if (interstitialAd_) {
        interstitialAd_->onFailedToLoad(message);
    } else {
        assert(false);
    }
}

void Self::onInterstitialAdFailedToShow(const std::string& message) {
    if (interstitialAd_) {
        interstitialAd_->onFailedToShow(message);
    } else {
        assert(false);
    }
}

void Self::onInterstitialAdClicked() {
    if (interstitialAd_) {
        interstitialAd_->onClicked();
    } else {
        assert(false);
    }
}

void Self::onInterstitialAdClosed() {
    logger_.debug("%s", __PRETTY_FUNCTION__);
    if (interstitialAd_) {
        interstitialAd_->onClosed();
    } else {
        onMediationAdClosed(FullScreenAdResult::Completed);
    }
}

#pragma mark - Rewarded Ad Callbacks.

void Self::onRewardedAdLoaded() {
    if (rewardedAd_) {
        rewardedAd_->onLoaded();
    } else {
        // Automatically reloaded by SDK.
    }
}

void Self::onRewardedAdFailedToShow(const std::string& message) {
    if (rewardedAd_) {
        rewardedAd_->onFailedToShow(message);
    } else {
        assert(false);
    }
}

void Self::onRewardedAdClicked() {
    if (rewardedAd_) {
        rewardedAd_->onClicked();
    } else {
        assert(false);
    }
}

void Self::onRewardedAdClosed(bool rewarded) {
    logger_.debug("%s", __PRETTY_FUNCTION__);
    if (rewardedAd_) {
        rewardedAd_->onClosed(rewarded);
    } else {
        onMediationAdClosed(rewarded ? FullScreenAdResult::Completed
                                     : FullScreenAdResult::Canceled);
    }
}

#pragma mark - Mediation Ad Callbacks.

void Self::onMediationAdClosed(FullScreenAdResult result) {
    logger_.debug("%s", __PRETTY_FUNCTION__);
    if (displayer_->isProcessing()) {
        displayer_->resolve(result);
        return;
    }
    assert(false);
}
} // namespace iron_source
} // namespace ee
<|endoftext|>


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

#include "perfetto/profiling/deobfuscator.h"
#include "perfetto/ext/base/string_splitter.h"

#include "perfetto/ext/base/optional.h"

namespace perfetto {
namespace profiling {
namespace {

base::Optional<std::pair<std::string, std::string>> ParseClass(
    std::string line) {
  base::StringSplitter ss(std::move(line), ' ');

  if (!ss.Next()) {
    PERFETTO_ELOG("Missing deobfuscated name.");
    return base::nullopt;
  }
  std::string deobfuscated_name(ss.cur_token(), ss.cur_token_size());

  if (!ss.Next() || ss.cur_token_size() != 2 ||
      strncmp("->", ss.cur_token(), 2) != 0) {
    PERFETTO_ELOG("Missing ->");
    return base::nullopt;
  }

  if (!ss.Next()) {
    PERFETTO_ELOG("Missing obfuscated name.");
    return base::nullopt;
  }
  std::string obfuscated_name(ss.cur_token(), ss.cur_token_size());
  if (obfuscated_name.size() == 0) {
    PERFETTO_ELOG("Empty obfuscated name.");
    return base::nullopt;
  }
  if (obfuscated_name.back() != ':') {
    PERFETTO_ELOG("Expected colon.");
    return base::nullopt;
  }

  obfuscated_name.resize(obfuscated_name.size() - 1);
  if (ss.Next()) {
    PERFETTO_ELOG("Unexpected data.");
    return base::nullopt;
  }
  return std::make_pair(std::move(obfuscated_name),
                        std::move(deobfuscated_name));
}

base::Optional<std::pair<std::string, std::string>> ParseMember(
    std::string line) {
  base::StringSplitter ss(std::move(line), ' ');

  if (!ss.Next()) {
    PERFETTO_ELOG("Missing type name.");
    return base::nullopt;
  }
  std::string type_name(ss.cur_token(), ss.cur_token_size());

  if (!ss.Next()) {
    PERFETTO_ELOG("Missing deobfuscated name.");
    return base::nullopt;
  }
  std::string deobfuscated_name(ss.cur_token(), ss.cur_token_size());

  if (!ss.Next() || ss.cur_token_size() != 2 ||
      strncmp("->", ss.cur_token(), 2) != 0) {
    PERFETTO_ELOG("Missing ->");
    return base::nullopt;
  }

  if (!ss.Next()) {
    PERFETTO_ELOG("Missing obfuscated name.");
    return base::nullopt;
  }
  std::string obfuscated_name(ss.cur_token(), ss.cur_token_size());

  if (ss.Next()) {
    PERFETTO_ELOG("Unexpected data.");
    return base::nullopt;
  }
  return std::make_pair(std::move(obfuscated_name),
                        std::move(deobfuscated_name));
}

}  // namespace

bool ProguardParser::AddLine(std::string line) {
  if (line.length() == 0)
    return true;
  bool is_member = line[0] == ' ';
  if (is_member && !current_class_) {
    PERFETTO_ELOG("Failed to parse proguard map. Saw member before class.");
    return false;
  }
  if (!is_member) {
    std::string obfuscated_name;
    std::string deobfuscated_name;
    auto opt_pair = ParseClass(std::move(line));
    if (!opt_pair)
      return false;
    std::tie(obfuscated_name, deobfuscated_name) = *opt_pair;
    auto p = mapping_.emplace(std::move(obfuscated_name),
                              std::move(deobfuscated_name));
    if (!p.second) {
      PERFETTO_ELOG("Duplicate class.");
      return false;
    }
    current_class_ = &p.first->second;
  } else {
    std::string obfuscated_name;
    std::string deobfuscated_name;
    auto opt_pair = ParseMember(std::move(line));
    if (!opt_pair)
      return false;
    std::tie(obfuscated_name, deobfuscated_name) = *opt_pair;
    // TODO(fmayer): Teach this to properly parse methods.
    if (deobfuscated_name.find("(") != std::string::npos) {
      // Skip functions, as they will trigger the "Duplicate member" below.
      return true;
    }
    auto p = current_class_->deobfuscated_fields.emplace(obfuscated_name,
                                                         deobfuscated_name);
    if (!p.second && p.first->second != deobfuscated_name) {
      PERFETTO_ELOG("Member redefinition: %s.%s",
                    current_class_->deobfuscated_name.c_str(),
                    deobfuscated_name.c_str());
      return false;
    }
  }
  return true;
}

}  // namespace profiling
}  // namespace perfetto
<commit_msg>Slightly refactor deobfuscator. Add structs for pairs.<commit_after>/*
 * Copyright (C) 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "perfetto/profiling/deobfuscator.h"
#include "perfetto/ext/base/string_splitter.h"

#include "perfetto/ext/base/optional.h"

namespace perfetto {
namespace profiling {
namespace {

struct ProguardClass {
  std::string obfuscated_name;
  std::string deobfuscated_name;
};

base::Optional<ProguardClass> ParseClass(std::string line) {
  base::StringSplitter ss(std::move(line), ' ');

  if (!ss.Next()) {
    PERFETTO_ELOG("Missing deobfuscated name.");
    return base::nullopt;
  }
  std::string deobfuscated_name(ss.cur_token(), ss.cur_token_size());

  if (!ss.Next() || ss.cur_token_size() != 2 ||
      strncmp("->", ss.cur_token(), 2) != 0) {
    PERFETTO_ELOG("Missing ->");
    return base::nullopt;
  }

  if (!ss.Next()) {
    PERFETTO_ELOG("Missing obfuscated name.");
    return base::nullopt;
  }
  std::string obfuscated_name(ss.cur_token(), ss.cur_token_size());
  if (obfuscated_name.size() == 0) {
    PERFETTO_ELOG("Empty obfuscated name.");
    return base::nullopt;
  }
  if (obfuscated_name.back() != ':') {
    PERFETTO_ELOG("Expected colon.");
    return base::nullopt;
  }

  obfuscated_name.resize(obfuscated_name.size() - 1);
  if (ss.Next()) {
    PERFETTO_ELOG("Unexpected data.");
    return base::nullopt;
  }
  return ProguardClass{std::move(obfuscated_name),
                       std::move(deobfuscated_name)};
}

enum class ProguardMemberType {
  kField,
  kMethod,
};

struct ProguardMember {
  ProguardMemberType type;
  std::string obfuscated_name;
  std::string deobfuscated_name;
};

base::Optional<ProguardMember> ParseMember(std::string line) {
  base::StringSplitter ss(std::move(line), ' ');

  if (!ss.Next()) {
    PERFETTO_ELOG("Missing type name.");
    return base::nullopt;
  }
  std::string type_name(ss.cur_token(), ss.cur_token_size());

  if (!ss.Next()) {
    PERFETTO_ELOG("Missing deobfuscated name.");
    return base::nullopt;
  }
  std::string deobfuscated_name(ss.cur_token(), ss.cur_token_size());

  if (!ss.Next() || ss.cur_token_size() != 2 ||
      strncmp("->", ss.cur_token(), 2) != 0) {
    PERFETTO_ELOG("Missing ->");
    return base::nullopt;
  }

  if (!ss.Next()) {
    PERFETTO_ELOG("Missing obfuscated name.");
    return base::nullopt;
  }
  std::string obfuscated_name(ss.cur_token(), ss.cur_token_size());

  if (ss.Next()) {
    PERFETTO_ELOG("Unexpected data.");
    return base::nullopt;
  }

  ProguardMemberType member_type;
  auto paren_idx = deobfuscated_name.find("(");
  if (paren_idx != std::string::npos) {
    member_type = ProguardMemberType::kMethod;
  } else {
    member_type = ProguardMemberType::kField;
  }
  return ProguardMember{member_type, std::move(obfuscated_name),
                        std::move(deobfuscated_name)};
}

}  // namespace

// See https://www.guardsquare.com/en/products/proguard/manual/retrace for the
// file format we are parsing.
bool ProguardParser::AddLine(std::string line) {
  if (line.length() == 0)
    return true;
  bool is_member = line[0] == ' ';
  if (is_member && !current_class_) {
    PERFETTO_ELOG("Failed to parse proguard map. Saw member before class.");
    return false;
  }
  if (!is_member) {
    auto opt_cls = ParseClass(std::move(line));
    if (!opt_cls)
      return false;
    auto p = mapping_.emplace(std::move(opt_cls->obfuscated_name),
                              std::move(opt_cls->deobfuscated_name));
    if (!p.second) {
      PERFETTO_ELOG("Duplicate class.");
      return false;
    }
    current_class_ = &p.first->second;
  } else {
    auto opt_member = ParseMember(std::move(line));
    if (!opt_member)
      return false;
    // TODO(fmayer): Teach this to properly parse methods.
    if (opt_member->type == ProguardMemberType::kMethod) {
      // Skip functions, as they will trigger the "Duplicate member" below.
      return true;
    }
    auto p = current_class_->deobfuscated_fields.emplace(
        opt_member->obfuscated_name, opt_member->deobfuscated_name);
    if (!p.second && p.first->second != opt_member->deobfuscated_name) {
      PERFETTO_ELOG("Member redefinition: %s.%s",
                    current_class_->deobfuscated_name.c_str(),
                    opt_member->deobfuscated_name.c_str());
      return false;
    }
  }
  return true;
}

}  // namespace profiling
}  // namespace perfetto
<|endoftext|>


<commit_before>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "EC_Sound.h"
#include "IModule.h"
#include "Framework.h"
#include "Entity.h"
#include "EC_OgrePlaceable.h"
#include "SceneManager.h"
#include "SoundServiceInterface.h"

#include "LoggingFunctions.h"
DEFINE_POCO_LOGGING_FUNCTIONS("EC_Sound")

#include "MemoryLeakCheck.h"

EC_Sound::EC_Sound(IModule *module):
    IComponent(module->GetFramework()),
    sound_id_(0),
    soundId(this, "Sound ref"),
    soundInnerRadius(this, "Sound radius inner", 0.0f),
    soundOuterRadius(this, "Sound radius outer", 20.0f),
    loopSound(this, "Loop sound", false),
    triggerSound(this, "Trigger sound", false),
    soundGain(this, "Sound gain", 1.0f)
{
    static AttributeMetadata metaData("", "0", "1", "0.1");
    soundGain.SetMetadata(&metaData);

    QObject::connect(this, SIGNAL(ParentEntitySet()), this, SLOT(UpdateSignals()));
}

EC_Sound::~EC_Sound()
{
    StopSound();
}

void EC_Sound::AttributeUpdated(IComponent *component, IAttribute *attribute)
{
    if(component != this)
        return;

    if(attribute->GetNameString() == soundId.GetNameString())
    {
        Foundation::SoundServiceInterface *soundService = framework_->GetService<Foundation::SoundServiceInterface>();
        if(soundService && soundService->GetSoundName(sound_id_) != soundId.Get().toStdString())
            StopSound();
    }
    else if(attribute->GetNameString() == triggerSound.GetNameString())
    {
        // Play sound if sound asset id has been setted and if sound has been triggered or looped.
        if(triggerSound.Get() == true && (!soundId.Get().isNull() || loopSound.Get()))
            PlaySound();
    }
    UpdateSoundSettings();
}

void EC_Sound::RegisterActions()
{
    Scene::Entity *entity = GetParentEntity();
    assert(entity);
    if (entity)
    {
        entity->ConnectAction("PlaySound", this, SLOT(PlaySound()));
        entity->ConnectAction("StopSound", this, SLOT(StopSound()));
    }
}

void EC_Sound::PlaySound()
{
    triggerSound.Set(false, AttributeChange::LocalOnly);
    ComponentChanged(AttributeChange::LocalOnly);

    Foundation::SoundServiceInterface *soundService = framework_->GetService<Foundation::SoundServiceInterface>();
    if(!soundService)
        return;

    if(sound_id_)
        StopSound();

    OgreRenderer::EC_OgrePlaceable *placeable = dynamic_cast<OgreRenderer::EC_OgrePlaceable *>(FindPlaceable().get());
    if(placeable)
    {
        sound_id_ = soundService->PlaySound3D(soundId.Get().toStdString(), Foundation::SoundServiceInterface::Triggered, false, placeable->GetPosition());
        soundService->SetGain(sound_id_, soundGain.Get());
        soundService->SetLooped(sound_id_, loopSound.Get());
        soundService->SetRange(sound_id_, soundInnerRadius.Get(), soundOuterRadius.Get(), 2.0f);
    }
    else // If entity isn't holding placeable component treat sound as ambient sound.
    {
        sound_id_ = soundService->PlaySound(soundId.Get().toStdString(), Foundation::SoundServiceInterface::Ambient);
        soundService->SetGain(sound_id_, soundGain.Get());
    }
}

void EC_Sound::StopSound()
{
    Foundation::SoundServiceInterface *soundService = framework_->GetService<Foundation::SoundServiceInterface>();
    if(!soundService)
        return;

    soundService->StopSound(sound_id_);
    sound_id_ = 0;
}

void EC_Sound::UpdateSoundSettings()
{
    Foundation::SoundServiceInterface *soundService = framework_->GetService<Foundation::SoundServiceInterface>();
    if(!soundService || !sound_id_)
        return;

    soundService->SetGain(sound_id_, soundGain.Get());
    soundService->SetLooped(sound_id_, loopSound.Get());
    soundService->SetRange(sound_id_, soundInnerRadius.Get(), soundOuterRadius.Get(), 2.0f);
}

void EC_Sound::UpdateSignals()
{
    disconnect(this, SLOT(AttributeUpdated(IComponent *, IAttribute *)));
    if(GetParentEntity())
    {
        Scene::SceneManager *scene = GetParentEntity()->GetScene();
        if(scene)
        connect(scene, SIGNAL(AttributeChanged(IComponent*, IAttribute*, AttributeChange::Type)),
                this, SLOT(AttributeUpdated(IComponent*, IAttribute*)));
        RegisterActions();
    }
}

ComponentPtr EC_Sound::FindPlaceable() const
{
    assert(framework_);
    ComponentPtr comp;
    if(!GetParentEntity())
        return comp;
    comp = GetParentEntity()->GetComponent<OgreRenderer::EC_OgrePlaceable>();
    return comp;
}<commit_msg>Annotated silent-fail issues with EC_Sound.cpp<commit_after>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "EC_Sound.h"
#include "IModule.h"
#include "Framework.h"
#include "Entity.h"
#include "EC_OgrePlaceable.h"
#include "SceneManager.h"
#include "SoundServiceInterface.h"

#include "LoggingFunctions.h"
DEFINE_POCO_LOGGING_FUNCTIONS("EC_Sound")

#include "MemoryLeakCheck.h"

EC_Sound::EC_Sound(IModule *module):
    IComponent(module->GetFramework()),
    sound_id_(0),
    soundId(this, "Sound ref"),
    soundInnerRadius(this, "Sound radius inner", 0.0f),
    soundOuterRadius(this, "Sound radius outer", 20.0f),
    loopSound(this, "Loop sound", false),
    triggerSound(this, "Trigger sound", false),
    soundGain(this, "Sound gain", 1.0f)
{
    static AttributeMetadata metaData("", "0", "1", "0.1");
    soundGain.SetMetadata(&metaData);

    QObject::connect(this, SIGNAL(ParentEntitySet()), this, SLOT(UpdateSignals()));
}

EC_Sound::~EC_Sound()
{
    StopSound();
}

void EC_Sound::AttributeUpdated(IComponent *component, IAttribute *attribute)
{
    if(component != this)
        return;

    if(attribute->GetNameString() == soundId.GetNameString())
    {
        Foundation::SoundServiceInterface *soundService = framework_->GetService<Foundation::SoundServiceInterface>();
        if(soundService && soundService->GetSoundName(sound_id_) != soundId.Get().toStdString())
            StopSound();
    }
    else if(attribute->GetNameString() == triggerSound.GetNameString())
    {
        // Play sound if sound asset id has been setted and if sound has been triggered or looped.
        if(triggerSound.Get() == true && (!soundId.Get().isNull() || loopSound.Get()))
            PlaySound();
    }
    UpdateSoundSettings();
}

void EC_Sound::RegisterActions()
{
    Scene::Entity *entity = GetParentEntity();
    assert(entity);
    if (entity)
    {
        entity->ConnectAction("PlaySound", this, SLOT(PlaySound()));
        entity->ConnectAction("StopSound", this, SLOT(StopSound()));
    }
}

void EC_Sound::PlaySound()
{
    triggerSound.Set(false, AttributeChange::LocalOnly);
    ComponentChanged(AttributeChange::LocalOnly);

    Foundation::SoundServiceInterface *soundService = framework_->GetService<Foundation::SoundServiceInterface>();
    if(!soundService)
    {
        // log warning
        return;
    }

    if(sound_id_)
        StopSound();

    OgreRenderer::EC_OgrePlaceable *placeable = dynamic_cast<OgreRenderer::EC_OgrePlaceable *>(FindPlaceable().get());
    if(placeable)
    {
        sound_id_ = soundService->PlaySound3D(soundId.Get().toStdString(), Foundation::SoundServiceInterface::Triggered, false, placeable->GetPosition());
        soundService->SetGain(sound_id_, soundGain.Get());
        soundService->SetLooped(sound_id_, loopSound.Get());
        soundService->SetRange(sound_id_, soundInnerRadius.Get(), soundOuterRadius.Get(), 2.0f);
    }
    else // If entity isn't holding placeable component treat sound as ambient sound.
    {
        sound_id_ = soundService->PlaySound(soundId.Get().toStdString(), Foundation::SoundServiceInterface::Ambient);
        soundService->SetGain(sound_id_, soundGain.Get());
    }
}

void EC_Sound::StopSound()
{
    Foundation::SoundServiceInterface *soundService = framework_->GetService<Foundation::SoundServiceInterface>();
    if (soundService)
        soundService->StopSound(sound_id_);

    sound_id_ = 0;
}

void EC_Sound::UpdateSoundSettings()
{
    Foundation::SoundServiceInterface *soundService = framework_->GetService<Foundation::SoundServiceInterface>();
    if(!soundService || !sound_id_)
    {
        // log warning
        return;
    }

    soundService->SetGain(sound_id_, soundGain.Get());
    soundService->SetLooped(sound_id_, loopSound.Get());
    soundService->SetRange(sound_id_, soundInnerRadius.Get(), soundOuterRadius.Get(), 2.0f);
}

void EC_Sound::UpdateSignals()
{
    disconnect(this, SLOT(AttributeUpdated(IComponent *, IAttribute *)));
    if (!GetParentEntity())
    {
        // log warning
        return;
    }
    Scene::SceneManager *scene = GetParentEntity()->GetScene();
    if(!scene)
    {
        // log warning
        return;
    }

    connect(scene, SIGNAL(AttributeChanged(IComponent*, IAttribute*, AttributeChange::Type)),
            this, SLOT(AttributeUpdated(IComponent*, IAttribute*)));
    RegisterActions();
}

ComponentPtr EC_Sound::FindPlaceable() const
{
    assert(framework_);
    ComponentPtr comp;
    if(!GetParentEntity())
        return comp;
    comp = GetParentEntity()->GetComponent<OgreRenderer::EC_OgrePlaceable>();
    return comp;
}<|endoftext|>


<commit_before>
// CPPUnit includes
#include "cppunit/XmlOutputter.h"
#include "cppunit/CompilerOutputter.h"
#include "cppunit/ui/text/TestRunner.h"
#include "cppunit/extensions/TestFactoryRegistry.h"

// Moose includes
#include "Moose.h"
#include "MooseInit.h"

#include "Factory.h"
#include "AppFactory.h"
#include "MoltresApp.h"

#include <fstream>
#include <string>

PerfLog Moose::perf_log("CppUnit");

int
main(int argc, char ** argv)
{
  MooseInit init(argc, argv);

  registerApp(MoltresApp);

  CppUnit::Test * suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest();

  CppUnit::TextTestRunner runner;
  runner.addTest(suite);
  std::ofstream out;

  // If you run with --xml, output will be sent to an xml file instead of the screen
  if (argc == 2 && std::string(argv[1]) == std::string("--xml"))
  {
    runner.setOutputter(new CppUnit::XmlOutputter(&runner.result(), out));
    out.open("test_results.xml");
  }

  else
  {
    // Note: upon calling setOutputter, any previous outputter is
    // destroyed. The TextTestRunner assumes ownership of the outputter, so you
    // don't have to worry about deleting it.
    runner.setOutputter(new CppUnit::CompilerOutputter(&runner.result(), Moose::err));
  }

  bool wasSucessful = runner.run(/*testPath=*/"",
                                 /*doWait=*/false,
                                 /*doPrintResult=*/true,
                                 /*doPrintProgress=*/false);

  return wasSucessful ? 0 : 1;
}
<commit_msg>Replace cppunit with gtest<commit_after>
#include "gtest/gtest.h"

// Moose includes
#include "Moose.h"
#include "MooseInit.h"

#include "Factory.h"
#include "AppFactory.h"
#include "MoltresApp.h"

#include <fstream>
#include <string>

PerfLog Moose::perf_log("gtest");

GTEST_API_ int
main(int argc, char ** argv)
{
  // gtest removes (only) its args from argc and argv - so this must be before moose init
  testing::InitGoogleTest(&argc, argv);

  MooseInit init(argc, argv);
  registerApp(MoltresApp);
  Moose::_throw_on_error = true;

  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before><commit_msg>Initialize time of day<commit_after><|endoftext|>


<commit_before>#include "pch.h"
#include "zip_stream.h"
#include "zip_packages.h"
#include <zlib.h>

std::mutex ZipStream::_zipReadMutex;

ZipStream::ZipStream()
{
}

ZipStream::~ZipStream()
{
}

gameplay::Stream * ZipStream::create(const char * packageName, const char * fileName)
{
    if (packageName == NULL || *packageName == '\0')
        return gameplay::FileSystem::open(fileName, gameplay::FileSystem::READ);

    zip * package = ZipPackagesCache::findOrOpenPackage(packageName);
    if (!package)
        return NULL;

    //Search for the file of given name
    struct zip_stat st;
    zip_stat_init(&st);
    if (zip_stat(package, fileName, ZIP_FL_NOCASE, &st) != 0)
        return NULL;

    // make sure we access any zip file only from one thread
    // hint: it would be more convinient to use one mutex per
    // zip * structure, not one mutex for all zips
    std::unique_lock<std::mutex> guard(_zipReadMutex);

    //Read the compressed file
    zip_file *f = zip_fopen(package, fileName, ZIP_FL_NOCASE);
    if (!f)
        return NULL;

    //Alloc memory for its uncompressed contents
    ZipStream * res = new ZipStream();
	std::unique_ptr<uint8_t[]> fileContent(new uint8_t[st.size]);

    if (zip_fread(f, fileContent.get(), st.size) != (int)st.size)
        GP_WARN("Can't read file %s:%s", packageName, fileName);
    zip_fclose(f);

    res->_underlyingStream.reset(MemoryStream::create(fileContent, static_cast<size_t>(st.size)));

    return res;
}

gameplay::Stream * ZipStream::create(gameplay::Stream * compressedStream)
{
	// TODO: it not very efficient at the moment since stream is fully read and decompressed in memory
	// it would be more efficient to decompress by chunks on demand

	if (!compressedStream)
		return NULL;

	size_t compressedLength = compressedStream->length() - compressedStream->position();
	std::unique_ptr<uint8_t[]> compressedData(new uint8_t[compressedLength]);

	if (compressedStream->read(compressedData.get(), 1, compressedLength) != compressedLength)
		return NULL;

	z_stream strm =
	{
		reinterpret_cast<unsigned char*>(compressedData.get()),
		static_cast<uInt>(compressedLength)
	};

	int ret = inflateInit(&strm);

	if (ret != Z_OK)
	{
		GP_WARN("Can't decompress the stream.");
		return NULL;
	}

	const int chunk = 10 * 1024 * 1024;
	std::unique_ptr<uint8_t[]> out(new uint8_t[chunk]);

	ZipStream * res = new ZipStream();
	res->_underlyingStream.reset(MemoryStream::create());

	do
	{
		strm.avail_out = chunk;
		strm.next_out = out.get();
		ret = inflate(&strm, Z_NO_FLUSH);

		assert(ret != Z_STREAM_ERROR);
		switch (ret)
		{
		case Z_NEED_DICT:
			ret = Z_DATA_ERROR;
		case Z_DATA_ERROR:
		case Z_MEM_ERROR:
			(void)inflateEnd(&strm);
		}

		int have = chunk - strm.avail_out;

		if (res->_underlyingStream->write(out.get(), 1, have) != have)
			GP_WARN("Can't write decompressed data.");

	}
	while (strm.avail_out == 0);

	(void)inflateEnd(&strm);

	if (ret != Z_STREAM_END)
		GP_WARN("Error while decompressing the stream.");

	res->_underlyingStream->seek(0, SEEK_SET);
	return res;
}

void ZipStream::close()
{
    _underlyingStream.reset();
}

size_t ZipStream::read(void* ptr, size_t size, size_t count)
{
    if (!_underlyingStream)
        return 0;

    return _underlyingStream->read(ptr, size, count);
}

char* ZipStream::readLine(char* str, int num)
{
    if (!_underlyingStream)
        return nullptr;

    return _underlyingStream->readLine(str, num);
}

size_t ZipStream::write(const void* ptr, size_t size, size_t count)
{
    if (!_underlyingStream)
        return 0;

    return _underlyingStream->write(ptr, size, count);
}

bool ZipStream::seek(long int offset, int origin)
{
    if (!_underlyingStream)
        return false;

    return _underlyingStream->seek(offset, origin);
}

bool ZipStream::rewind()
{
    if (!_underlyingStream)
        return false;

    return _underlyingStream->rewind();
}<commit_msg>using small blocks for zip stream<commit_after>#include "pch.h"
#include "zip_stream.h"
#include "zip_packages.h"
#include <zlib.h>

std::mutex ZipStream::_zipReadMutex;

ZipStream::ZipStream()
{
}

ZipStream::~ZipStream()
{
}

gameplay::Stream * ZipStream::create(const char * packageName, const char * fileName)
{
    if (packageName == NULL || *packageName == '\0')
        return gameplay::FileSystem::open(fileName, gameplay::FileSystem::READ);

    zip * package = ZipPackagesCache::findOrOpenPackage(packageName);
    if (!package)
        return NULL;

    //Search for the file of given name
    struct zip_stat st;
    zip_stat_init(&st);
    if (zip_stat(package, fileName, ZIP_FL_NOCASE, &st) != 0)
        return NULL;

    // make sure we access any zip file only from one thread
    // hint: it would be more convinient to use one mutex per
    // zip * structure, not one mutex for all zips
    std::unique_lock<std::mutex> guard(_zipReadMutex);

    //Read the compressed file
    zip_file *f = zip_fopen(package, fileName, ZIP_FL_NOCASE);
    if (!f)
        return NULL;

    //Alloc memory for its uncompressed contents
    ZipStream * res = new ZipStream();
	std::unique_ptr<uint8_t[]> fileContent(new uint8_t[st.size]);

    if (zip_fread(f, fileContent.get(), st.size) != (int)st.size)
        GP_WARN("Can't read file %s:%s", packageName, fileName);
    zip_fclose(f);

    res->_underlyingStream.reset(MemoryStream::create(fileContent, static_cast<size_t>(st.size)));

    return res;
}

gameplay::Stream * ZipStream::create(gameplay::Stream * compressedStream)
{
	// TODO: it not very efficient at the moment since stream is fully read and decompressed in memory
	// it would be more efficient to decompress by chunks on demand

	if (!compressedStream)
		return NULL;

	size_t compressedLength = compressedStream->length() - compressedStream->position();
	std::unique_ptr<uint8_t[]> compressedData(new uint8_t[compressedLength]);

	if (compressedStream->read(compressedData.get(), 1, compressedLength) != compressedLength)
		return NULL;

	z_stream strm =
	{
		reinterpret_cast<unsigned char*>(compressedData.get()),
		static_cast<uInt>(compressedLength)
	};

	int ret = inflateInit(&strm);

	if (ret != Z_OK)
	{
		GP_WARN("Can't decompress the stream.");
		return NULL;
	}

	const int chunk = 1 * 1024 * 1024;
	std::unique_ptr<uint8_t[]> out(new uint8_t[chunk]);

	ZipStream * res = new ZipStream();
	res->_underlyingStream.reset(MemoryStream::create());

	do
	{
		strm.avail_out = chunk;
		strm.next_out = out.get();
		ret = inflate(&strm, Z_NO_FLUSH);

		assert(ret != Z_STREAM_ERROR);
		switch (ret)
		{
		case Z_NEED_DICT:
			ret = Z_DATA_ERROR;
		case Z_DATA_ERROR:
		case Z_MEM_ERROR:
			(void)inflateEnd(&strm);
		}

		int have = chunk - strm.avail_out;

		if (res->_underlyingStream->write(out.get(), 1, have) != have)
			GP_WARN("Can't write decompressed data.");

	}
	while (strm.avail_out == 0);

	(void)inflateEnd(&strm);

	if (ret != Z_STREAM_END && ret != Z_OK)
		GP_WARN("Error while decompressing the stream.");

	res->_underlyingStream->seek(0, SEEK_SET);
	return res;
}

void ZipStream::close()
{
    _underlyingStream.reset();
}

size_t ZipStream::read(void* ptr, size_t size, size_t count)
{
    if (!_underlyingStream)
        return 0;

    return _underlyingStream->read(ptr, size, count);
}

char* ZipStream::readLine(char* str, int num)
{
    if (!_underlyingStream)
        return nullptr;

    return _underlyingStream->readLine(str, num);
}

size_t ZipStream::write(const void* ptr, size_t size, size_t count)
{
    if (!_underlyingStream)
        return 0;

    return _underlyingStream->write(ptr, size, count);
}

bool ZipStream::seek(long int offset, int origin)
{
    if (!_underlyingStream)
        return false;

    return _underlyingStream->seek(offset, origin);
}

bool ZipStream::rewind()
{
    if (!_underlyingStream)
        return false;

    return _underlyingStream->rewind();
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: unotype.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 03:35:32 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_codemaker.hxx"

#include "codemaker/unotype.hxx"

#include "osl/diagnose.h"
#include "rtl/string.hxx"
#include "sal/types.h"

#include <vector>

codemaker::UnoType::Sort codemaker::UnoType::getSort(rtl::OString const & type)
{
    return type == "void" ? SORT_VOID
        : type == "boolean" ? SORT_BOOLEAN
        : type == "byte" ? SORT_BYTE
        : type == "short" ? SORT_SHORT
        : type == "unsigned short" ? SORT_UNSIGNED_SHORT
        : type == "long" ? SORT_LONG
        : type == "unsigned long" ? SORT_UNSIGNED_LONG
        : type == "hyper" ? SORT_HYPER
        : type == "unsigned hyper" ? SORT_UNSIGNED_HYPER
        : type == "float" ? SORT_FLOAT
        : type == "double" ? SORT_DOUBLE
        : type == "char" ? SORT_CHAR
        : type == "string" ? SORT_STRING
        : type == "type" ? SORT_TYPE
        : type == "any" ? SORT_ANY
        : SORT_COMPLEX;
}

bool codemaker::UnoType::isSequenceType(rtl::OString const & type) {
    return type.getLength() > 0 && type[0] == '[';
}

rtl::OString codemaker::UnoType::decompose(
    rtl::OString const & type, sal_Int32 * rank,
    std::vector< rtl::OString > * arguments)
{
    sal_Int32 len = type.getLength();
    sal_Int32 i = 0;
    while (len - i > 1 && type[i + 1] == ']') {
        i += 2;
    }
    if (rank != 0) {
        *rank = i / 2;
    }
    sal_Int32 j = arguments == 0 ? -1 : type.indexOf('<', i);
    if (j < 0) {
        return type.copy(i);
    }
    sal_Int32 k = j;
    do {
        ++k; // skip '<' or ','
        sal_Int32 l = k;
        for (sal_Int32 level = 0; l != len; ++l) {
            char c = type[l];
            if (c == ',') {
                if (level == 0) {
                    break;
                }
            } else if (c == '<') {
                ++level;
            } else if (c == '>') {
                if (level == 0) {
                    break;
                }
                --level;
            }
        }
        arguments->push_back(type.copy(k, l - k));
        k = l;
    } while (k != len && type[k] != '>');
    OSL_ASSERT(k == len - 1 && type[k] == '>');
    return type.copy(i, j - i);
}
<commit_msg>INTEGRATION: CWS changefileheader (1.4.38); FILE MERGED 2008/03/31 07:22:52 rt 1.4.38.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: unotype.cxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_codemaker.hxx"

#include "codemaker/unotype.hxx"

#include "osl/diagnose.h"
#include "rtl/string.hxx"
#include "sal/types.h"

#include <vector>

codemaker::UnoType::Sort codemaker::UnoType::getSort(rtl::OString const & type)
{
    return type == "void" ? SORT_VOID
        : type == "boolean" ? SORT_BOOLEAN
        : type == "byte" ? SORT_BYTE
        : type == "short" ? SORT_SHORT
        : type == "unsigned short" ? SORT_UNSIGNED_SHORT
        : type == "long" ? SORT_LONG
        : type == "unsigned long" ? SORT_UNSIGNED_LONG
        : type == "hyper" ? SORT_HYPER
        : type == "unsigned hyper" ? SORT_UNSIGNED_HYPER
        : type == "float" ? SORT_FLOAT
        : type == "double" ? SORT_DOUBLE
        : type == "char" ? SORT_CHAR
        : type == "string" ? SORT_STRING
        : type == "type" ? SORT_TYPE
        : type == "any" ? SORT_ANY
        : SORT_COMPLEX;
}

bool codemaker::UnoType::isSequenceType(rtl::OString const & type) {
    return type.getLength() > 0 && type[0] == '[';
}

rtl::OString codemaker::UnoType::decompose(
    rtl::OString const & type, sal_Int32 * rank,
    std::vector< rtl::OString > * arguments)
{
    sal_Int32 len = type.getLength();
    sal_Int32 i = 0;
    while (len - i > 1 && type[i + 1] == ']') {
        i += 2;
    }
    if (rank != 0) {
        *rank = i / 2;
    }
    sal_Int32 j = arguments == 0 ? -1 : type.indexOf('<', i);
    if (j < 0) {
        return type.copy(i);
    }
    sal_Int32 k = j;
    do {
        ++k; // skip '<' or ','
        sal_Int32 l = k;
        for (sal_Int32 level = 0; l != len; ++l) {
            char c = type[l];
            if (c == ',') {
                if (level == 0) {
                    break;
                }
            } else if (c == '<') {
                ++level;
            } else if (c == '>') {
                if (level == 0) {
                    break;
                }
                --level;
            }
        }
        arguments->push_back(type.copy(k, l - k));
        k = l;
    } while (k != len && type[k] != '>');
    OSL_ASSERT(k == len - 1 && type[k] == '>');
    return type.copy(i, j - i);
}
<|endoftext|>


<commit_before>/*
 * LMS1xx.cpp
 *
 *  Created on: 09-08-2010
 *  Author: Konrad Banachowicz
 ***************************************************************************
 *   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                                *
 *                                                                         *
 ***************************************************************************/

#include <csignal>
#include <cstdio>
#include <colibri_laser/LMS1xx.h>
#include "ros/ros.h"
#include "sensor_msgs/LaserScan.h"

#define DEG2RAD M_PI/180.0
#define MIN(x,y) (x<=y)?(x):(y)

int main(int argc, char **argv)
{
  // laser data
  LMS1xx laser;
  scanCfg cfg;
  scanOutputRange outputRange;
  scanDataCfg dataCfg;
  sensor_msgs::LaserScan scan_msg;

  sensor_msgs::LaserScan gmapscan_msg;

  // switch frame flag
  int cartoFlag = 1;

  // parameters
  std::string host;
  std::string frame_id;

  std::string gmapframe_id;

  ros::init(argc, argv, "lms1xx");
  ros::NodeHandle nh;
  ros::NodeHandle n("~");
  ros::Publisher scan_pub = nh.advertise<sensor_msgs::LaserScan>("cartoscan", 1);

  ros::Publisher gmapscan_pub = nh.advertise<sensor_msgs::LaserScan>("scan", 1);

  n.param<std::string>("host", host, "192.168.10.100");
  n.param<std::string>("frame_id", frame_id, "laser_frame");  //cartographer use "laser_frame",

  n.param<std::string>("gmapframe_id", gmapframe_id, "gmaplaser_frame");  //gmap use "gmaplaser_frame",

  ROS_INFO_STREAM(" Testing output... " );

  while (ros::ok())
  {
    ROS_INFO_STREAM("Connecting to laser at " << host);
    laser.connect(host);
    if (!laser.isConnected())
    {
      ROS_WARN("Unable to connect, retrying.");
      ros::Duration(1).sleep();
      continue;
    }

    ROS_INFO_STREAM("Logging in to laser.");
    laser.login();
    cfg = laser.getScanCfg();

   ROS_INFO_STREAM("cfg.scaningFrequency =" << cfg.scaningFrequency );
   ROS_INFO_STREAM("cfg.angleResolution=" << cfg.angleResolution);
   ROS_INFO_STREAM("cfg.startAngle  =" << cfg.startAngle);
   ROS_INFO_STREAM("cfg.stopAngle  =" << cfg.stopAngle);

    ROS_INFO_STREAM("Connecting to laser at " << host);
    outputRange = laser.getScanOutputRange();

   ROS_INFO_STREAM("outputRange.angleResoluton=" << outputRange.angleResolution);
   ROS_INFO_STREAM("outputRange.startAngle  =" << outputRange.startAngle);
   ROS_INFO_STREAM("outputRange.stopAngle	=" << outputRange.stopAngle);

    if (cfg.scaningFrequency != 2500)
    {
      laser.disconnect();
      ROS_WARN("Unable to get laser output range. Retrying.");
      ros::Duration(1).sleep();
      continue;
    }

    ROS_INFO("Connected to laser.");

    ROS_DEBUG("Laser configuration: scaningFrequency %d, angleResolution %d, startAngle %d, stopAngle %d",
              cfg.scaningFrequency, cfg.angleResolution, cfg.startAngle, cfg.stopAngle);
    ROS_DEBUG("Laser output range:angleResolution %d, startAngle %d, stopAngle %d",
              outputRange.angleResolution, outputRange.startAngle, outputRange.stopAngle);

    scan_msg.header.frame_id = frame_id;
    scan_msg.range_min = 0.01;
    scan_msg.range_max = 20.0;
    scan_msg.scan_time = 100.0 / cfg.scaningFrequency;
    scan_msg.angle_increment = (double)cfg.angleResolution / 10000.0 * DEG2RAD;
    scan_msg.angle_min = (double)outputRange.startAngle / 10000.0 * DEG2RAD - M_PI / 2;
    scan_msg.angle_max = (double)outputRange.stopAngle / 10000.0 * DEG2RAD - M_PI / 2;

    gmapscan_msg.header.frame_id = gmapframe_id;
    gmapscan_msg.range_min = 0.01;
    gmapscan_msg.range_max = 20.0;
    gmapscan_msg.scan_time = 100.0 / cfg.scaningFrequency;
    gmapscan_msg.angle_increment = (double)cfg.angleResolution / 10000.0 * DEG2RAD;
    gmapscan_msg.angle_min = (double)outputRange.startAngle / 10000.0 * DEG2RAD - M_PI / 2;
    gmapscan_msg.angle_max = (double)outputRange.stopAngle / 10000.0 * DEG2RAD - M_PI / 2;

    ROS_INFO_STREAM("Device resolution is " << (double)outputRange.angleResolution / 10000.0 << " degrees.");
    ROS_INFO_STREAM("Device frequency is " << (double)cfg.scaningFrequency / 100.0 << " Hz");

    int angle_range = outputRange.stopAngle - outputRange.startAngle;
    int num_values = angle_range / cfg.angleResolution ;

    if (angle_range % cfg.angleResolution == 0)
    {
      // Include endpoint
      ++num_values;
    }

    ROS_INFO_STREAM("Device num_values is " << num_values);
    scan_msg.ranges.resize(num_values);
    scan_msg.intensities.resize(num_values);

	gmapscan_msg.ranges.resize(num_values);
    gmapscan_msg.intensities.resize(num_values);

    scan_msg.time_increment =
      (cfg.angleResolution / 10000.0)
      / 360.0
      / (cfg.scaningFrequency / 100.0);

    ROS_INFO_STREAM("Time increment is " << static_cast<int>(scan_msg.time_increment * 1000000) << " microseconds");

    dataCfg.outputChannel = 1;
    dataCfg.remission = true;
    dataCfg.resolution = 1;
    dataCfg.encoder = 0;
    dataCfg.position = false;
    dataCfg.deviceName = false;
    dataCfg.outputInterval = 1;

    //ROS_DEBUG("Setting scan data configuration.");
    //laser.setScanDataCfg(dataCfg);

    ROS_INFO_STREAM("Starting measurements.");
    laser.startMeas();

    ROS_INFO_STREAM("Waiting for ready status.");
    ros::Time ready_status_timeout = ros::Time::now() + ros::Duration(5);

    //while(1)
    //{
    status_t stat = laser.queryStatus();
    ros::Duration(1.0).sleep();
    if (stat != ready_for_measurement)
    {
      ROS_WARN("Laser not ready. Retrying initialization.");
      laser.disconnect();
      ros::Duration(1).sleep();
      continue;
    }
    /*if (stat == ready_for_measurement)
    {
      ROS_DEBUG("Ready status achieved.");
      break;
    }

      if (ros::Time::now() > ready_status_timeout)
      {
        ROS_WARN("Timed out waiting for ready status. Trying again.");
        laser.disconnect();
        continue;
      }

      if (!ros::ok())
      {
        laser.disconnect();
        return 1;
      }
    }*/

    ROS_DEBUG("Starting device.");
    laser.startDevice(); // Log out to properly re-enable system after config

    ROS_INFO_STREAM("Commanding continuous measurements.");
    laser.scanContinous(1);

	int zero_cnt = 0;
	float tmp_zero_bnd = 20.0;
	int rec_flag = 0;

    while (ros::ok())
    {

      ros::Time start = ros::Time::now();

      scan_msg.header.stamp = start;
      ++scan_msg.header.seq;

      gmapscan_msg.header.stamp = start;
      ++gmapscan_msg.header.seq;

      scanData data;
      ROS_DEBUG("Reading scan data.");
      if (laser.getScanData(&data))
      {
        for (int i = 0; i < data.dist_len1; i++)
        {
			if(data.dist1[i] * 0.001 > 0.05)  //if scan < 0.05 we believe that is wrong or interference
			{
				if(0 == zero_cnt)
				{
					scan_msg.ranges[data.dist_len1-1-i] = data.dist1[i] * 0.001;  //built for lms1xxinv_node for cartographer
					gmapscan_msg.ranges[data.dist_len1-1-i] = data.dist1[i] * 0.001;
				}
				else
				{
					float tmp_scan = data.dist1[i] * 0.001;
					float min_bnd_scan = MIN(tmp_scan,tmp_zero_bnd);
					for(int j = 0; j <= zero_cnt; j++)
					{
						scan_msg.ranges[data.dist_len1-1-i+j] = min_bnd_scan;	//care for the over bound
						gmapscan_msg.ranges[data.dist_len1-1-i+j] = min_bnd_scan;
					}
					zero_cnt = 0;
					rec_flag = 0;
				}

			}
			else
			{
				zero_cnt++;
				if(0 == rec_flag)
				{
					tmp_zero_bnd = data.dist1[i-1] * 0.001;
					rec_flag = 1;
				}
				scan_msg.ranges[data.dist_len1-1-i] = data.dist1[i] * 0.001;
				gmapscan_msg.ranges[data.dist_len1-1-i] = data.dist1[i] * 0.001;
			}

		  //scan_msg.ranges[data.dist_len1-1-i] = data.dist1[i] * 0.001;  //built for lms1xxinv_node for cartographer
		  //gmapscan_msg.ranges[data.dist_len1-1-i] = data.dist1[i] * 0.001;  //built for lms1xxinv_node for cartographer
        }

        for (int i = 0; i < data.rssi_len1; i++)
        {
          scan_msg.intensities[i] = data.rssi1[i];
		  gmapscan_msg.intensities[i] = data.rssi1[i];
        }

        ROS_DEBUG("Publishing scan data.");
        scan_pub.publish(scan_msg);
		gmapscan_pub.publish(gmapscan_msg);
      }
      else
      {
        ROS_ERROR("Laser timed out on delivering scan, attempting to reinitialize.");
        break;
      }

      ros::spinOnce();
    }

    laser.scanContinous(0);
    laser.stopMeas();
    laser.disconnect();
  }

  return 0;
}
<commit_msg>comment the laser cfg info in pkg colibri_laser<commit_after>/*
 * LMS1xx.cpp
 *
 *  Created on: 09-08-2010
 *  Author: Konrad Banachowicz
 ***************************************************************************
 *   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                                *
 *                                                                         *
 ***************************************************************************/

#include <csignal>
#include <cstdio>
#include <colibri_laser/LMS1xx.h>
#include "ros/ros.h"
#include "sensor_msgs/LaserScan.h"

#define DEG2RAD M_PI/180.0
#define MIN(x,y) (x<=y)?(x):(y)

int main(int argc, char **argv)
{
  // laser data
  LMS1xx laser;
  scanCfg cfg;
  scanOutputRange outputRange;
  scanDataCfg dataCfg;
  sensor_msgs::LaserScan scan_msg;

  sensor_msgs::LaserScan gmapscan_msg;

  // switch frame flag
  int cartoFlag = 1;

  // parameters
  std::string host;
  std::string frame_id;

  std::string gmapframe_id;

  ros::init(argc, argv, "lms1xx");
  ros::NodeHandle nh;
  ros::NodeHandle n("~");
  ros::Publisher scan_pub = nh.advertise<sensor_msgs::LaserScan>("cartoscan", 1);

  ros::Publisher gmapscan_pub = nh.advertise<sensor_msgs::LaserScan>("scan", 1);

  n.param<std::string>("host", host, "192.168.10.100");
  n.param<std::string>("frame_id", frame_id, "laser_frame");  //cartographer use "laser_frame",

  n.param<std::string>("gmapframe_id", gmapframe_id, "gmaplaser_frame");  //gmap use "gmaplaser_frame",

  ROS_INFO_STREAM(" Testing output... " );

  while (ros::ok())
  {
    ROS_INFO_STREAM("Connecting to laser at " << host);
    laser.connect(host);
    if (!laser.isConnected())
    {
      ROS_WARN("Unable to connect, retrying.");
      ros::Duration(1).sleep();
      continue;
    }

    ROS_INFO_STREAM("Logging in to laser.");
    laser.login();
    cfg = laser.getScanCfg();

//   ROS_INFO_STREAM("cfg.scaningFrequency =" << cfg.scaningFrequency );
//   ROS_INFO_STREAM("cfg.angleResolution=" << cfg.angleResolution);
//   ROS_INFO_STREAM("cfg.startAngle  =" << cfg.startAngle);
//   ROS_INFO_STREAM("cfg.stopAngle  =" << cfg.stopAngle);

    ROS_INFO_STREAM("Connecting to laser at " << host);
    outputRange = laser.getScanOutputRange();

   ROS_INFO_STREAM("outputRange.angleResoluton=" << outputRange.angleResolution);
   ROS_INFO_STREAM("outputRange.startAngle  =" << outputRange.startAngle);
   ROS_INFO_STREAM("outputRange.stopAngle	=" << outputRange.stopAngle);

    if (cfg.scaningFrequency != 2500)
    {
      laser.disconnect();
      ROS_WARN("Unable to get laser output range. Retrying.");
      ros::Duration(1).sleep();
      continue;
    }

    ROS_INFO("Connected to laser.");

    ROS_DEBUG("Laser configuration: scaningFrequency %d, angleResolution %d, startAngle %d, stopAngle %d",
              cfg.scaningFrequency, cfg.angleResolution, cfg.startAngle, cfg.stopAngle);
    ROS_DEBUG("Laser output range:angleResolution %d, startAngle %d, stopAngle %d",
              outputRange.angleResolution, outputRange.startAngle, outputRange.stopAngle);

    scan_msg.header.frame_id = frame_id;
    scan_msg.range_min = 0.01;
    scan_msg.range_max = 20.0;
    scan_msg.scan_time = 100.0 / cfg.scaningFrequency;
    scan_msg.angle_increment = (double)cfg.angleResolution / 10000.0 * DEG2RAD;
    scan_msg.angle_min = (double)outputRange.startAngle / 10000.0 * DEG2RAD - M_PI / 2;
    scan_msg.angle_max = (double)outputRange.stopAngle / 10000.0 * DEG2RAD - M_PI / 2;

    gmapscan_msg.header.frame_id = gmapframe_id;
    gmapscan_msg.range_min = 0.01;
    gmapscan_msg.range_max = 20.0;
    gmapscan_msg.scan_time = 100.0 / cfg.scaningFrequency;
    gmapscan_msg.angle_increment = (double)cfg.angleResolution / 10000.0 * DEG2RAD;
    gmapscan_msg.angle_min = (double)outputRange.startAngle / 10000.0 * DEG2RAD - M_PI / 2;
    gmapscan_msg.angle_max = (double)outputRange.stopAngle / 10000.0 * DEG2RAD - M_PI / 2;

    ROS_INFO_STREAM("Device resolution is " << (double)outputRange.angleResolution / 10000.0 << " degrees.");
    ROS_INFO_STREAM("Device frequency is " << (double)cfg.scaningFrequency / 100.0 << " Hz");

    int angle_range = outputRange.stopAngle - outputRange.startAngle;
    int num_values = angle_range / cfg.angleResolution ;

    if (angle_range % cfg.angleResolution == 0)
    {
      // Include endpoint
      ++num_values;
    }

    ROS_INFO_STREAM("Device num_values is " << num_values);
    scan_msg.ranges.resize(num_values);
    scan_msg.intensities.resize(num_values);

	gmapscan_msg.ranges.resize(num_values);
    gmapscan_msg.intensities.resize(num_values);

    scan_msg.time_increment =
      (cfg.angleResolution / 10000.0)
      / 360.0
      / (cfg.scaningFrequency / 100.0);

    ROS_INFO_STREAM("Time increment is " << static_cast<int>(scan_msg.time_increment * 1000000) << " microseconds");

    dataCfg.outputChannel = 1;
    dataCfg.remission = true;
    dataCfg.resolution = 1;
    dataCfg.encoder = 0;
    dataCfg.position = false;
    dataCfg.deviceName = false;
    dataCfg.outputInterval = 1;

    //ROS_DEBUG("Setting scan data configuration.");
    //laser.setScanDataCfg(dataCfg);

    ROS_INFO_STREAM("Starting measurements.");
    laser.startMeas();

    ROS_INFO_STREAM("Waiting for ready status.");
    ros::Time ready_status_timeout = ros::Time::now() + ros::Duration(5);

    //while(1)
    //{
    status_t stat = laser.queryStatus();
    ros::Duration(1.0).sleep();
    if (stat != ready_for_measurement)
    {
      ROS_WARN("Laser not ready. Retrying initialization.");
      laser.disconnect();
      ros::Duration(1).sleep();
      continue;
    }
    /*if (stat == ready_for_measurement)
    {
      ROS_DEBUG("Ready status achieved.");
      break;
    }

      if (ros::Time::now() > ready_status_timeout)
      {
        ROS_WARN("Timed out waiting for ready status. Trying again.");
        laser.disconnect();
        continue;
      }

      if (!ros::ok())
      {
        laser.disconnect();
        return 1;
      }
    }*/

    ROS_DEBUG("Starting device.");
    laser.startDevice(); // Log out to properly re-enable system after config

    ROS_INFO_STREAM("Commanding continuous measurements.");
    laser.scanContinous(1);

	int zero_cnt = 0;
	float tmp_zero_bnd = 20.0;
	int rec_flag = 0;

    while (ros::ok())
    {

      ros::Time start = ros::Time::now();

      scan_msg.header.stamp = start;
      ++scan_msg.header.seq;

      gmapscan_msg.header.stamp = start;
      ++gmapscan_msg.header.seq;

      scanData data;
      ROS_DEBUG("Reading scan data.");
      if (laser.getScanData(&data))
      {
        for (int i = 0; i < data.dist_len1; i++)
        {
			if(data.dist1[i] * 0.001 > 0.05)  //if scan < 0.05 we believe that is wrong or interference
			{
				if(0 == zero_cnt)
				{
					scan_msg.ranges[data.dist_len1-1-i] = data.dist1[i] * 0.001;  //built for lms1xxinv_node for cartographer
					gmapscan_msg.ranges[data.dist_len1-1-i] = data.dist1[i] * 0.001;
				}
				else
				{
					float tmp_scan = data.dist1[i] * 0.001;
					float min_bnd_scan = MIN(tmp_scan,tmp_zero_bnd);
					for(int j = 0; j <= zero_cnt; j++)
					{
						scan_msg.ranges[data.dist_len1-1-i+j] = min_bnd_scan;	//care for the over bound
						gmapscan_msg.ranges[data.dist_len1-1-i+j] = min_bnd_scan;
					}
					zero_cnt = 0;
					rec_flag = 0;
				}

			}
			else
			{
				zero_cnt++;
				if(0 == rec_flag)
				{
					tmp_zero_bnd = data.dist1[i-1] * 0.001;
					rec_flag = 1;
				}
				scan_msg.ranges[data.dist_len1-1-i] = data.dist1[i] * 0.001;
				gmapscan_msg.ranges[data.dist_len1-1-i] = data.dist1[i] * 0.001;
			}

		  //scan_msg.ranges[data.dist_len1-1-i] = data.dist1[i] * 0.001;  //built for lms1xxinv_node for cartographer
		  //gmapscan_msg.ranges[data.dist_len1-1-i] = data.dist1[i] * 0.001;  //built for lms1xxinv_node for cartographer
        }

        for (int i = 0; i < data.rssi_len1; i++)
        {
          scan_msg.intensities[i] = data.rssi1[i];
		  gmapscan_msg.intensities[i] = data.rssi1[i];
        }

        ROS_DEBUG("Publishing scan data.");
        scan_pub.publish(scan_msg);
		gmapscan_pub.publish(gmapscan_msg);
      }
      else
      {
        ROS_ERROR("Laser timed out on delivering scan, attempting to reinitialize.");
        break;
      }

      ros::spinOnce();
    }

    laser.scanContinous(0);
    laser.stopMeas();
    laser.disconnect();
  }

  return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015 SeNDA
 *
 * 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.
 *
 */
/**
 * FILE PayloadBlock.cpp
 * AUTHOR Blackcatn13
 * DATE Jun 16, 2015
 * VERSION 1
 * This file contains the implementation of the PayloadBlock class.
 */

#include "Bundle/PayloadBlock.h"
#include <string>
#include <sstream>
#include "Bundle/BundleTypes.h"
#include "Utils/SDNV.h"

PayloadBlock::PayloadBlock()
    : m_payload() {
  m_blockType = static_cast<uint8_t>(BlockTypes::PAYLOAD_BLOCK);
}

PayloadBlock::PayloadBlock(const std::string &rawData) {
  /**
   * The payload block contains
   *
   * Block Type 1 byte
   * Proc. Flags as SDNV
   * Block Length as SDNV
   * Payload variable length
   */
  // Get the Block Type
  uint8_t blockType = static_cast<uint8_t>(rawData[0]);
  // If the block type is a paylod block
  if (blockType == static_cast<uint8_t>(BlockTypes::PAYLOAD_BLOCK)) {
    // Set the block type to payload
    m_blockType = static_cast<uint8_t>(BlockTypes::PAYLOAD_BLOCK);
    std::string data = rawData;
    data = data.substr(1);
    // Get the proc flags.
    size_t procFlagsSize = getLength(data);
    uint64_t procFlags = decode(data);
    m_procFlags = std::bitset<7>(procFlags);
    data = data.substr(procFlagsSize);
    // Jump the payload length, the rawData only contains this block
    size_t payloadSizeSize = getLength(data);
    data = data.substr(procFlagsSize);
    m_payload = data;
  }
}

PayloadBlock::~PayloadBlock() {
}

std::string PayloadBlock::getRaw() {
  /**
   * The payload block contains
   *
   * Block Type 1 byte
   * Proc. Flags as SDNV
   * Block Length as SDNV
   * Payload variable length
   */
  std::stringstream ss;
  ss << m_blockType;
  ss << encode(m_procFlags.to_ulong());
  ss << encode(m_payload.size());
  ss << m_payload;
  return ss.str();
}

std::string PayloadBlock::getPayload() {
  return m_payload;
}

void PayloadBlock::setPayload(const std::string &payload) {
  m_payload = payload;
}

<commit_msg>Fixes misspelling error.<commit_after>/*
 * Copyright (c) 2015 SeNDA
 *
 * 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.
 *
 */
/**
 * FILE PayloadBlock.cpp
 * AUTHOR Blackcatn13
 * DATE Jun 16, 2015
 * VERSION 1
 * This file contains the implementation of the PayloadBlock class.
 */

#include "Bundle/PayloadBlock.h"
#include <string>
#include <sstream>
#include "Bundle/BundleTypes.h"
#include "Utils/SDNV.h"

PayloadBlock::PayloadBlock()
    : m_payload() {
  m_blockType = static_cast<uint8_t>(BlockTypes::PAYLOAD_BLOCK);
}

PayloadBlock::PayloadBlock(const std::string &rawData) {
  /**
   * The payload block contains
   *
   * Block Type 1 byte
   * Proc. Flags as SDNV
   * Block Length as SDNV
   * Payload variable length
   */
  // Get the Block Type
  uint8_t blockType = static_cast<uint8_t>(rawData[0]);
  // If the block type is a paylod block
  if (blockType == static_cast<uint8_t>(BlockTypes::PAYLOAD_BLOCK)) {
    // Set the block type to payload
    m_blockType = static_cast<uint8_t>(BlockTypes::PAYLOAD_BLOCK);
    std::string data = rawData;
    data = data.substr(1);
    // Get the proc flags.
    size_t procFlagsSize = getLength(data);
    uint64_t procFlags = decode(data);
    m_procFlags = std::bitset<7>(procFlags);
    data = data.substr(procFlagsSize);
    // Jump the payload length, the rawData only contains this block
    size_t payloadSize = getLength(data);
    data = data.substr(payloadSize);
    m_payload = data;
  }
}

PayloadBlock::~PayloadBlock() {
}

std::string PayloadBlock::getRaw() {
  /**
   * The payload block contains
   *
   * Block Type 1 byte
   * Proc. Flags as SDNV
   * Block Length as SDNV
   * Payload variable length
   */
  std::stringstream ss;
  ss << m_blockType;
  ss << encode(m_procFlags.to_ulong());
  ss << encode(m_payload.size());
  ss << m_payload;
  return ss.str();
}

std::string PayloadBlock::getPayload() {
  return m_payload;
}

void PayloadBlock::setPayload(const std::string &payload) {
  m_payload = payload;
}

<|endoftext|>