<commit_before>//
// Copyright (c) 2013-2017 Christoph Malek
// See LICENSE for more information.
//

#ifndef RJ_GAME_ENTITY_HANDLER_HPP
#define RJ_GAME_ENTITY_HANDLER_HPP

#include "collision.hpp"
#include "components/player.hpp"
#include "entity.hpp"
#include "particle_manager.hpp"

#include <mlk/containers/container_utl.h>
#include <mlk/log/log.h>
#include <mlk/types/types.h>

#include <vector>

namespace rj
{
	template <typename T>
	using entity_ptr = mlk::sptr<T>;
	using entity_base_ptr = entity_ptr<entity_base>;
	using player_ptr = entity_ptr<player>;

	class entity_handler
	{
		rndr& m_render;
		particle_manager<game_handler>& m_particlemgr;
		game_handler* m_gamehandler{nullptr};

		player_ptr m_player{nullptr};
		std::vector<entity_base_ptr> m_entities;
		std::size_t m_max_entities;
		std::size_t m_current_id{0};

		static constexpr float m_despawn_zone{0.f};

	public:
		using iterator = std::vector<entity_base_ptr>::iterator;
		using const_iterator = std::vector<entity_base_ptr>::const_iterator;

		entity_handler(rndr& r, particle_manager<game_handler>& pm,
					   std::size_t max_entities = 100000)
			: m_render{r}, m_particlemgr{pm}, m_max_entities{max_entities}
		{
		}

		void set_gamehandler(game_handler* gh) { m_gamehandler = gh; }

		bool create_entity(const entity_base_ptr& e) noexcept
		{
			if(!this->is_entity_valid(e)) return false;

			this->create_entity_impl(e);// add/create entity in handler
			return true;
		}

		bool create_entity(const player_ptr& p) noexcept
		{
			if(!this->is_entity_valid(p) || this->is_player_registered())
				return false;

			this->create_entity_impl(p);
			return true;
		}

		void update(dur duration)
		{
			// update player
			if(this->is_player_registered()) m_player->update(duration);

			// update other
			for(auto& a : m_entities) {
				a->update(duration);
				if(a->right_out() <= m_despawn_zone) a->destroy();
			}

			this->check_collision();

			// erase flagged entities
			this->erase_destroyed();
		}

		void render()
		{
			// render player
			if(this->is_player_registered()) m_player->render();

			// render other
			for(auto& a : m_entities) a->render();
		}

		void clear() noexcept { m_entities.clear(); }

		// deleting ents on next update
		void delete_entities(std::vector<iterator>& iters)
		{
			for(auto& a : iters) (*a)->destroy();
		}

		auto get_entities_at(const vec2f& at,
							 const vec2f& size = {1.f, 1.f}) noexcept
		{
			std::vector<iterator> result;
			sf::FloatRect at_bounds{at, size};
			for(auto iter{std::begin(m_entities)}; iter != std::end(m_entities);
				++iter)
			{
				sf::FloatRect ent_bounds{
					{(*iter)->left_out(), (*iter)->top_out()}, (*iter)->size()};
				if(ent_bounds.intersects(at_bounds)) result.emplace_back(iter);
			}
			return result;
		}

		bool exists_entity_at(const vec2f& at,
							  const vec2f& size = {1.f, 1.f}) noexcept
		{
			return !this->get_entities_at(at, size).empty();
		}

		iterator begin() { return std::begin(m_entities); }

		iterator end() { return std::end(m_entities); }

		std::size_t num_entities() const noexcept
		{
			return m_entities.size() + this->is_player_registered();
		}

		auto& player() noexcept { return m_player; }

		bool is_player_registered() const noexcept
		{
			return m_player != nullptr;
		}

		void set_outlines_dbg(bool on)
		{
			for(auto& e : m_entities) {
				if(e->figure() == entity_figure::f_rectangle) {
					auto ptr{std::static_pointer_cast<platform>(e)};
					ptr->activate_outlines(on);
				}
				else if(e->figure() == entity_figure::f_triangle)
				{
					auto ptr{std::static_pointer_cast<triangle>(e)};
					ptr->activate_outlines(on);
				}
			}
		}

	private:
		void on_player_death();

		void try_player_death()
		{
			if(!m_player->is_alive()) return;

			// player should die here
			// do effects, game stats etc....
			m_player->render_object().setFillColor({255, 0, 0});
			m_particlemgr.create_particles(10000, m_player->pos(), 3000, true);

			// on kill
			m_player->on_kill();
			this->on_player_death();
		}

		void check_collision() noexcept
		{
			if(!this->is_player_registered()) return;

			bool collided{false};

			for(auto& a : m_entities) {
				if(is_colliding(*m_player, *a)) {
					collided = true;

					if(m_player->bottom_out() - 2 <= a->top_out()) {
						m_player->on_collision(a->top_out());
						m_player->render_object().setFillColor({0, 255, 0});
					}
					else
					{
						this->try_player_death();
					}

					if(a->has_propertie(entity_propertie::death)) {
						// player touched death entity
						this->try_player_death();
					}
				}
			}
			if(!collided) m_player->on_collision_end();
		}

		// checking the entities
		bool is_entity_valid(const entity_base_ptr& e) const noexcept
		{
			if(m_entities.size() >= m_max_entities) {
				mlk::lout("rj::entity_handler")
					<< "max_entities limit is reached,"
					   "can't add more entities";
				return false;
			}
			if(e->is_registered()) {
				mlk::lout("rj::entity_handler")
					<< "entity with id '" << e->m_id
					<< "' exists already in entity handler, ignoring";
				return false;
			}
			return true;
		}

		// create the entities
		void create_entity_impl(const entity_base_ptr& e) noexcept
		{
			this->register_impl(e);
			m_entities.push_back(e);
		}

		void create_entity_impl(const player_ptr& p) noexcept
		{
			this->register_impl(p);
			m_player = p;
		}

		void register_impl(const entity_base_ptr& e) noexcept
		{
			// important: set game and init
			e->handler_register(&m_render, m_current_id);
			e->init();
			++m_current_id;
		}

		void erase_destroyed() noexcept
		{
			mlk::cnt::remove_all_if(
				[](const auto& entity) { return entity->m_destroyed; },
				m_entities);
		}
	};
}

#endif// RJ_GAME_ENTITY_HANDLER_HPP
<commit_msg>entity_handler::update: using one loop instead of 3<commit_after>//
// Copyright (c) 2013-2017 Christoph Malek
// See LICENSE for more information.
//

#ifndef RJ_GAME_ENTITY_HANDLER_HPP
#define RJ_GAME_ENTITY_HANDLER_HPP

#include "collision.hpp"
#include "components/player.hpp"
#include "entity.hpp"
#include "particle_manager.hpp"

#include <mlk/containers/container_utl.h>
#include <mlk/log/log.h>
#include <mlk/types/types.h>

#include <vector>

namespace rj
{
	template <typename T>
	using entity_ptr = mlk::sptr<T>;
	using entity_base_ptr = entity_ptr<entity_base>;
	using player_ptr = entity_ptr<player>;

	class entity_handler
	{
		rndr& m_render;
		particle_manager<game_handler>& m_particlemgr;
		game_handler* m_gamehandler{nullptr};

		player_ptr m_player{nullptr};
		std::vector<entity_base_ptr> m_entities;
		std::size_t m_max_entities;
		std::size_t m_current_id{0};

		static constexpr float m_despawn_zone{0.f};

	public:
		using iterator = std::vector<entity_base_ptr>::iterator;
		using const_iterator = std::vector<entity_base_ptr>::const_iterator;

		entity_handler(rndr& r, particle_manager<game_handler>& pm,
					   std::size_t max_entities = 100000)
			: m_render{r}, m_particlemgr{pm}, m_max_entities{max_entities}
		{
		}

		void set_gamehandler(game_handler* gh) { m_gamehandler = gh; }

		bool create_entity(const entity_base_ptr& e) noexcept
		{
			if(!this->is_entity_valid(e)) return false;

			this->create_entity_impl(e);// add/create entity in handler
			return true;
		}

		bool create_entity(const player_ptr& p) noexcept
		{
			if(!this->is_entity_valid(p) || this->is_player_registered())
				return false;

			this->create_entity_impl(p);
			return true;
		}

		void update(dur duration)
		{
			// update player
			if(this->is_player_registered()) m_player->update(duration);

			// update other
			bool collided{false};
			for(auto iter{m_entities.begin()}; iter < m_entities.end(); ++iter)
			{
				auto a{*iter};
				a->update(duration);

				// check collision
				if(this->is_player_registered()) {
					if(is_colliding(*m_player, *a)) {
						collided = true;

						if(m_player->bottom_out() - 2 <= a->top_out()) {
							m_player->on_collision(a->top_out());
							m_player->render_object().setFillColor({0, 255, 0});
						}
						else
						{
							this->try_player_death();
						}

						if(a->has_propertie(entity_propertie::death)) {
							// player touched death entity
							this->try_player_death();
						}
					}
				}
				if(a->right_out() <= m_despawn_zone) {
					a->destroy();
					m_entities.erase(iter);
				}
			}
			if(!collided) m_player->on_collision_end();
		}

		void render()
		{
			// render player
			if(this->is_player_registered()) m_player->render();

			// render other
			for(auto& a : m_entities) a->render();
		}

		void clear() noexcept { m_entities.clear(); }

		// deleting ents on next update
		void delete_entities(std::vector<iterator>& iters)
		{
			for(auto& a : iters) (*a)->destroy();
		}

		auto get_entities_at(const vec2f& at,
							 const vec2f& size = {1.f, 1.f}) noexcept
		{
			std::vector<iterator> result;
			sf::FloatRect at_bounds{at, size};
			for(auto iter{std::begin(m_entities)}; iter != std::end(m_entities);
				++iter)
			{
				sf::FloatRect ent_bounds{
					{(*iter)->left_out(), (*iter)->top_out()}, (*iter)->size()};
				if(ent_bounds.intersects(at_bounds)) result.emplace_back(iter);
			}
			return result;
		}

		bool exists_entity_at(const vec2f& at,
							  const vec2f& size = {1.f, 1.f}) noexcept
		{
			return !this->get_entities_at(at, size).empty();
		}

		iterator begin() { return std::begin(m_entities); }

		iterator end() { return std::end(m_entities); }

		std::size_t num_entities() const noexcept
		{
			return m_entities.size() + this->is_player_registered();
		}

		auto& player() noexcept { return m_player; }

		bool is_player_registered() const noexcept
		{
			return m_player != nullptr;
		}

		void set_outlines_dbg(bool on)
		{
			for(auto& e : m_entities) {
				if(e->figure() == entity_figure::f_rectangle) {
					auto ptr{std::static_pointer_cast<platform>(e)};
					ptr->activate_outlines(on);
				}
				else if(e->figure() == entity_figure::f_triangle)
				{
					auto ptr{std::static_pointer_cast<triangle>(e)};
					ptr->activate_outlines(on);
				}
			}
		}

	private:
		void on_player_death();

		void try_player_death()
		{
			if(!m_player->is_alive()) return;

			// player should die here
			// do effects, game stats etc....
			m_player->render_object().setFillColor({255, 0, 0});
			m_particlemgr.create_particles(10000, m_player->pos(), 3000, true);

			// on kill
			m_player->on_kill();
			this->on_player_death();
		}

		// checking the entities
		bool is_entity_valid(const entity_base_ptr& e) const noexcept
		{
			if(m_entities.size() >= m_max_entities) {
				mlk::lout("rj::entity_handler")
					<< "max_entities limit is reached,"
					   "can't add more entities";
				return false;
			}
			if(e->is_registered()) {
				mlk::lout("rj::entity_handler")
					<< "entity with id '" << e->m_id
					<< "' exists already in entity handler, ignoring";
				return false;
			}
			return true;
		}

		// create the entities
		void create_entity_impl(const entity_base_ptr& e) noexcept
		{
			this->register_impl(e);
			m_entities.push_back(e);
		}

		void create_entity_impl(const player_ptr& p) noexcept
		{
			this->register_impl(p);
			m_player = p;
		}

		void register_impl(const entity_base_ptr& e) noexcept
		{
			// important: set game and init
			e->handler_register(&m_render, m_current_id);
			e->init();
			++m_current_id;
		}

		void erase_destroyed() noexcept
		{
			mlk::cnt::remove_all_if(
				[](const auto& entity) { return entity->m_destroyed; },
				m_entities);
		}
	};
}

#endif// RJ_GAME_ENTITY_HANDLER_HPP
<|endoftext|>


<commit_before>// The Art of C++ / Sequences
// Copyright (c) 2015 Daniel Frey

#ifndef TAOCPP_SEQUENCES_INCLUDE_MAKE_INTEGER_SEQUENCE_HPP
#define TAOCPP_SEQUENCES_INCLUDE_MAKE_INTEGER_SEQUENCE_HPP

#include <cstddef>
#include <utility>
#include <type_traits>

#include "integer_sequence.hpp"

namespace tao
{
  namespace seq
  {

#ifdef _LIBCXX_VERSION

    // libc++ already has very efficient versions for make_*

    using std::make_integer_sequence;
    using std::make_index_sequence;
    using std::index_sequence_for;

#else

    // idea from http://stackoverflow.com/a/13073076

    namespace impl
    {
      template< typename S, bool, std::size_t = S::size() >
      struct double_up;

      template< typename T, T... Ns, std::size_t N >
      struct double_up< integer_sequence< T, Ns... >, false, N >
      {
        using type = integer_sequence< T, Ns..., ( N + Ns )... >;
      };

      template< typename T, T... Ns, std::size_t N >
      struct double_up< integer_sequence< T, Ns... >, true, N >
      {
        using type = integer_sequence< T, Ns..., ( N + Ns )..., 2 * N >;
      };

      template< typename T, T N, typename = void >
      struct generate;

      template< typename T, T N >
      using generate_t = typename generate< T, N >::type;

      template< typename T, T N >
      struct generate< T, N, typename std::enable_if< ( N > 1 ) >::type >
        : double_up< generate_t< T, N / 2 >, N % 2 == 1 >
      {};

      template< typename T, T N >
      struct generate< T, N, typename std::enable_if< ( N == 0 ) >::type >
      {
        using type = integer_sequence< T >;
      };

      template< typename T, T N >
      struct generate< T, N, typename std::enable_if< ( N == 1 ) >::type >
      {
        using type = integer_sequence< T, 0 >;
      };
    }

    template< typename T, T N >
    using make_integer_sequence = impl::generate_t< T, N >;

    template< std::size_t N >
    using make_index_sequence = make_integer_sequence< std::size_t, N >;

    template< typename... Ts >
    using index_sequence_for = make_index_sequence< sizeof...( Ts ) >;

#endif

  }
}

#endif // TAOCPP_SEQUENCES_INCLUDE_MAKE_INTEGER_SEQUENCE_HPP
<commit_msg>Fix detection of libc++<commit_after>// The Art of C++ / Sequences
// Copyright (c) 2015 Daniel Frey

#ifndef TAOCPP_SEQUENCES_INCLUDE_MAKE_INTEGER_SEQUENCE_HPP
#define TAOCPP_SEQUENCES_INCLUDE_MAKE_INTEGER_SEQUENCE_HPP

#include <cstddef>
#include <utility>
#include <type_traits>

#include "integer_sequence.hpp"

namespace tao
{
  namespace seq
  {

#ifdef _LIBCPP_VERSION

    // libc++ already has very efficient versions for make_*

    using std::make_integer_sequence;
    using std::make_index_sequence;
    using std::index_sequence_for;

#else

    // idea from http://stackoverflow.com/a/13073076

    namespace impl
    {
      template< typename S, bool, std::size_t = S::size() >
      struct double_up;

      template< typename T, T... Ns, std::size_t N >
      struct double_up< integer_sequence< T, Ns... >, false, N >
      {
        using type = integer_sequence< T, Ns..., ( N + Ns )... >;
      };

      template< typename T, T... Ns, std::size_t N >
      struct double_up< integer_sequence< T, Ns... >, true, N >
      {
        using type = integer_sequence< T, Ns..., ( N + Ns )..., 2 * N >;
      };

      template< typename T, T N, typename = void >
      struct generate;

      template< typename T, T N >
      using generate_t = typename generate< T, N >::type;

      template< typename T, T N >
      struct generate< T, N, typename std::enable_if< ( N > 1 ) >::type >
        : double_up< generate_t< T, N / 2 >, N % 2 == 1 >
      {};

      template< typename T, T N >
      struct generate< T, N, typename std::enable_if< ( N == 0 ) >::type >
      {
        using type = integer_sequence< T >;
      };

      template< typename T, T N >
      struct generate< T, N, typename std::enable_if< ( N == 1 ) >::type >
      {
        using type = integer_sequence< T, 0 >;
      };
    }

    template< typename T, T N >
    using make_integer_sequence = impl::generate_t< T, N >;

    template< std::size_t N >
    using make_index_sequence = make_integer_sequence< std::size_t, N >;

    template< typename... Ts >
    using index_sequence_for = make_index_sequence< sizeof...( Ts ) >;

#endif

  }
}

#endif // TAOCPP_SEQUENCES_INCLUDE_MAKE_INTEGER_SEQUENCE_HPP
<|endoftext|>


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

#include "llfloatertestinspectors.h"

// Viewer includes
#include "llstartup.h"

// Linden library includes
#include "llfloaterreg.h"
//#include "lluictrlfactory.h"

LLFloaterTestInspectors::LLFloaterTestInspectors(const LLSD& seed)
:	LLFloater(seed)
{
	mCommitCallbackRegistrar.add("ShowAvatarInspector",
		boost::bind(&LLFloaterTestInspectors::showAvatarInspector, this, _1, _2));
	mCommitCallbackRegistrar.add("ShowObjectInspector",
		boost::bind(&LLFloaterTestInspectors::showObjectInspector, this, _1, _2));
}

LLFloaterTestInspectors::~LLFloaterTestInspectors()
{}

BOOL LLFloaterTestInspectors::postBuild()
{
//	getChild<LLUICtrl>("avatar_2d_btn")->setCommitCallback(
//		boost::bind(&LLFloaterTestInspectors::onClickAvatar2D, this));
	getChild<LLUICtrl>("avatar_3d_btn")->setCommitCallback(
		boost::bind(&LLFloaterTestInspectors::onClickAvatar3D, this));
	getChild<LLUICtrl>("object_2d_btn")->setCommitCallback(
		boost::bind(&LLFloaterTestInspectors::onClickObject2D, this));
	getChild<LLUICtrl>("object_3d_btn")->setCommitCallback(
		boost::bind(&LLFloaterTestInspectors::onClickObject3D, this));
	getChild<LLUICtrl>("group_btn")->setCommitCallback(
		boost::bind(&LLFloaterTestInspectors::onClickGroup, this));
	getChild<LLUICtrl>("place_btn")->setCommitCallback(
		boost::bind(&LLFloaterTestInspectors::onClickPlace, this));
	getChild<LLUICtrl>("event_btn")->setCommitCallback(
		boost::bind(&LLFloaterTestInspectors::onClickEvent, this));

	return LLFloater::postBuild();
}

void LLFloaterTestInspectors::showAvatarInspector(LLUICtrl*, const LLSD& avatar_id)
{
	LLUUID id;  // defaults to null
	if (LLStartUp::getStartupState() >= STATE_STARTED)
	{
		id = avatar_id.asUUID();
	}
	// spawns off mouse position automatically
	LLFloaterReg::showInstance("inspect_avatar", LLSD().insert("avatar_id", id));
}

void LLFloaterTestInspectors::showObjectInspector(LLUICtrl*, const LLSD& object_id)
{
	LLFloaterReg::showInstance("inspect_object", LLSD().insert("object_id", object_id));
}

void LLFloaterTestInspectors::onClickAvatar2D()
{
}

void LLFloaterTestInspectors::onClickAvatar3D()
{
}

void LLFloaterTestInspectors::onClickObject2D()
{
}

void LLFloaterTestInspectors::onClickObject3D()
{
}

void LLFloaterTestInspectors::onClickGroup()
{
}

void LLFloaterTestInspectors::onClickPlace()
{
}

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

#include "llfloatertestinspectors.h"

// Viewer includes
#include "llstartup.h"

// Linden library includes
#include "llfloaterreg.h"
//#include "lluictrlfactory.h"

LLFloaterTestInspectors::LLFloaterTestInspectors(const LLSD& seed)
:	LLFloater(seed)
{
	mCommitCallbackRegistrar.add("ShowAvatarInspector",
		boost::bind(&LLFloaterTestInspectors::showAvatarInspector, this, _1, _2));
	mCommitCallbackRegistrar.add("ShowObjectInspector",
		boost::bind(&LLFloaterTestInspectors::showObjectInspector, this, _1, _2));
}

LLFloaterTestInspectors::~LLFloaterTestInspectors()
{}

BOOL LLFloaterTestInspectors::postBuild()
{
	getChild<LLUICtrl>("intentionally-not-found");

//	getChild<LLUICtrl>("avatar_2d_btn")->setCommitCallback(
//		boost::bind(&LLFloaterTestInspectors::onClickAvatar2D, this));
	getChild<LLUICtrl>("avatar_3d_btn")->setCommitCallback(
		boost::bind(&LLFloaterTestInspectors::onClickAvatar3D, this));
	getChild<LLUICtrl>("object_2d_btn")->setCommitCallback(
		boost::bind(&LLFloaterTestInspectors::onClickObject2D, this));
	getChild<LLUICtrl>("object_3d_btn")->setCommitCallback(
		boost::bind(&LLFloaterTestInspectors::onClickObject3D, this));
	getChild<LLUICtrl>("group_btn")->setCommitCallback(
		boost::bind(&LLFloaterTestInspectors::onClickGroup, this));
	getChild<LLUICtrl>("place_btn")->setCommitCallback(
		boost::bind(&LLFloaterTestInspectors::onClickPlace, this));
	getChild<LLUICtrl>("event_btn")->setCommitCallback(
		boost::bind(&LLFloaterTestInspectors::onClickEvent, this));

	return LLFloater::postBuild();
}

void LLFloaterTestInspectors::showAvatarInspector(LLUICtrl*, const LLSD& avatar_id)
{
	LLUUID id;  // defaults to null
	if (LLStartUp::getStartupState() >= STATE_STARTED)
	{
		id = avatar_id.asUUID();
	}
	// spawns off mouse position automatically
	LLFloaterReg::showInstance("inspect_avatar", LLSD().insert("avatar_id", id));
}

void LLFloaterTestInspectors::showObjectInspector(LLUICtrl*, const LLSD& object_id)
{
	LLFloaterReg::showInstance("inspect_object", LLSD().insert("object_id", object_id));
}

void LLFloaterTestInspectors::onClickAvatar2D()
{
}

void LLFloaterTestInspectors::onClickAvatar3D()
{
}

void LLFloaterTestInspectors::onClickObject2D()
{
}

void LLFloaterTestInspectors::onClickObject3D()
{
}

void LLFloaterTestInspectors::onClickGroup()
{
}

void LLFloaterTestInspectors::onClickPlace()
{
}

void LLFloaterTestInspectors::onClickEvent()
{
}
<|endoftext|>


<commit_before>/**
 * @file   llviewercontrollistener.cpp
 * @author Nat Goodspeed
 * @date   2009-06-30
 * @brief  Implementation for llviewercontrollistener.
 *
 * $LicenseInfo:firstyear=2009&license=viewergpl$
 * Copyright (c) 2009, Linden Research, Inc.
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"

#include "llviewercontrollistener.h"

#include "llviewercontrol.h"

LLViewerControlListener gSavedSettingsListener;

LLViewerControlListener::LLViewerControlListener()
	: LLDispatchListener("LLViewerControl",  "group")
{
	add("Global", boost::bind(&LLViewerControlListener::set, &gSavedSettings, _1));
	add("Skin", boost::bind(&LLViewerControlListener::set, &gSavedSkinSettings, _1));
	add("PerAccount", boost::bind(&LLViewerControlListener::set, &gSavedPerAccountSettings, _1));
	add("Warning", boost::bind(&LLViewerControlListener::set, &gWarningSettings, _1));
	add("Crash", boost::bind(&LLViewerControlListener::set, &gCrashSettings, _1));

#if 0
	add(/*"toggleControl",*/ "Global", boost::bind(&LLViewerControlListener::toggleControl, &gSavedSettings, _1));
	add(/*"toggleControl",*/ "Skin", boost::bind(&LLViewerControlListener::toggleControl, &gSavedSkinSettings, _1));
	add(/*"toggleControl",*/ "PerAccount", boost::bind(&LLViewerControlListener::toggleControl, &gSavedPerAccountSettings, _1));
	add(/*"toggleControl",*/ "Warning", boost::bind(&LLViewerControlListener::toggleControl, &gWarningSettings, _1));
	add(/*"toggleControl",*/ "Crash", boost::bind(&LLViewerControlListener::toggleControl, &gCrashSettings, _1));

	add(/*"setDefault",*/ "Global", boost::bind(&LLViewerControlListener::setDefault, &gSavedSettings, _1));
	add(/*"setDefault",*/ "Skin", boost::bind(&LLViewerControlListener::setDefault, &gSavedSkinSettings, _1));
	add(/*"setDefault",*/ "PerAccount", boost::bind(&LLViewerControlListener::setDefault, &gSavedPerAccountSettings, _1));
	add(/*"setDefault",*/ "Warning", boost::bind(&LLViewerControlListener::setDefault, &gWarningSettings, _1));
	add(/*"setDefault",*/ "Crash", boost::bind(&LLViewerControlListener::setDefault, &gCrashSettings, _1));
#endif // 0
}

//static
void LLViewerControlListener::set(LLControlGroup * controls, LLSD const & event_data)
{
	if(event_data.has("key"))
	{
		std::string key(event_data["key"]);

		if(controls->controlExists(key))
		{
			controls->setUntypedValue(key, event_data["value"]);
		}
		else
		{
			llwarns << "requested unknown control: \"" << key << '\"' << llendl;
		}
	}
}

//static
void LLViewerControlListener::toggleControl(LLControlGroup * controls, LLSD const & event_data)
{
	if(event_data.has("key"))
	{
		std::string key(event_data["key"]);

		if(controls->controlExists(key))
		{
			LLControlVariable * control = controls->getControl(key);
			if(control->isType(TYPE_BOOLEAN))
			{
				control->set(!control->get().asBoolean());
			}
			else
			{
				llwarns << "requested toggle of non-boolean control: \"" << key << "\", type is " << control->type() << llendl;
			}
		}
		else
		{
			llwarns << "requested unknown control: \"" << key << '\"' << llendl;
		}
	}
}

//static
void LLViewerControlListener::setDefault(LLControlGroup * controls, LLSD const & event_data)
{
	if(event_data.has("key"))
	{
		std::string key(event_data["key"]);

		if(controls->controlExists(key))
		{
			LLControlVariable * control = controls->getControl(key);
			control->resetToDefault();
		}
		else
		{
			llwarns << "requested unknown control: \"" << key << '\"' << llendl;
		}
	}
}
<commit_msg>Oops, copy/paste error in the llviewercontrol.cpp file top level comments.<commit_after>/**
 * @file   llviewercontrollistener.cpp
 * @author Brad Kittenbrink
 * @date   2009-07-09
 * @brief  Implementation for llviewercontrollistener.
 *
 * $LicenseInfo:firstyear=2009&license=viewergpl$
 * Copyright (c) 2009, Linden Research, Inc.
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"

#include "llviewercontrollistener.h"

#include "llviewercontrol.h"

LLViewerControlListener gSavedSettingsListener;

LLViewerControlListener::LLViewerControlListener()
	: LLDispatchListener("LLViewerControl",  "group")
{
	add("Global", boost::bind(&LLViewerControlListener::set, &gSavedSettings, _1));
	add("Skin", boost::bind(&LLViewerControlListener::set, &gSavedSkinSettings, _1));
	add("PerAccount", boost::bind(&LLViewerControlListener::set, &gSavedPerAccountSettings, _1));
	add("Warning", boost::bind(&LLViewerControlListener::set, &gWarningSettings, _1));
	add("Crash", boost::bind(&LLViewerControlListener::set, &gCrashSettings, _1));

#if 0
	add(/*"toggleControl",*/ "Global", boost::bind(&LLViewerControlListener::toggleControl, &gSavedSettings, _1));
	add(/*"toggleControl",*/ "Skin", boost::bind(&LLViewerControlListener::toggleControl, &gSavedSkinSettings, _1));
	add(/*"toggleControl",*/ "PerAccount", boost::bind(&LLViewerControlListener::toggleControl, &gSavedPerAccountSettings, _1));
	add(/*"toggleControl",*/ "Warning", boost::bind(&LLViewerControlListener::toggleControl, &gWarningSettings, _1));
	add(/*"toggleControl",*/ "Crash", boost::bind(&LLViewerControlListener::toggleControl, &gCrashSettings, _1));

	add(/*"setDefault",*/ "Global", boost::bind(&LLViewerControlListener::setDefault, &gSavedSettings, _1));
	add(/*"setDefault",*/ "Skin", boost::bind(&LLViewerControlListener::setDefault, &gSavedSkinSettings, _1));
	add(/*"setDefault",*/ "PerAccount", boost::bind(&LLViewerControlListener::setDefault, &gSavedPerAccountSettings, _1));
	add(/*"setDefault",*/ "Warning", boost::bind(&LLViewerControlListener::setDefault, &gWarningSettings, _1));
	add(/*"setDefault",*/ "Crash", boost::bind(&LLViewerControlListener::setDefault, &gCrashSettings, _1));
#endif // 0
}

//static
void LLViewerControlListener::set(LLControlGroup * controls, LLSD const & event_data)
{
	if(event_data.has("key"))
	{
		std::string key(event_data["key"]);

		if(controls->controlExists(key))
		{
			controls->setUntypedValue(key, event_data["value"]);
		}
		else
		{
			llwarns << "requested unknown control: \"" << key << '\"' << llendl;
		}
	}
}

//static
void LLViewerControlListener::toggleControl(LLControlGroup * controls, LLSD const & event_data)
{
	if(event_data.has("key"))
	{
		std::string key(event_data["key"]);

		if(controls->controlExists(key))
		{
			LLControlVariable * control = controls->getControl(key);
			if(control->isType(TYPE_BOOLEAN))
			{
				control->set(!control->get().asBoolean());
			}
			else
			{
				llwarns << "requested toggle of non-boolean control: \"" << key << "\", type is " << control->type() << llendl;
			}
		}
		else
		{
			llwarns << "requested unknown control: \"" << key << '\"' << llendl;
		}
	}
}

//static
void LLViewerControlListener::setDefault(LLControlGroup * controls, LLSD const & event_data)
{
	if(event_data.has("key"))
	{
		std::string key(event_data["key"]);

		if(controls->controlExists(key))
		{
			LLControlVariable * control = controls->getControl(key);
			control->resetToDefault();
		}
		else
		{
			llwarns << "requested unknown control: \"" << key << '\"' << llendl;
		}
	}
}
<|endoftext|>


<commit_before>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.

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 "tensorflow/compiler/xla/service/gpu/tests/gpu_codegen_test.h"
#include "tensorflow/compiler/xla/tests/hlo_test_base.h"

namespace xla {
namespace gpu {
namespace {

class KernelThunkTest : public GpuCodegenTest {};

TEST_F(KernelThunkTest, Basic) {
  const char* hlo_text = R"(
    HloModule Test

    add_F32 {
      lhs = f32[] parameter(0)
      rhs = f32[] parameter(1)
      ROOT add = f32[] add(lhs, rhs)
    }

    ENTRY main {
      a = f32[2, 2]{1,0} parameter(0)
      b = f32[2, 2]{1,0} parameter(1)
      ROOT r1 = f32[2, 2]{1,0} map(a, b), dimensions={0, 1}, to_apply=add_F32
    }
  )";

  EXPECT_TRUE(RunAndCompare(hlo_text, ErrorSpec{1e-5, 1e-5}));
}

TEST_F(KernelThunkTest, KernelWithConstants) {
  const char* hlo_text = R"(
    HloModule Test

    add_F32 {
      lhs = f32[] parameter(0)
      rhs = f32[] parameter(1)
      ROOT add = f32[] add(lhs, rhs)
    }

    ENTRY main {
      a = f32[2, 2]{1,0} constant({{1, 2}, {3, 4}})
      b = f32[2, 2]{1,0} constant({{5, 6}, {7, 8}})
      ROOT r1 = f32[2, 2]{1,0} map(a, b), dimensions={0, 1}, to_apply=add_F32
    }
  )";

  EXPECT_TRUE(RunAndCompare(hlo_text, ErrorSpec{1e-5, 1e-5}));
}

}  // namespace
}  // namespace gpu
}  // namespace xla
<commit_msg>Fixes for kernel thunk whole-program lowering.<commit_after>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.

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 "tensorflow/compiler/xla/service/gpu/tests/gpu_codegen_test.h"
#include "tensorflow/compiler/xla/tests/hlo_test_base.h"

namespace xla {
namespace gpu {
namespace {

class KernelThunkTest : public GpuCodegenTest {};

TEST_F(KernelThunkTest, Basic) {
  const char* hlo_text = R"(
    HloModule Test1

    add_F32 {
      lhs = f32[] parameter(0)
      rhs = f32[] parameter(1)
      ROOT add = f32[] add(lhs, rhs)
    }

    ENTRY Test1 {
      a = f32[2, 2]{1,0} parameter(0)
      b = f32[2, 2]{1,0} parameter(1)
      ROOT r1 = f32[2, 2]{1,0} map(a, b), dimensions={0, 1}, to_apply=add_F32
    }
  )";

  EXPECT_TRUE(RunAndCompare(hlo_text, ErrorSpec{1e-5, 1e-5}));
}

TEST_F(KernelThunkTest, KernelWithConstants) {
  const char* hlo_text = R"(
    HloModule Test2

    add_F32 {
      lhs = f32[] parameter(0)
      rhs = f32[] parameter(1)
      ROOT add = f32[] add(lhs, rhs)
    }

    ENTRY Test2 {
      a = f32[2, 2]{1,0} constant({{1, 2}, {3, 4}})
      b = f32[2, 2]{1,0} constant({{5, 6}, {7, 8}})
      ROOT r1 = f32[2, 2]{1,0} map(a, b), dimensions={0, 1}, to_apply=add_F32
    }
  )";

  EXPECT_TRUE(RunAndCompare(hlo_text, ErrorSpec{1e-5, 1e-5}));
}

}  // namespace
}  // namespace gpu
}  // namespace xla
<|endoftext|>


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

#ifndef _SLIDESHOW_SIMPLECONTINUOUSACTIVITYBASE_HXX
#define _SLIDESHOW_SIMPLECONTINUOUSACTIVITYBASE_HXX

#include <activitybase.hxx>
#include <canvas/elapsedtime.hxx>

namespace presentation
{
    namespace internal
    {
        /** Simple, continuous animation.

            This class implements a simple, continuous animation
            without considering repeats or acceleration on the
            perform call. Only useful as a base class, you
            probably want to use ContinuousActivityBase.
        */
        class SimpleContinuousActivityBase : public ActivityBase
        {
        public:
            SimpleContinuousActivityBase( const ActivityParameters& rParms );

            virtual double calcTimeLag() const;

            virtual bool perform();
            virtual void dequeued();

        protected:
            /** Hook for derived classes

                This method will be called from perform().

                @param nSimpleTime
                Simple animation time, without repeat,
                acceleration or deceleration applied. This value
                is always in the [0,1] range, the repeat is
                accounted for with the nRepeatCount parameter.

                @param nRepeatCount
                Number of full repeats already performed
            */
            virtual void simplePerform( double nSimpleTime, sal_uInt32 nRepeatCount ) const = 0;

            virtual void startAnimation();

        private:
            /// Time elapsed since activity started
            ::canvas::tools::ElapsedTime    maTimer;

            /// Simple duration of activity
            const double                    mnMinSimpleDuration;

            /// Minimal number of frames to show (see ActivityParameters)
            const sal_uInt32                mnMinNumberOfFrames;

            /// Actual number of frames shown until now.
            sal_uInt32                      mnCurrPerformCalls;
        };
    }
}

#endif /* _SLIDESHOW_SIMPLECONTINUOUSACTIVITYBASE_HXX */
<commit_msg>INTEGRATION: CWS presfixes08 (1.3.24); FILE MERGED 2005/08/08 09:36:54 dbo 1.3.24.1: #i45197# dequeued() -> ActivityBase added end() Issue number: Submitted by: Reviewed by:<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: simplecontinuousactivitybase.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2005-10-11 08:41:36 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SLIDESHOW_SIMPLECONTINUOUSACTIVITYBASE_HXX
#define _SLIDESHOW_SIMPLECONTINUOUSACTIVITYBASE_HXX

#include <activitybase.hxx>
#include <canvas/elapsedtime.hxx>

namespace presentation
{
    namespace internal
    {
        /** Simple, continuous animation.

            This class implements a simple, continuous animation
            without considering repeats or acceleration on the
            perform call. Only useful as a base class, you
            probably want to use ContinuousActivityBase.
        */
        class SimpleContinuousActivityBase : public ActivityBase
        {
        public:
            SimpleContinuousActivityBase( const ActivityParameters& rParms );

            virtual double calcTimeLag() const;
            virtual bool perform();

        protected:
            /** Hook for derived classes

                This method will be called from perform().

                @param nSimpleTime
                Simple animation time, without repeat,
                acceleration or deceleration applied. This value
                is always in the [0,1] range, the repeat is
                accounted for with the nRepeatCount parameter.

                @param nRepeatCount
                Number of full repeats already performed
            */
            virtual void simplePerform( double nSimpleTime, sal_uInt32 nRepeatCount ) const = 0;

            virtual void startAnimation();

        private:
            /// Time elapsed since activity started
            ::canvas::tools::ElapsedTime    maTimer;

            /// Simple duration of activity
            const double                    mnMinSimpleDuration;

            /// Minimal number of frames to show (see ActivityParameters)
            const sal_uInt32                mnMinNumberOfFrames;

            /// Actual number of frames shown until now.
            sal_uInt32                      mnCurrPerformCalls;
        };
    }
}

#endif /* _SLIDESHOW_SIMPLECONTINUOUSACTIVITYBASE_HXX */
<|endoftext|>


<commit_before>#include "boxml.h"
#include <algorithm>
#include <ctime>
#include <sst/sumi_api.h>

using namespace std;
using namespace sstmac;

namespace lblxml
{
  int boxml::count_events () {
    int ret = g_rank_to_comps[rank_].size()
        + g_rank_to_sends[rank_].size()
        + g_rank_to_recvs[rank_].size()
        + g_rank_to_allreduces[rank_].size();
    return ret;
  }

  bool boxml::send_boxes(int& n_events) {
      SSTMACBacktrace("send boxes");
      // any sends ready?
      da_list_t& v_sends(g_rank_to_valid_sends[rank_]);
      set_t& my_sends(g_rank_to_sends[rank_]);
      int n_send = v_sends.size();
      if (randomize_events_)
        std::random_shuffle(v_sends.begin(), v_sends.end());
      int n_sent = 0;
      while (!v_sends.empty()) {
        comm_t* sendptr = static_cast<comm_t*>(g_events[v_sends.front()]);
        comm_t& send = *sendptr;
        if (send.n_dep() == 0) { // abundance of caution
          //int count = send.size();
          int count = 0;
          int dest_box = send.to();
          int dest = g_boxindex_to_rank[ dest_box ];
          int index = send.index();
          if( dest != rank_ ) {
            ++n_sent;
            if (debug_ > 0)
              std::cerr << "boxml: rank " << rank_ << " sending message " << index << " to rank " << dest <<  "\n";
            pt2pt_message::ptr mess = new pt2pt_message(index,count);
            comm_rdma_put(dest, mess);
          }
          else {
            simple_event_done(index);
          }
          my_sends.erase(send.index());
          v_sends.pop_front();
        }
        else {
          std::cerr << "error: valid send has n_deps > 0\n";
          abort();
        }
      }

      int old_n_events = n_events;
      n_events -= n_sent;
      //events aren't tracked properly anymore
      if (0) {
        cout << "Rank " << rank_ << " posted " << n_sent << " sends\n";
        if (n_send > 0) {
          int temp_n = count_events();
          if (temp_n != n_events) {
            std::cerr << "send_boxes: n_events " << n_events << " doesn't match count_events() "
                         << temp_n << "\n";
            abort();
          }
          cout << "Rank " << rank_ << " after send processing, "
               << " continuing while loop with " << n_events
               << " events remaining (delta=" << n_events - old_n_events
               << ")\n";
        }
      }

      if (n_sent > 0)
        return true;
      return false;
  }

  /**
   * @brief boxml::reduce
   * @param n_events [IN,OUT]  Number of outstanding events - decrement
   * @return
   */
  bool boxml::reduce(int& n_events) {
    SSTMACBacktrace("reduce");
    int n_allreduce = valid_allreduces_.size();
    while (!valid_allreduces_.empty()) {
      index_box_pair_t pair = valid_allreduces_.front();
      valid_allreduces_.pop();
      int index = pair.first;
      int box_number = pair.second;
      event* ev = g_events[index];
      reduce_t* comm = static_cast<reduce_t*>(ev);
      int my_domain_rank = comm->domain_rank(box_number);
      const int* boxes = comm->box_array();
      sumi::domain* dom = new box_domain(my_domain_rank, comm->nboxes(), boxes, g_boxindex_to_rank.data());

      int count = comm->size();
      if (debug_ > 0)
        std::cerr << "boxml: rank " << rank_ << " starting allreduce " << ev->id() << " for box " << box_number << "\n";
      sumi::comm_allreduce<double,sumi::Add>(NULL, NULL, count, index,
                                 false, sumi::options::initial_context, dom);
    }
    return n_allreduce > 0;
  }

  bool boxml::compute_boxes(int& n_events) {
      SSTMACBacktrace("compute boxes");
      da_list_t& v_comps(g_rank_to_valid_comps[rank_]);
      set_t& my_comps(g_rank_to_comps[rank_]);
      int n_comp = v_comps.size();

      if (n_comp) {
        if (randomize_events_)
          std::random_shuffle(v_comps.begin(), v_comps.end());

        comp_t* compptr = static_cast<comp_t*>(g_events[v_comps.front()]);
        comp_t& comp = *compptr;
        if (comp.n_dep() == 0) { // Abundance of caution
          if (do_compute_) {
            compute( timestamp( compute_scale_ * comp.time() ));
          }
          if (debug_ > 0) {
            cout << "boxml: rank " << rank_ << ": all deps satisfied, performing compute "
                 << comp.id() << " on " << rank_ << "\n";
          }
          my_comps.erase(comp.index());
          v_comps.pop_front();
          simple_event_done(comp.index());
          n_events -= 1; //I only do one compute at a time
        }
        else {
          spkt_throw_printf(sprockit::value_error,
            "valid compute event %d still has %d deps",
            comp.index(), comp.n_dep());
        }
      }

      n_comp = min(n_comp,1);
      int old_n_events = n_events;
      // events aren't properly tracked anymore
      if (0) {
        cout << "Rank " << rank_ << " completed " << n_comp <<  " computes\n";
        if (n_comp) {
          int temp_n = count_events();
          if (temp_n != n_events) {
            std::cerr << "compute_boxes: n_events doesn't match count_events()\n";
            abort();
          }
          cout << "Rank " << rank_ << " after compute processing, "
               << " continuing while loop with " << n_events
               << " events remaining (delta=" << n_events - old_n_events
               << ")\n";
        }
      }
      if (n_comp > 0)
        return true;
      return false;
  }

  void boxml::recv_boxes(int& n_events)
  {
      SSTMACBacktrace("recv boxes");
      sumi::message::ptr dmess = sumi::comm_poll();
      switch (dmess->class_type()){
        case sumi::message::pt2pt:
        {
          if (debug_ > 0)
            std::cerr << "boxml: rank " << rank_ << " receiving pt2pt message\n";
          pt2pt_message::ptr pmess = ptr_safe_cast(pt2pt_message, dmess);
          simple_event_done(pmess->event_index());
          break;
        }
        case sumi::message::collective_done:
        {
          sumi::collective_done_message::ptr cmess = ptr_safe_cast(sumi::collective_done_message, dmess);
          box_domain* dom = static_cast<box_domain*>(cmess->dom());
          int my_box_number = dom->my_box_number();
          if (debug_ > 0)
            std::cerr << "boxml: rank " << rank_ << " receiving collective_done message for " << cmess->tag() << "\n";
          collective_done(my_box_number, cmess->tag());
          //for now, we dynamically create domains - delete it
          delete dom;
          break;
        }
        default:
        {
          spkt_throw_printf(sprockit::value_error,
            "got invalid message type %s",
            sumi::message::tostr(dmess->class_type()));
        }
      }

      int old_n_events = n_events;
      --n_events;
      // events aren't properly tracked anymore
      if (0) {
        cout << "Rank " << rank_ << " handled receive\n";
        int temp_n = count_events();
        if (temp_n != n_events) {
          std::cerr << "recv_boxes: n_events " << n_events << " doesn't match count_events() "
                    << temp_n << "\n";
          abort();
        }
        cout << "Rank " << rank_ << " after recv processing, "
             << " continuing while loop with " << n_events
             << " events remaining (delta=" << n_events - old_n_events
             << ")\n";
      }
  }

  void boxml::run_loop() {
    SSTMACBacktrace("run loop");

    //std::cerr << "Rank 0 entering run loop with "
    //          << g_rank_to_recvs[0].size() << " recvs\n";
    if (debug_ > 0) cout << "Rank " << rank_ << " entering run loop with "
                         << g_rank_to_recvs[rank_].size() << " recvs\n";

    // Loop until no elements left
    int total_events = count_events();
    int n_events = total_events;
    int q_events = total_events/4;
    bool q1 = false, q2 = false, q3 = false;
    while (n_events > 0) {
    bool doloop = true;
    //while (doloop) {

      if (debug_ > 0 || detailed_progress_ ) {
        if (n_events < 3 * q_events && q1 == false) {
          cout << "Rank " << rank_ << " 25% complete\n";
          q1 = true;
        }
        if (n_events < 2 * q_events && q2 == false) {
          cout << "Rank " << rank_ << " 50% complete\n";
          q2 = true;
        }
        if (n_events < q_events && q3 == false) {
          cout << "Rank " << rank_ << " 75% complete\n";
          q3 = true;
        }
      }
      else if (rank_ == 0) {
        if (n_events < 3 * q_events && q1 == false) {
          cout << "Rank 0 25% complete\n";
          q1 = true;
        }
        if (n_events < 2 * q_events && q2 == false) {
          cout << "Rank 0 50% complete\n";
          q2 = true;
        }
        if (n_events < q_events && q3 == false) {
          cout << "Rank 0 75% complete\n";
          q3 = true;
        }
      }

      if(detailed_progress_ && rank_ == 0) {
        cout << "Rank 0 completed " << total_events - n_events << " of " << total_events
             << " events\n";
        cout << std::flush;
        cerr << std::flush;
      }

      //std::cerr << "Rank before send boxes with "
      //          << g_rank_to_recvs[0].size() << " recvs\n";

      bool skip_to_next_loop = send_boxes(n_events);
      if (skip_to_next_loop)
        continue;

      //std::cerr << "Rank before compute boxes with "
      //          << g_rank_to_recvs[0].size() << " recvs\n";

      skip_to_next_loop = compute_boxes(n_events);
      if (skip_to_next_loop)
        continue;

      //std::cerr << "Rank before reduce with "
      //          << g_rank_to_recvs[0].size() << " recvs\n";

      skip_to_next_loop = reduce(n_events);
      if (skip_to_next_loop)
        continue;

      //std::cerr << "Rank before recv with "
      //          << g_rank_to_recvs[0].size() << " recvs\n";

      recv_boxes(n_events);

      //if( n_events == count_events())
      //  sstmac_usleep(1000);

      doloop = false;
    }

    if (debug_ > 0)
      cout << "Rank " << rank_ << " completed run loop\n";

  }

}
<commit_msg>remove debugging hack from boxml<commit_after>#include "boxml.h"
#include <algorithm>
#include <ctime>
#include <sst/sumi_api.h>

using namespace std;
using namespace sstmac;

namespace lblxml
{
  int boxml::count_events () {
    int ret = g_rank_to_comps[rank_].size()
        + g_rank_to_sends[rank_].size()
        + g_rank_to_recvs[rank_].size()
        + g_rank_to_allreduces[rank_].size();
    return ret;
  }

  bool boxml::send_boxes(int& n_events) {
      SSTMACBacktrace("send boxes");
      // any sends ready?
      da_list_t& v_sends(g_rank_to_valid_sends[rank_]);
      set_t& my_sends(g_rank_to_sends[rank_]);
      int n_send = v_sends.size();
      if (randomize_events_)
        std::random_shuffle(v_sends.begin(), v_sends.end());
      int n_sent = 0;
      while (!v_sends.empty()) {
        comm_t* sendptr = static_cast<comm_t*>(g_events[v_sends.front()]);
        comm_t& send = *sendptr;
        if (send.n_dep() == 0) { // abundance of caution
          int count = send.size();
          int dest_box = send.to();
          int dest = g_boxindex_to_rank[ dest_box ];
          int index = send.index();
          if( dest != rank_ ) {
            ++n_sent;
            if (debug_ > 0)
              std::cerr << "boxml: rank " << rank_ << " sending message " << index << " to rank " << dest <<  "\n";
            pt2pt_message::ptr mess = new pt2pt_message(index,count);
            comm_rdma_put(dest, mess);
          }
          else {
            simple_event_done(index);
          }
          my_sends.erase(send.index());
          v_sends.pop_front();
        }
        else {
          std::cerr << "error: valid send has n_deps > 0\n";
          abort();
        }
      }

      int old_n_events = n_events;
      n_events -= n_sent;
      //events aren't tracked properly anymore
      if (0) {
        cout << "Rank " << rank_ << " posted " << n_sent << " sends\n";
        if (n_send > 0) {
          int temp_n = count_events();
          if (temp_n != n_events) {
            std::cerr << "send_boxes: n_events " << n_events << " doesn't match count_events() "
                         << temp_n << "\n";
            abort();
          }
          cout << "Rank " << rank_ << " after send processing, "
               << " continuing while loop with " << n_events
               << " events remaining (delta=" << n_events - old_n_events
               << ")\n";
        }
      }

      if (n_sent > 0)
        return true;
      return false;
  }

  /**
   * @brief boxml::reduce
   * @param n_events [IN,OUT]  Number of outstanding events - decrement
   * @return
   */
  bool boxml::reduce(int& n_events) {
    SSTMACBacktrace("reduce");
    int n_allreduce = valid_allreduces_.size();
    while (!valid_allreduces_.empty()) {
      index_box_pair_t pair = valid_allreduces_.front();
      valid_allreduces_.pop();
      int index = pair.first;
      int box_number = pair.second;
      event* ev = g_events[index];
      reduce_t* comm = static_cast<reduce_t*>(ev);
      int my_domain_rank = comm->domain_rank(box_number);
      const int* boxes = comm->box_array();
      sumi::domain* dom = new box_domain(my_domain_rank, comm->nboxes(), boxes, g_boxindex_to_rank.data());

      int count = comm->size();
      if (debug_ > 0)
        std::cerr << "boxml: rank " << rank_ << " starting allreduce " << ev->id() << " for box " << box_number << "\n";
      sumi::comm_allreduce<double,sumi::Add>(NULL, NULL, count, index,
                                 false, sumi::options::initial_context, dom);
    }
    return n_allreduce > 0;
  }

  bool boxml::compute_boxes(int& n_events) {
      SSTMACBacktrace("compute boxes");
      da_list_t& v_comps(g_rank_to_valid_comps[rank_]);
      set_t& my_comps(g_rank_to_comps[rank_]);
      int n_comp = v_comps.size();

      if (n_comp) {
        if (randomize_events_)
          std::random_shuffle(v_comps.begin(), v_comps.end());

        comp_t* compptr = static_cast<comp_t*>(g_events[v_comps.front()]);
        comp_t& comp = *compptr;
        if (comp.n_dep() == 0) { // Abundance of caution
          if (do_compute_) {
            compute( timestamp( compute_scale_ * comp.time() ));
          }
          if (debug_ > 0) {
            cout << "boxml: rank " << rank_ << ": all deps satisfied, performing compute "
                 << comp.id() << " on " << rank_ << "\n";
          }
          my_comps.erase(comp.index());
          v_comps.pop_front();
          simple_event_done(comp.index());
          n_events -= 1; //I only do one compute at a time
        }
        else {
          spkt_throw_printf(sprockit::value_error,
            "valid compute event %d still has %d deps",
            comp.index(), comp.n_dep());
        }
      }

      n_comp = min(n_comp,1);
      int old_n_events = n_events;
      // events aren't properly tracked anymore
      if (0) {
        cout << "Rank " << rank_ << " completed " << n_comp <<  " computes\n";
        if (n_comp) {
          int temp_n = count_events();
          if (temp_n != n_events) {
            std::cerr << "compute_boxes: n_events doesn't match count_events()\n";
            abort();
          }
          cout << "Rank " << rank_ << " after compute processing, "
               << " continuing while loop with " << n_events
               << " events remaining (delta=" << n_events - old_n_events
               << ")\n";
        }
      }
      if (n_comp > 0)
        return true;
      return false;
  }

  void boxml::recv_boxes(int& n_events)
  {
      SSTMACBacktrace("recv boxes");
      sumi::message::ptr dmess = sumi::comm_poll();
      switch (dmess->class_type()){
        case sumi::message::pt2pt:
        {
          if (debug_ > 0)
            std::cerr << "boxml: rank " << rank_ << " receiving pt2pt message\n";
          pt2pt_message::ptr pmess = ptr_safe_cast(pt2pt_message, dmess);
          simple_event_done(pmess->event_index());
          break;
        }
        case sumi::message::collective_done:
        {
          sumi::collective_done_message::ptr cmess = ptr_safe_cast(sumi::collective_done_message, dmess);
          box_domain* dom = static_cast<box_domain*>(cmess->dom());
          int my_box_number = dom->my_box_number();
          if (debug_ > 0)
            std::cerr << "boxml: rank " << rank_ << " receiving collective_done message for " << cmess->tag() << "\n";
          collective_done(my_box_number, cmess->tag());
          //for now, we dynamically create domains - delete it
          delete dom;
          break;
        }
        default:
        {
          spkt_throw_printf(sprockit::value_error,
            "got invalid message type %s",
            sumi::message::tostr(dmess->class_type()));
        }
      }

      int old_n_events = n_events;
      --n_events;
      // events aren't properly tracked anymore
      if (0) {
        cout << "Rank " << rank_ << " handled receive\n";
        int temp_n = count_events();
        if (temp_n != n_events) {
          std::cerr << "recv_boxes: n_events " << n_events << " doesn't match count_events() "
                    << temp_n << "\n";
          abort();
        }
        cout << "Rank " << rank_ << " after recv processing, "
             << " continuing while loop with " << n_events
             << " events remaining (delta=" << n_events - old_n_events
             << ")\n";
      }
  }

  void boxml::run_loop() {
    SSTMACBacktrace("run loop");

    //std::cerr << "Rank 0 entering run loop with "
    //          << g_rank_to_recvs[0].size() << " recvs\n";
    if (debug_ > 0) cout << "Rank " << rank_ << " entering run loop with "
                         << g_rank_to_recvs[rank_].size() << " recvs\n";

    // Loop until no elements left
    int total_events = count_events();
    int n_events = total_events;
    int q_events = total_events/4;
    bool q1 = false, q2 = false, q3 = false;
    while (n_events > 0) {
    bool doloop = true;
    //while (doloop) {

      if (debug_ > 0 || detailed_progress_ ) {
        if (n_events < 3 * q_events && q1 == false) {
          cout << "Rank " << rank_ << " 25% complete\n";
          q1 = true;
        }
        if (n_events < 2 * q_events && q2 == false) {
          cout << "Rank " << rank_ << " 50% complete\n";
          q2 = true;
        }
        if (n_events < q_events && q3 == false) {
          cout << "Rank " << rank_ << " 75% complete\n";
          q3 = true;
        }
      }
      else if (rank_ == 0) {
        if (n_events < 3 * q_events && q1 == false) {
          cout << "Rank 0 25% complete\n";
          q1 = true;
        }
        if (n_events < 2 * q_events && q2 == false) {
          cout << "Rank 0 50% complete\n";
          q2 = true;
        }
        if (n_events < q_events && q3 == false) {
          cout << "Rank 0 75% complete\n";
          q3 = true;
        }
      }

      if(detailed_progress_ && rank_ == 0) {
        cout << "Rank 0 completed " << total_events - n_events << " of " << total_events
             << " events\n";
        cout << std::flush;
        cerr << std::flush;
      }

      //std::cerr << "Rank before send boxes with "
      //          << g_rank_to_recvs[0].size() << " recvs\n";

      bool skip_to_next_loop = send_boxes(n_events);
      if (skip_to_next_loop)
        continue;

      //std::cerr << "Rank before compute boxes with "
      //          << g_rank_to_recvs[0].size() << " recvs\n";

      skip_to_next_loop = compute_boxes(n_events);
      if (skip_to_next_loop)
        continue;

      //std::cerr << "Rank before reduce with "
      //          << g_rank_to_recvs[0].size() << " recvs\n";

      skip_to_next_loop = reduce(n_events);
      if (skip_to_next_loop)
        continue;

      //std::cerr << "Rank before recv with "
      //          << g_rank_to_recvs[0].size() << " recvs\n";

      recv_boxes(n_events);

      //if( n_events == count_events())
      //  sstmac_usleep(1000);

      doloop = false;
    }

    if (debug_ > 0)
      cout << "Rank " << rank_ << " completed run loop\n";

  }

}
<|endoftext|>


<commit_before>#include "../../../shared/SystemImplBase.h"

#include "common/RhoConf.h"
#include "logging/RhoLog.h"
#include "../../platform/shared/qt/rhodes/impl/MainWindowImpl.h"
#include "../../platform/shared/qt/rhodes/RhoSimulator.h"

#undef null
#include <qwebkitglobal.h>
#include <QLocale>
#include <QDesktopServices>
#include <QUrl>

#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "System"

namespace rho {

using namespace apiGenerator;

class CSystemImpl: public CSystemImplBase
{
public:
    CSystemImpl(): CSystemImplBase(){}

    virtual void getScreenWidth(CMethodResult& oResult);
    virtual void getScreenHeight(CMethodResult& oResult);
    virtual void getScreenOrientation(CMethodResult& oResult);
    virtual void getPpiX(CMethodResult& oResult);
    virtual void getPpiY(CMethodResult& oResult);
    virtual void getPhoneId(CMethodResult& oResult);
    virtual void getDeviceName(CMethodResult& oResult);
    virtual void getOsVersion(CMethodResult& oResult);
    virtual void getIsMotorolaDevice(CMethodResult& oResult);
    virtual void getLocale(CMethodResult& oResult);
    virtual void getCountry(CMethodResult& oResult);
    virtual void getIsEmulator(CMethodResult& oResult);
    virtual void getHasCalendar(CMethodResult& oResult);
    virtual void getOemInfo(CMethodResult& oResult);
    virtual void getUuid(CMethodResult& oResult);
    virtual void getHttpProxyURI(CMethodResult& oResult);
    virtual void setHttpProxyURI( const rho::String& value, CMethodResult& oResult);
    virtual void getLockWindowSize(CMethodResult& oResult);
    virtual void setLockWindowSize( bool value, CMethodResult& oResult);
    virtual void getKeyboardState(CMethodResult& oResult);
    virtual void setKeyboardState( const rho::String& value, CMethodResult& oResult);
    virtual void getFullScreen(CMethodResult& oResult);
    virtual void setFullScreen( bool value, CMethodResult& oResult);
    virtual void getScreenAutoRotate(CMethodResult& oResult);
    virtual void setScreenAutoRotate( bool value, CMethodResult& oResult);
    virtual void getHasTouchscreen(rho::apiGenerator::CMethodResult& oResult);
    virtual void getScreenSleeping(rho::apiGenerator::CMethodResult& oResult);
    virtual void setScreenSleeping( bool value, rho::apiGenerator::CMethodResult& oResult);

    virtual void applicationInstall( const rho::String& applicationUrl, CMethodResult& oResult);
    virtual void isApplicationInstalled( const rho::String& applicationName, CMethodResult& oResult);
    virtual void applicationUninstall( const rho::String& applicationName, CMethodResult& oResult);
    virtual void openUrl( const rho::String& url, CMethodResult& oResult);
    virtual void setRegistrySetting( int hive,  int type,  const rho::String& subKey,  const rho::String& setting,  const rho::String& value, rho::apiGenerator::CMethodResult& oResult);
    virtual void getRegistrySetting( int hive,  const rho::String& subKey,  const rho::String& setting, rho::apiGenerator::CMethodResult& oResult);
    virtual void setWindowFrame( int x,  int y,  int width,  int height, CMethodResult& oResult);
    virtual void setWindowPosition( int x,  int y, CMethodResult& oResult);
    virtual void setWindowSize( int width,  int height, rho::apiGenerator::CMethodResult& oResult);
    virtual void getWebviewFramework(rho::apiGenerator::CMethodResult& oResult);
    virtual void bringToFront(rho::apiGenerator::CMethodResult& oResult);
    virtual void runApplication( const rho::String& appName,  const rho::String& params,  bool blockingCall, rho::apiGenerator::CMethodResult& oResult);

    virtual void set_http_proxy_url( const rho::String& proxyURI, rho::apiGenerator::CMethodResult& oResult);
    virtual void unset_http_proxy(rho::apiGenerator::CMethodResult& oResult);
};

void CSystemImpl::getOsVersion(CMethodResult& oResult)
{
    oResult.set(String(RHOSIMULATOR_NAME " v" RHOSIMULATOR_VERSION));
}

void CSystemImpl::getIsEmulator(CMethodResult& oResult)
{
    oResult.set(true);
}

void CSystemImpl::getScreenWidth(CMethodResult& oResult)
{
    oResult.set(CMainWindow::getScreenWidth());
}

void CSystemImpl::getScreenHeight(CMethodResult& oResult)
{
    oResult.set(CMainWindow::getScreenHeight());
}

void CSystemImpl::getScreenOrientation(CMethodResult& oResult)
{
    oResult.set(StringW(CMainWindow::getScreenWidth() <= CMainWindow::getScreenHeight() ? L"portrait" : L"landscape"));
}

void CSystemImpl::getPpiX(CMethodResult& oResult)
{
    oResult.set(CMainWindow::getInstance()->getLogicalDpiX());
}

void CSystemImpl::getPpiY(CMethodResult& oResult)
{
    oResult.set(CMainWindow::getInstance()->getLogicalDpiY());
}

void CSystemImpl::getPhoneId(CMethodResult& oResult)
{
    //oResult.set(...);
    getOsVersion(oResult);
}

void CSystemImpl::getDeviceName(CMethodResult& oResult)
{
    oResult.set(String("Qt"));
}

void CSystemImpl::getLocale(CMethodResult& oResult)
{
    oResult.set(String(QLocale::system().name().left(2).toStdString().c_str()));
}

void CSystemImpl::getCountry(CMethodResult& oResult)
{
    oResult.set(String(QLocale::system().name().right(2).toStdString().c_str()));
}

void CSystemImpl::getHasCalendar(CMethodResult& oResult)
{
	oResult.set(true);
}

void CSystemImpl::getIsMotorolaDevice(CMethodResult& oResult)
{
	oResult.set(false);
}

void CSystemImpl::getOemInfo(CMethodResult& oResult)
{
    //oResult.set(...);
}

void CSystemImpl::getUuid(CMethodResult& oResult)
{
    //oResult.set(...);
}

void CSystemImpl::getLockWindowSize(CMethodResult& oResult){}
void CSystemImpl::setLockWindowSize( bool value, CMethodResult& oResult){}
//void CSystemImpl::getKeyboardState(CMethodResult& oResult){}
//void CSystemImpl::setKeyboardState( const rho::String& value, CMethodResult& oResult){}
void CSystemImpl::getFullScreen(CMethodResult& oResult)
{
	//all apps working in full screen mode on WP8
    oResult.set(CMainWindow::getInstance()->getFullScreen());
}
void CSystemImpl::setFullScreen(bool value, CMethodResult& oResult)
{
    CMainWindow::getInstance()->fullscreenCommand(value);
}

void CSystemImpl::getScreenAutoRotate(CMethodResult& oResult)
{
    oResult.set(false);
}

void CSystemImpl::setScreenAutoRotate( bool value, CMethodResult& oResult)
{
    // TODO: impolement auto rotate
}

void CSystemImpl::applicationInstall( const rho::String& applicationUrl, CMethodResult& oResult)
{
}

void CSystemImpl::isApplicationInstalled( const rho::String& applicationName, CMethodResult& oResult)
{
	oResult.set(false);
}

void CSystemImpl::applicationUninstall( const rho::String& applicationName, CMethodResult& oResult)
{
}

void CSystemImpl::openUrl( const rho::String& url, CMethodResult& oResult)
{
    QString sUrl = QString::fromStdString(url);
    if (sUrl.startsWith("/"))
        sUrl.prepend("file://");
    QDesktopServices::openUrl(QUrl(sUrl));
}

void CSystemImpl::runApplication( const rho::String& appName,  const rho::String& params,  bool blockingCall, CMethodResult& oResult)
{
    //unsupported
}

void CSystemImpl::setRegistrySetting( int hive,  int type,  const rho::String& subKey,  const rho::String& setting,  const rho::String& value, rho::apiGenerator::CMethodResult& oResult)
{
	//unsupported
}

void CSystemImpl::getRegistrySetting( int hive,  const rho::String& subKey,  const rho::String& setting, rho::apiGenerator::CMethodResult& oResult)
{
	//unsupported
}

void CSystemImpl::setWindowFrame(int x,  int y,  int width,  int height, CMethodResult& oResult)
{
    CMainWindow::getInstance()->setFrame(x, y, width, height);
}
void CSystemImpl::setWindowPosition( int x,  int y, CMethodResult& oResult)
{
    CMainWindow::getInstance()->setPosition(x, y);
}

void CSystemImpl::getWebviewFramework(rho::apiGenerator::CMethodResult& oResult)
{
    oResult.set(String("WEBKIT/" QTWEBKIT_VERSION_STR));
}

void CSystemImpl::bringToFront(rho::apiGenerator::CMethodResult& oResult)
{
    CMainWindow::getInstance()->bringToFront();
}

extern "C" const char* rho_sys_get_http_proxy_url();
extern "C" void rho_sys_set_http_proxy_url(const char* url);
extern "C" void rho_sys_unset_http_proxy();
void CSystemImpl::getHttpProxyURI(CMethodResult& oResult)
{
	oResult.set(rho_sys_get_http_proxy_url());
}

void CSystemImpl::setHttpProxyURI( const rho::String& value, CMethodResult& oResult)
{
	if ( value.length() )
        rho_sys_set_http_proxy_url( value.c_str() );
    else
        rho_sys_unset_http_proxy();
}

void CSystemImpl::getHasTouchscreen(rho::apiGenerator::CMethodResult& oResult)
{
	oResult.set(true);
}

void CSystemImpl::getScreenSleeping(rho::apiGenerator::CMethodResult& oResult)
{
    oResult.set(false);
}

void CSystemImpl::setScreenSleeping( bool value, rho::apiGenerator::CMethodResult& oResult)
{
    //unsupported
}

void CSystemImpl::setWindowSize( int width,  int height, rho::apiGenerator::CMethodResult& oResult)
{
    CMainWindow::getInstance()->setSize(width, height);
}

void CSystemImpl::set_http_proxy_url( const rho::String& proxyURI, rho::apiGenerator::CMethodResult& oResult)
{
	rho_sys_set_http_proxy_url( proxyURI.c_str() );
}

void CSystemImpl::unset_http_proxy(rho::apiGenerator::CMethodResult& oResult)
{
	rho_sys_unset_http_proxy();
}

////////////////////////////////////////////////////////////////////////
class CSystemSingleton: public CModuleSingletonBase<ISystemSingleton>
{
public:
    ~CSystemSingleton(){}
    rho::StringW getInitialDefaultID(){return L"1";}
	rho::StringW getDefaultID(){return L"1";}
	void setDefaultID(const rho::StringW& strI){}
};

class CSystemFactory: public CSystemFactoryBase
{
public:
    ~CSystemFactory(){}

    ISystemSingleton* createModuleSingleton(){ return new CSystemImpl(); }
};

extern "C" void Init_System()
{
    CSystemFactory::setInstance( new CSystemFactory() );
    Init_System_API();
}

}
<commit_msg>rhosimulator/osx: build fixed<commit_after>#include "../../../shared/SystemImplBase.h"

#include "common/RhoConf.h"
#include "logging/RhoLog.h"
#include "../../platform/shared/qt/rhodes/impl/MainWindowImpl.h"
#include "../../platform/shared/qt/rhodes/RhoSimulator.h"

#undef null
#include <qwebkitglobal.h>
#include <QLocale>
#include <QDesktopServices>
#include <QUrl>

#undef DEFAULT_LOGCATEGORY
#define DEFAULT_LOGCATEGORY "System"

namespace rho {

using namespace apiGenerator;

class CSystemImpl: public CSystemImplBase
{
public:
    CSystemImpl(): CSystemImplBase(){}

    virtual void getScreenWidth(CMethodResult& oResult);
    virtual void getScreenHeight(CMethodResult& oResult);
    virtual void getScreenOrientation(CMethodResult& oResult);
    virtual void getPpiX(CMethodResult& oResult);
    virtual void getPpiY(CMethodResult& oResult);
    virtual void getPhoneId(CMethodResult& oResult);
    virtual void getDeviceName(CMethodResult& oResult);
    virtual void getOsVersion(CMethodResult& oResult);
    virtual void getIsMotorolaDevice(CMethodResult& oResult);
    virtual void getLocale(CMethodResult& oResult);
    virtual void getCountry(CMethodResult& oResult);
    virtual void getIsEmulator(CMethodResult& oResult);
    virtual void getHasCalendar(CMethodResult& oResult);
    virtual void getOemInfo(CMethodResult& oResult);
    virtual void getUuid(CMethodResult& oResult);
    virtual void getHttpProxyURI(CMethodResult& oResult);
    virtual void setHttpProxyURI( const rho::String& value, CMethodResult& oResult);
    virtual void getLockWindowSize(CMethodResult& oResult);
    virtual void setLockWindowSize( bool value, CMethodResult& oResult);
    //virtual void getKeyboardState(CMethodResult& oResult);
    //virtual void setKeyboardState( const rho::String& value, CMethodResult& oResult);
    virtual void getFullScreen(CMethodResult& oResult);
    virtual void setFullScreen( bool value, CMethodResult& oResult);
    virtual void getScreenAutoRotate(CMethodResult& oResult);
    virtual void setScreenAutoRotate( bool value, CMethodResult& oResult);
    virtual void getHasTouchscreen(rho::apiGenerator::CMethodResult& oResult);
    virtual void getScreenSleeping(rho::apiGenerator::CMethodResult& oResult);
    virtual void setScreenSleeping( bool value, rho::apiGenerator::CMethodResult& oResult);

    virtual void applicationInstall( const rho::String& applicationUrl, CMethodResult& oResult);
    virtual void isApplicationInstalled( const rho::String& applicationName, CMethodResult& oResult);
    virtual void applicationUninstall( const rho::String& applicationName, CMethodResult& oResult);
    virtual void openUrl( const rho::String& url, CMethodResult& oResult);
    virtual void setRegistrySetting( int hive,  int type,  const rho::String& subKey,  const rho::String& setting,  const rho::String& value, rho::apiGenerator::CMethodResult& oResult);
    virtual void getRegistrySetting( int hive,  const rho::String& subKey,  const rho::String& setting, rho::apiGenerator::CMethodResult& oResult);
    virtual void setWindowFrame( int x,  int y,  int width,  int height, CMethodResult& oResult);
    virtual void setWindowPosition( int x,  int y, CMethodResult& oResult);
    virtual void setWindowSize( int width,  int height, rho::apiGenerator::CMethodResult& oResult);
    virtual void getWebviewFramework(rho::apiGenerator::CMethodResult& oResult);
    virtual void bringToFront(rho::apiGenerator::CMethodResult& oResult);
    virtual void runApplication( const rho::String& appName,  const rho::String& params,  bool blockingCall, rho::apiGenerator::CMethodResult& oResult);

    virtual void set_http_proxy_url( const rho::String& proxyURI, rho::apiGenerator::CMethodResult& oResult);
    virtual void unset_http_proxy(rho::apiGenerator::CMethodResult& oResult);
};

void CSystemImpl::getOsVersion(CMethodResult& oResult)
{
    oResult.set(String(RHOSIMULATOR_NAME " v" RHOSIMULATOR_VERSION));
}

void CSystemImpl::getIsEmulator(CMethodResult& oResult)
{
    oResult.set(true);
}

void CSystemImpl::getScreenWidth(CMethodResult& oResult)
{
    oResult.set(CMainWindow::getScreenWidth());
}

void CSystemImpl::getScreenHeight(CMethodResult& oResult)
{
    oResult.set(CMainWindow::getScreenHeight());
}

void CSystemImpl::getScreenOrientation(CMethodResult& oResult)
{
    oResult.set(StringW(CMainWindow::getScreenWidth() <= CMainWindow::getScreenHeight() ? L"portrait" : L"landscape"));
}

void CSystemImpl::getPpiX(CMethodResult& oResult)
{
    oResult.set(CMainWindow::getInstance()->getLogicalDpiX());
}

void CSystemImpl::getPpiY(CMethodResult& oResult)
{
    oResult.set(CMainWindow::getInstance()->getLogicalDpiY());
}

void CSystemImpl::getPhoneId(CMethodResult& oResult)
{
    //oResult.set(...);
    getOsVersion(oResult);
}

void CSystemImpl::getDeviceName(CMethodResult& oResult)
{
    oResult.set(String("Qt"));
}

void CSystemImpl::getLocale(CMethodResult& oResult)
{
    oResult.set(String(QLocale::system().name().left(2).toStdString().c_str()));
}

void CSystemImpl::getCountry(CMethodResult& oResult)
{
    oResult.set(String(QLocale::system().name().right(2).toStdString().c_str()));
}

void CSystemImpl::getHasCalendar(CMethodResult& oResult)
{
	oResult.set(true);
}

void CSystemImpl::getIsMotorolaDevice(CMethodResult& oResult)
{
	oResult.set(false);
}

void CSystemImpl::getOemInfo(CMethodResult& oResult)
{
    //oResult.set(...);
}

void CSystemImpl::getUuid(CMethodResult& oResult)
{
    //oResult.set(...);
}

void CSystemImpl::getLockWindowSize(CMethodResult& oResult){}
void CSystemImpl::setLockWindowSize( bool value, CMethodResult& oResult){}
//void CSystemImpl::getKeyboardState(CMethodResult& oResult){}
//void CSystemImpl::setKeyboardState( const rho::String& value, CMethodResult& oResult){}
void CSystemImpl::getFullScreen(CMethodResult& oResult)
{
	//all apps working in full screen mode on WP8
    oResult.set(CMainWindow::getInstance()->getFullScreen());
}
void CSystemImpl::setFullScreen(bool value, CMethodResult& oResult)
{
    CMainWindow::getInstance()->fullscreenCommand(value);
}

void CSystemImpl::getScreenAutoRotate(CMethodResult& oResult)
{
    oResult.set(false);
}

void CSystemImpl::setScreenAutoRotate( bool value, CMethodResult& oResult)
{
    // TODO: impolement auto rotate
}

void CSystemImpl::applicationInstall( const rho::String& applicationUrl, CMethodResult& oResult)
{
}

void CSystemImpl::isApplicationInstalled( const rho::String& applicationName, CMethodResult& oResult)
{
	oResult.set(false);
}

void CSystemImpl::applicationUninstall( const rho::String& applicationName, CMethodResult& oResult)
{
}

void CSystemImpl::openUrl( const rho::String& url, CMethodResult& oResult)
{
    QString sUrl = QString::fromStdString(url);
    if (sUrl.startsWith("/"))
        sUrl.prepend("file://");
    QDesktopServices::openUrl(QUrl(sUrl));
}

void CSystemImpl::runApplication( const rho::String& appName,  const rho::String& params,  bool blockingCall, CMethodResult& oResult)
{
    //unsupported
}

void CSystemImpl::setRegistrySetting( int hive,  int type,  const rho::String& subKey,  const rho::String& setting,  const rho::String& value, rho::apiGenerator::CMethodResult& oResult)
{
	//unsupported
}

void CSystemImpl::getRegistrySetting( int hive,  const rho::String& subKey,  const rho::String& setting, rho::apiGenerator::CMethodResult& oResult)
{
	//unsupported
}

void CSystemImpl::setWindowFrame(int x,  int y,  int width,  int height, CMethodResult& oResult)
{
    CMainWindow::getInstance()->setFrame(x, y, width, height);
}
void CSystemImpl::setWindowPosition( int x,  int y, CMethodResult& oResult)
{
    CMainWindow::getInstance()->setPosition(x, y);
}

void CSystemImpl::getWebviewFramework(rho::apiGenerator::CMethodResult& oResult)
{
    oResult.set(String("WEBKIT/" QTWEBKIT_VERSION_STR));
}

void CSystemImpl::bringToFront(rho::apiGenerator::CMethodResult& oResult)
{
    CMainWindow::getInstance()->bringToFront();
}

extern "C" const char* rho_sys_get_http_proxy_url();
extern "C" void rho_sys_set_http_proxy_url(const char* url);
extern "C" void rho_sys_unset_http_proxy();
void CSystemImpl::getHttpProxyURI(CMethodResult& oResult)
{
	oResult.set(rho_sys_get_http_proxy_url());
}

void CSystemImpl::setHttpProxyURI( const rho::String& value, CMethodResult& oResult)
{
	if ( value.length() )
        rho_sys_set_http_proxy_url( value.c_str() );
    else
        rho_sys_unset_http_proxy();
}

void CSystemImpl::getHasTouchscreen(rho::apiGenerator::CMethodResult& oResult)
{
	oResult.set(true);
}

void CSystemImpl::getScreenSleeping(rho::apiGenerator::CMethodResult& oResult)
{
    oResult.set(false);
}

void CSystemImpl::setScreenSleeping( bool value, rho::apiGenerator::CMethodResult& oResult)
{
    //unsupported
}

void CSystemImpl::setWindowSize( int width,  int height, rho::apiGenerator::CMethodResult& oResult)
{
    CMainWindow::getInstance()->setSize(width, height);
}

void CSystemImpl::set_http_proxy_url( const rho::String& proxyURI, rho::apiGenerator::CMethodResult& oResult)
{
	rho_sys_set_http_proxy_url( proxyURI.c_str() );
}

void CSystemImpl::unset_http_proxy(rho::apiGenerator::CMethodResult& oResult)
{
	rho_sys_unset_http_proxy();
}

////////////////////////////////////////////////////////////////////////
class CSystemSingleton: public CModuleSingletonBase<ISystemSingleton>
{
public:
    ~CSystemSingleton(){}
    rho::StringW getInitialDefaultID(){return L"1";}
	rho::StringW getDefaultID(){return L"1";}
	void setDefaultID(const rho::StringW& strI){}
};

class CSystemFactory: public CSystemFactoryBase
{
public:
    ~CSystemFactory(){}

    ISystemSingleton* createModuleSingleton(){ return new CSystemImpl(); }
};

extern "C" void Init_System()
{
    CSystemFactory::setInstance( new CSystemFactory() );
    Init_System_API();
}

}
<|endoftext|>