<commit_before>/**
 * @file image.cpp
 *
 * @brief Purpose: Contains methods to images management
 *
 * MIT License
 * Copyright (c) 2017 MindScape
 *
 * https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md
 *
 */
#include "image.hpp"
#include <string>

using namespace engine;

/**
 * @brief Method Load
 *
 * Responsible for load the game images and create the texture
 *
 * @return void
 */
bool Image::load() {
    free();

    SDL_Texture* new_texture = NULL; /**< sdl texture new texture converted */
    SDL_Surface* loaded_surface = IMG_Load(image_path.c_str()); /**< surface loaded to be converted */

    if (loaded_surface != NULL) {
        /* if the loaded surface is null (didnt work properly) */
        new_texture = SDL_CreateTextureFromSurface(renderer, loaded_surface);

        if (new_texture == NULL) {
			/* if the texture is null */
            printf("Unable to create texture from %s! SDL Error: %s\n",
                   image_path.c_str(), SDL_GetError());
        }

        SDL_FreeSurface(loaded_surface);
    }
    else {
		/* if the surface loaded properly */
        printf("Unable to load image %s! Image error: %s\n",
               image_path.c_str(), IMG_GetError());
    }

	texture = nullptr;
	texture = new_texture;
	return texture != nullptr;
}

/**
 * @brief Free Method
 *
 * Method responsible for close the game
 *
 * @return void
 */
void Image::free() {
    if (texture != NULL) {
		/* if the texture didnt load properly */
        SDL_DestroyTexture(texture);

		texture = nullptr;

		dimension_on_screen.first = 0;
		dimension_on_screen.second = 0;
	}
}

/**
 * @brief Draw
 *
 * Draw the image on the screen
 *
 * @param x position in axis x on the screen
 * @param y position in axis y on the screen
 *
 * @return
 */
void Image::draw(int x, int y) {
    SDL_Rect ret = {coordinatesOnTexture.first,
                    coordinatesOnTexture.second,
                    dimensionOnTexture.first,
                    dimensionOnTexture.second}; /**< rectangle holding the images positions and dimensions */

    // This render_quad tells where the image will appear in the screen
    SDL_Rect render_quad = {x+get_displacement().first,
                            y+get_displacement().second, this->get_width(),
                            this->get_height()}; /**< on screen rendering rectangle */

	SDL_RenderCopy(renderer, texture, &ret, &render_quad);
}

/**
 * @brief Methods Set values
 *
 * Set the position and dimension of the texture on the screen
 *
 * @param _dimension_on_screen size in the screen of the texture
 * @param _dimension_on_texture size of the texture
 * @param _coordinates_on_texture coordinates in axis x,y
 */
void Image::set_values(std::pair<int, int> _dimension_on_screen,
					   std::pair<int, int> _dimension_on_texture,
					   std::pair<int, int> _coordinates_on_texture) {

	dimension_on_screen = _dimension_on_screen;
	dimensionOnTexture = _dimension_on_texture;
	coordinatesOnTexture = _coordinates_on_texture;
}

/**
 * @brief Get Width
 *
 * @return width dimension
 */
int Image::get_width() {
	return dimension_on_screen.first;
}

/**
 * @brief Get Height
 *
 * @return the height dimension
 */
int Image::get_height() {
	return dimension_on_screen.second;

}
<commit_msg>[LOGGING] Apply technique in image.cpp<commit_after>/**
 * @file image.cpp
 *
 * @brief Purpose: Contains methods to images management
 *
 * MIT License
 * Copyright (c) 2017 MindScape
 *
 * https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md
 *
 */
#include "image.hpp"
#include <string>
#include "log.hpp"

using namespace engine;

/**
 * @brief Method Load
 *
 * Responsible for load the game images and create the texture
 *
 * @return void
 */
bool Image::load() {
    DEBUG("Loading image");
    free();

    SDL_Texture* new_texture = NULL; /**< sdl texture new texture converted */
    SDL_Surface* loaded_surface = IMG_Load(image_path.c_str()); /**< surface loaded to be converted */

    if (loaded_surface != NULL) {
        /* if the loaded surface is null (didnt work properly) */
        new_texture = SDL_CreateTextureFromSurface(renderer, loaded_surface);

        if (new_texture == NULL) {
			/* if the texture is null */
            ERROR("Unable to create texture");
        }
        SDL_FreeSurface(loaded_surface);
    }
    else {
		/* if the surface loaded properly */
        ERROR("Unable to load image");
    }

	texture = nullptr;
	texture = new_texture;
	return texture != nullptr;
}

/**
 * @brief Free Method
 *
 * Method responsible for close the game
 *
 * @return void
 */
void Image::free() {
    DEBUG("Trying to free image");
    if (texture != NULL) {
        /* if the texture didnt load properly */
        ERROR("Image could not be freed");
        SDL_DestroyTexture(texture);

		texture = nullptr;

		dimension_on_screen.first = 0;
		dimension_on_screen.second = 0;
	}
}

/**
 * @brief Draw
 *
 * Draw the image on the screen
 *
 * @param x position in axis x on the screen
 * @param y position in axis y on the screen
 *
 * @return
 */
void Image::draw(int x, int y) {
    DEBUG("Drawing image");
    SDL_Rect ret = {coordinatesOnTexture.first,
                    coordinatesOnTexture.second,
                    dimensionOnTexture.first,
                    dimensionOnTexture.second}; /**< rectangle holding the images positions and dimensions */

    // This render_quad tells where the image will appear in the screen
    SDL_Rect render_quad = {x+get_displacement().first,
                            y+get_displacement().second, this->get_width(),
                            this->get_height()}; /**< on screen rendering rectangle */

	SDL_RenderCopy(renderer, texture, &ret, &render_quad);
}

/**
 * @brief Methods Set values
 *
 * Set the position and dimension of the texture on the screen
 *
 * @param _dimension_on_screen size in the screen of the texture
 * @param _dimension_on_texture size of the texture
 * @param _coordinates_on_texture coordinates in axis x,y
 */
void Image::set_values(std::pair<int, int> _dimension_on_screen,
					   std::pair<int, int> _dimension_on_texture,
					   std::pair<int, int> _coordinates_on_texture) {

	dimension_on_screen = _dimension_on_screen;
	dimensionOnTexture = _dimension_on_texture;
	coordinatesOnTexture = _coordinates_on_texture;
}

/**
 * @brief Get Width
 *
 * @return width dimension
 */
int Image::get_width() {
	return dimension_on_screen.first;
}

/**
 * @brief Get Height
 *
 * @return the height dimension
 */
int Image::get_height() {
	return dimension_on_screen.second;

}
<|endoftext|>


<commit_before>#pragma once

#include <nano/crypto/blake2/blake2.h>
#include <nano/lib/blockbuilders.hpp>
#include <nano/lib/blocks.hpp>
#include <nano/lib/config.hpp>
#include <nano/lib/numbers.hpp>
#include <nano/lib/utility.hpp>
#include <nano/secure/epoch.hpp>
#include <nano/secure/utility.hpp>

#include <boost/iterator/transform_iterator.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/variant.hpp>

#include <unordered_map>

namespace boost
{
template <>
struct hash<::nano::uint256_union>
{
	size_t operator() (::nano::uint256_union const & value_a) const
	{
		return std::hash<::nano::uint256_union> () (value_a);
	}
};

template <>
struct hash<::nano::block_hash>
{
	size_t operator() (::nano::block_hash const & value_a) const
	{
		return std::hash<::nano::block_hash> () (value_a);
	}
};

template <>
struct hash<::nano::public_key>
{
	size_t operator() (::nano::public_key const & value_a) const
	{
		return std::hash<::nano::public_key> () (value_a);
	}
};
template <>
struct hash<::nano::uint512_union>
{
	size_t operator() (::nano::uint512_union const & value_a) const
	{
		return std::hash<::nano::uint512_union> () (value_a);
	}
};
template <>
struct hash<::nano::qualified_root>
{
	size_t operator() (::nano::qualified_root const & value_a) const
	{
		return std::hash<::nano::qualified_root> () (value_a);
	}
};
}
namespace nano
{
/**
 * A key pair. The private key is generated from the random pool, or passed in
 * as a hex string. The public key is derived using ed25519.
 */
class keypair
{
public:
	keypair ();
	keypair (std::string const &);
	keypair (nano::raw_key &&);
	nano::public_key pub;
	nano::raw_key prv;
};

/**
 * Latest information about an account
 */
class account_info final
{
public:
	account_info () = default;
	account_info (nano::block_hash const &, nano::account const &, nano::block_hash const &, nano::amount const &, uint64_t, uint64_t, epoch);
	bool deserialize (nano::stream &);
	bool operator== (nano::account_info const &) const;
	bool operator!= (nano::account_info const &) const;
	size_t db_size () const;
	nano::epoch epoch () const;
	nano::block_hash head{ 0 };
	nano::account representative{ 0 };
	nano::block_hash open_block{ 0 };
	nano::amount balance{ 0 };
	/** Seconds since posix epoch */
	uint64_t modified{ 0 };
	uint64_t block_count{ 0 };
	nano::epoch epoch_m{ nano::epoch::epoch_0 };
};

/**
 * Information on an uncollected send
 */
class pending_info final
{
public:
	pending_info () = default;
	pending_info (nano::account const &, nano::amount const &, nano::epoch);
	size_t db_size () const;
	bool deserialize (nano::stream &);
	bool operator== (nano::pending_info const &) const;
	nano::account source{ 0 };
	nano::amount amount{ 0 };
	nano::epoch epoch{ nano::epoch::epoch_0 };
};
class pending_key final
{
public:
	pending_key () = default;
	pending_key (nano::account const &, nano::block_hash const &);
	bool deserialize (nano::stream &);
	bool operator== (nano::pending_key const &) const;
	nano::account const & key () const;
	nano::account account{ 0 };
	nano::block_hash hash{ 0 };
};

class endpoint_key final
{
public:
	endpoint_key () = default;

	/*
	 * @param address_a This should be in network byte order
	 * @param port_a This should be in host byte order
	 */
	endpoint_key (const std::array<uint8_t, 16> & address_a, uint16_t port_a);

	/*
	 * @return The ipv6 address in network byte order
	 */
	const std::array<uint8_t, 16> & address_bytes () const;

	/*
	 * @return The port in host byte order
	 */
	uint16_t port () const;

private:
	// Both stored internally in network byte order
	std::array<uint8_t, 16> address;
	uint16_t network_port{ 0 };
};

enum class no_value
{
	dummy
};

class unchecked_key final
{
public:
	unchecked_key () = default;
	unchecked_key (nano::block_hash const &, nano::block_hash const &);
	bool deserialize (nano::stream &);
	bool operator== (nano::unchecked_key const &) const;
	nano::block_hash const & key () const;
	nano::block_hash previous{ 0 };
	nano::block_hash hash{ 0 };
};

/**
 * Tag for block signature verification result
 */
enum class signature_verification : uint8_t
{
	unknown = 0,
	invalid = 1,
	valid = 2,
	valid_epoch = 3 // Valid for epoch blocks
};

/**
 * Information on an unchecked block
 */
class unchecked_info final
{
public:
	unchecked_info () = default;
	unchecked_info (std::shared_ptr<nano::block>, nano::account const &, uint64_t, nano::signature_verification = nano::signature_verification::unknown, bool = false);
	void serialize (nano::stream &) const;
	bool deserialize (nano::stream &);
	std::shared_ptr<nano::block> block;
	nano::account account{ 0 };
	/** Seconds since posix epoch */
	uint64_t modified{ 0 };
	nano::signature_verification verified{ nano::signature_verification::unknown };
	bool confirmed{ false };
};

class block_info final
{
public:
	block_info () = default;
	block_info (nano::account const &, nano::amount const &);
	nano::account account{ 0 };
	nano::amount balance{ 0 };
};
class block_counts final
{
public:
	size_t sum () const;
	size_t send{ 0 };
	size_t receive{ 0 };
	size_t open{ 0 };
	size_t change{ 0 };
	size_t state{ 0 };
};
using vote_blocks_vec_iter = std::vector<boost::variant<std::shared_ptr<nano::block>, nano::block_hash>>::const_iterator;
class iterate_vote_blocks_as_hash final
{
public:
	iterate_vote_blocks_as_hash () = default;
	nano::block_hash operator() (boost::variant<std::shared_ptr<nano::block>, nano::block_hash> const & item) const;
};
class vote final
{
public:
	vote () = default;
	vote (nano::vote const &);
	vote (bool &, nano::stream &, nano::block_uniquer * = nullptr);
	vote (bool &, nano::stream &, nano::block_type, nano::block_uniquer * = nullptr);
	vote (nano::account const &, nano::raw_key const &, uint64_t, std::shared_ptr<nano::block>);
	vote (nano::account const &, nano::raw_key const &, uint64_t, std::vector<nano::block_hash> const &);
	std::string hashes_string () const;
	nano::block_hash hash () const;
	nano::block_hash full_hash () const;
	bool operator== (nano::vote const &) const;
	bool operator!= (nano::vote const &) const;
	void serialize (nano::stream &, nano::block_type) const;
	void serialize (nano::stream &) const;
	void serialize_json (boost::property_tree::ptree & tree) const;
	bool deserialize (nano::stream &, nano::block_uniquer * = nullptr);
	bool validate () const;
	boost::transform_iterator<nano::iterate_vote_blocks_as_hash, nano::vote_blocks_vec_iter> begin () const;
	boost::transform_iterator<nano::iterate_vote_blocks_as_hash, nano::vote_blocks_vec_iter> end () const;
	std::string to_json () const;
	// Vote round sequence number
	uint64_t sequence;
	// The blocks, or block hashes, that this vote is for
	std::vector<boost::variant<std::shared_ptr<nano::block>, nano::block_hash>> blocks;
	// Account that's voting
	nano::account account;
	// Signature of sequence + block hashes
	nano::signature signature;
	static const std::string hash_prefix;
};
/**
 * This class serves to find and return unique variants of a vote in order to minimize memory usage
 */
class vote_uniquer final
{
public:
	using value_type = std::pair<const nano::block_hash, std::weak_ptr<nano::vote>>;

	vote_uniquer (nano::block_uniquer &);
	std::shared_ptr<nano::vote> unique (std::shared_ptr<nano::vote>);
	size_t size ();

private:
	nano::block_uniquer & uniquer;
	std::mutex mutex;
	std::unordered_map<std::remove_const_t<value_type::first_type>, value_type::second_type> votes;
	static unsigned constexpr cleanup_count = 2;
};

std::unique_ptr<seq_con_info_component> collect_seq_con_info (vote_uniquer & vote_uniquer, const std::string & name);

enum class vote_code
{
	invalid, // Vote is not signed correctly
	replay, // Vote does not have the highest sequence number, it's a replay
	vote // Vote has the highest sequence number
};

enum class process_result
{
	progress, // Hasn't been seen before, signed correctly
	bad_signature, // Signature was bad, forged or transmission error
	old, // Already seen and was valid
	negative_spend, // Malicious attempt to spend a negative amount
	fork, // Malicious fork based on previous
	unreceivable, // Source block doesn't exist, has already been received, or requires an account upgrade (epoch blocks)
	gap_previous, // Block marked as previous is unknown
	gap_source, // Block marked as source is unknown
	opened_burn_account, // The impossible happened, someone found the private key associated with the public key '0'.
	balance_mismatch, // Balance and amount delta don't match
	representative_mismatch, // Representative is changed when it is not allowed
	block_position // This block cannot follow the previous block
};
class process_return final
{
public:
	nano::process_result code;
	nano::account account;
	nano::amount amount;
	nano::account pending_account;
	boost::optional<bool> state_is_send;
	nano::signature_verification verified;
};
enum class tally_result
{
	vote,
	changed,
	confirm
};

class genesis final
{
public:
	genesis ();
	nano::block_hash hash () const;
	std::shared_ptr<nano::block> open;
};

class network_params;

/** Protocol versions whose value may depend on the active network */
class protocol_constants
{
public:
	protocol_constants (nano::nano_networks network_a);

	/** Current protocol version */
	uint8_t protocol_version = 0x11;

	/** Minimum accepted protocol version */
	uint8_t protocol_version_min = 0x0d;

	/** Do not bootstrap from nodes older than this version. */
	uint8_t protocol_version_bootstrap_min = 0x0d;

	/** Do not lazy bootstrap from nodes older than this version. */
	uint8_t protocol_version_bootstrap_lazy_min = 0x10;

	/** Do not start TCP realtime network connections to nodes older than this version */
	uint8_t tcp_realtime_protocol_version_min = 0x11;
};

/** Genesis keys and ledger constants for network variants */
class ledger_constants
{
public:
	ledger_constants (nano::network_constants & network_constants);
	ledger_constants (nano::nano_networks network_a);
	nano::keypair zero_key;
	nano::keypair test_genesis_key;
	nano::account nano_test_account;
	nano::account nano_beta_account;
	nano::account nano_live_account;
	std::string nano_test_genesis;
	std::string nano_beta_genesis;
	std::string nano_live_genesis;
	nano::account genesis_account;
	std::string genesis_block;
	nano::uint128_t genesis_amount;
	nano::account burn_account;
	nano::epochs epochs;
};

/** Constants which depend on random values (this class should never be used globally due to CryptoPP globals potentially not being initialized) */
class random_constants
{
public:
	random_constants ();
	nano::account not_an_account;
	nano::uint128_union random_128;
};

/** Node related constants whose value depends on the active network */
class node_constants
{
public:
	node_constants (nano::network_constants & network_constants);
	std::chrono::seconds period;
	std::chrono::milliseconds half_period;
	/** Default maximum idle time for a socket before it's automatically closed */
	std::chrono::seconds idle_timeout;
	std::chrono::seconds cutoff;
	std::chrono::seconds syn_cookie_cutoff;
	std::chrono::minutes backup_interval;
	std::chrono::seconds search_pending_interval;
	std::chrono::seconds peer_interval;
	std::chrono::minutes unchecked_cleaning_interval;
	std::chrono::milliseconds process_confirmed_interval;

	/** The maximum amount of samples for a 2 week period on live or 3 days on beta */
	uint64_t max_weight_samples;
	uint64_t weight_period;
};

/** Voting related constants whose value depends on the active network */
class voting_constants
{
public:
	voting_constants (nano::network_constants & network_constants);
	size_t max_cache;
};

/** Port-mapping related constants whose value depends on the active network */
class portmapping_constants
{
public:
	portmapping_constants (nano::network_constants & network_constants);
	// Timeouts are primes so they infrequently happen at the same time
	int mapping_timeout;
	int check_timeout;
};

/** Bootstrap related constants whose value depends on the active network */
class bootstrap_constants
{
public:
	bootstrap_constants (nano::network_constants & network_constants);
	uint64_t lazy_max_pull_blocks;
};

/** Constants whose value depends on the active network */
class network_params
{
public:
	/** Populate values based on the current active network */
	network_params ();

	/** Populate values based on \p network_a */
	network_params (nano::nano_networks network_a);

	std::array<uint8_t, 2> header_magic_number;
	unsigned kdf_work;
	network_constants network;
	protocol_constants protocol;
	ledger_constants ledger;
	random_constants random;
	voting_constants voting;
	node_constants node;
	portmapping_constants portmapping;
	bootstrap_constants bootstrap;
};

nano::wallet_id random_wallet_id ();
}
<commit_msg>move min bootstrap and traffic to v16 (#2363)<commit_after>#pragma once

#include <nano/crypto/blake2/blake2.h>
#include <nano/lib/blockbuilders.hpp>
#include <nano/lib/blocks.hpp>
#include <nano/lib/config.hpp>
#include <nano/lib/numbers.hpp>
#include <nano/lib/utility.hpp>
#include <nano/secure/epoch.hpp>
#include <nano/secure/utility.hpp>

#include <boost/iterator/transform_iterator.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/variant.hpp>

#include <unordered_map>

namespace boost
{
template <>
struct hash<::nano::uint256_union>
{
	size_t operator() (::nano::uint256_union const & value_a) const
	{
		return std::hash<::nano::uint256_union> () (value_a);
	}
};

template <>
struct hash<::nano::block_hash>
{
	size_t operator() (::nano::block_hash const & value_a) const
	{
		return std::hash<::nano::block_hash> () (value_a);
	}
};

template <>
struct hash<::nano::public_key>
{
	size_t operator() (::nano::public_key const & value_a) const
	{
		return std::hash<::nano::public_key> () (value_a);
	}
};
template <>
struct hash<::nano::uint512_union>
{
	size_t operator() (::nano::uint512_union const & value_a) const
	{
		return std::hash<::nano::uint512_union> () (value_a);
	}
};
template <>
struct hash<::nano::qualified_root>
{
	size_t operator() (::nano::qualified_root const & value_a) const
	{
		return std::hash<::nano::qualified_root> () (value_a);
	}
};
}
namespace nano
{
/**
 * A key pair. The private key is generated from the random pool, or passed in
 * as a hex string. The public key is derived using ed25519.
 */
class keypair
{
public:
	keypair ();
	keypair (std::string const &);
	keypair (nano::raw_key &&);
	nano::public_key pub;
	nano::raw_key prv;
};

/**
 * Latest information about an account
 */
class account_info final
{
public:
	account_info () = default;
	account_info (nano::block_hash const &, nano::account const &, nano::block_hash const &, nano::amount const &, uint64_t, uint64_t, epoch);
	bool deserialize (nano::stream &);
	bool operator== (nano::account_info const &) const;
	bool operator!= (nano::account_info const &) const;
	size_t db_size () const;
	nano::epoch epoch () const;
	nano::block_hash head{ 0 };
	nano::account representative{ 0 };
	nano::block_hash open_block{ 0 };
	nano::amount balance{ 0 };
	/** Seconds since posix epoch */
	uint64_t modified{ 0 };
	uint64_t block_count{ 0 };
	nano::epoch epoch_m{ nano::epoch::epoch_0 };
};

/**
 * Information on an uncollected send
 */
class pending_info final
{
public:
	pending_info () = default;
	pending_info (nano::account const &, nano::amount const &, nano::epoch);
	size_t db_size () const;
	bool deserialize (nano::stream &);
	bool operator== (nano::pending_info const &) const;
	nano::account source{ 0 };
	nano::amount amount{ 0 };
	nano::epoch epoch{ nano::epoch::epoch_0 };
};
class pending_key final
{
public:
	pending_key () = default;
	pending_key (nano::account const &, nano::block_hash const &);
	bool deserialize (nano::stream &);
	bool operator== (nano::pending_key const &) const;
	nano::account const & key () const;
	nano::account account{ 0 };
	nano::block_hash hash{ 0 };
};

class endpoint_key final
{
public:
	endpoint_key () = default;

	/*
	 * @param address_a This should be in network byte order
	 * @param port_a This should be in host byte order
	 */
	endpoint_key (const std::array<uint8_t, 16> & address_a, uint16_t port_a);

	/*
	 * @return The ipv6 address in network byte order
	 */
	const std::array<uint8_t, 16> & address_bytes () const;

	/*
	 * @return The port in host byte order
	 */
	uint16_t port () const;

private:
	// Both stored internally in network byte order
	std::array<uint8_t, 16> address;
	uint16_t network_port{ 0 };
};

enum class no_value
{
	dummy
};

class unchecked_key final
{
public:
	unchecked_key () = default;
	unchecked_key (nano::block_hash const &, nano::block_hash const &);
	bool deserialize (nano::stream &);
	bool operator== (nano::unchecked_key const &) const;
	nano::block_hash const & key () const;
	nano::block_hash previous{ 0 };
	nano::block_hash hash{ 0 };
};

/**
 * Tag for block signature verification result
 */
enum class signature_verification : uint8_t
{
	unknown = 0,
	invalid = 1,
	valid = 2,
	valid_epoch = 3 // Valid for epoch blocks
};

/**
 * Information on an unchecked block
 */
class unchecked_info final
{
public:
	unchecked_info () = default;
	unchecked_info (std::shared_ptr<nano::block>, nano::account const &, uint64_t, nano::signature_verification = nano::signature_verification::unknown, bool = false);
	void serialize (nano::stream &) const;
	bool deserialize (nano::stream &);
	std::shared_ptr<nano::block> block;
	nano::account account{ 0 };
	/** Seconds since posix epoch */
	uint64_t modified{ 0 };
	nano::signature_verification verified{ nano::signature_verification::unknown };
	bool confirmed{ false };
};

class block_info final
{
public:
	block_info () = default;
	block_info (nano::account const &, nano::amount const &);
	nano::account account{ 0 };
	nano::amount balance{ 0 };
};
class block_counts final
{
public:
	size_t sum () const;
	size_t send{ 0 };
	size_t receive{ 0 };
	size_t open{ 0 };
	size_t change{ 0 };
	size_t state{ 0 };
};
using vote_blocks_vec_iter = std::vector<boost::variant<std::shared_ptr<nano::block>, nano::block_hash>>::const_iterator;
class iterate_vote_blocks_as_hash final
{
public:
	iterate_vote_blocks_as_hash () = default;
	nano::block_hash operator() (boost::variant<std::shared_ptr<nano::block>, nano::block_hash> const & item) const;
};
class vote final
{
public:
	vote () = default;
	vote (nano::vote const &);
	vote (bool &, nano::stream &, nano::block_uniquer * = nullptr);
	vote (bool &, nano::stream &, nano::block_type, nano::block_uniquer * = nullptr);
	vote (nano::account const &, nano::raw_key const &, uint64_t, std::shared_ptr<nano::block>);
	vote (nano::account const &, nano::raw_key const &, uint64_t, std::vector<nano::block_hash> const &);
	std::string hashes_string () const;
	nano::block_hash hash () const;
	nano::block_hash full_hash () const;
	bool operator== (nano::vote const &) const;
	bool operator!= (nano::vote const &) const;
	void serialize (nano::stream &, nano::block_type) const;
	void serialize (nano::stream &) const;
	void serialize_json (boost::property_tree::ptree & tree) const;
	bool deserialize (nano::stream &, nano::block_uniquer * = nullptr);
	bool validate () const;
	boost::transform_iterator<nano::iterate_vote_blocks_as_hash, nano::vote_blocks_vec_iter> begin () const;
	boost::transform_iterator<nano::iterate_vote_blocks_as_hash, nano::vote_blocks_vec_iter> end () const;
	std::string to_json () const;
	// Vote round sequence number
	uint64_t sequence;
	// The blocks, or block hashes, that this vote is for
	std::vector<boost::variant<std::shared_ptr<nano::block>, nano::block_hash>> blocks;
	// Account that's voting
	nano::account account;
	// Signature of sequence + block hashes
	nano::signature signature;
	static const std::string hash_prefix;
};
/**
 * This class serves to find and return unique variants of a vote in order to minimize memory usage
 */
class vote_uniquer final
{
public:
	using value_type = std::pair<const nano::block_hash, std::weak_ptr<nano::vote>>;

	vote_uniquer (nano::block_uniquer &);
	std::shared_ptr<nano::vote> unique (std::shared_ptr<nano::vote>);
	size_t size ();

private:
	nano::block_uniquer & uniquer;
	std::mutex mutex;
	std::unordered_map<std::remove_const_t<value_type::first_type>, value_type::second_type> votes;
	static unsigned constexpr cleanup_count = 2;
};

std::unique_ptr<seq_con_info_component> collect_seq_con_info (vote_uniquer & vote_uniquer, const std::string & name);

enum class vote_code
{
	invalid, // Vote is not signed correctly
	replay, // Vote does not have the highest sequence number, it's a replay
	vote // Vote has the highest sequence number
};

enum class process_result
{
	progress, // Hasn't been seen before, signed correctly
	bad_signature, // Signature was bad, forged or transmission error
	old, // Already seen and was valid
	negative_spend, // Malicious attempt to spend a negative amount
	fork, // Malicious fork based on previous
	unreceivable, // Source block doesn't exist, has already been received, or requires an account upgrade (epoch blocks)
	gap_previous, // Block marked as previous is unknown
	gap_source, // Block marked as source is unknown
	opened_burn_account, // The impossible happened, someone found the private key associated with the public key '0'.
	balance_mismatch, // Balance and amount delta don't match
	representative_mismatch, // Representative is changed when it is not allowed
	block_position // This block cannot follow the previous block
};
class process_return final
{
public:
	nano::process_result code;
	nano::account account;
	nano::amount amount;
	nano::account pending_account;
	boost::optional<bool> state_is_send;
	nano::signature_verification verified;
};
enum class tally_result
{
	vote,
	changed,
	confirm
};

class genesis final
{
public:
	genesis ();
	nano::block_hash hash () const;
	std::shared_ptr<nano::block> open;
};

class network_params;

/** Protocol versions whose value may depend on the active network */
class protocol_constants
{
public:
	protocol_constants (nano::nano_networks network_a);

	/** Current protocol version */
	uint8_t protocol_version = 0x11;

	/** Minimum accepted protocol version */
	uint8_t protocol_version_min = 0x10;

	/** Do not bootstrap from nodes older than this version. */
	uint8_t protocol_version_bootstrap_min = 0x10;

	/** Do not lazy bootstrap from nodes older than this version. */
	uint8_t protocol_version_bootstrap_lazy_min = 0x10;

	/** Do not start TCP realtime network connections to nodes older than this version */
	uint8_t tcp_realtime_protocol_version_min = 0x11;
};

/** Genesis keys and ledger constants for network variants */
class ledger_constants
{
public:
	ledger_constants (nano::network_constants & network_constants);
	ledger_constants (nano::nano_networks network_a);
	nano::keypair zero_key;
	nano::keypair test_genesis_key;
	nano::account nano_test_account;
	nano::account nano_beta_account;
	nano::account nano_live_account;
	std::string nano_test_genesis;
	std::string nano_beta_genesis;
	std::string nano_live_genesis;
	nano::account genesis_account;
	std::string genesis_block;
	nano::uint128_t genesis_amount;
	nano::account burn_account;
	nano::epochs epochs;
};

/** Constants which depend on random values (this class should never be used globally due to CryptoPP globals potentially not being initialized) */
class random_constants
{
public:
	random_constants ();
	nano::account not_an_account;
	nano::uint128_union random_128;
};

/** Node related constants whose value depends on the active network */
class node_constants
{
public:
	node_constants (nano::network_constants & network_constants);
	std::chrono::seconds period;
	std::chrono::milliseconds half_period;
	/** Default maximum idle time for a socket before it's automatically closed */
	std::chrono::seconds idle_timeout;
	std::chrono::seconds cutoff;
	std::chrono::seconds syn_cookie_cutoff;
	std::chrono::minutes backup_interval;
	std::chrono::seconds search_pending_interval;
	std::chrono::seconds peer_interval;
	std::chrono::minutes unchecked_cleaning_interval;
	std::chrono::milliseconds process_confirmed_interval;

	/** The maximum amount of samples for a 2 week period on live or 3 days on beta */
	uint64_t max_weight_samples;
	uint64_t weight_period;
};

/** Voting related constants whose value depends on the active network */
class voting_constants
{
public:
	voting_constants (nano::network_constants & network_constants);
	size_t max_cache;
};

/** Port-mapping related constants whose value depends on the active network */
class portmapping_constants
{
public:
	portmapping_constants (nano::network_constants & network_constants);
	// Timeouts are primes so they infrequently happen at the same time
	int mapping_timeout;
	int check_timeout;
};

/** Bootstrap related constants whose value depends on the active network */
class bootstrap_constants
{
public:
	bootstrap_constants (nano::network_constants & network_constants);
	uint64_t lazy_max_pull_blocks;
};

/** Constants whose value depends on the active network */
class network_params
{
public:
	/** Populate values based on the current active network */
	network_params ();

	/** Populate values based on \p network_a */
	network_params (nano::nano_networks network_a);

	std::array<uint8_t, 2> header_magic_number;
	unsigned kdf_work;
	network_constants network;
	protocol_constants protocol;
	ledger_constants ledger;
	random_constants random;
	voting_constants voting;
	node_constants node;
	portmapping_constants portmapping;
	bootstrap_constants bootstrap;
};

nano::wallet_id random_wallet_id ();
}
<|endoftext|>


<commit_before>//
//  yas_ui_collider.cpp
//

#include "yas_to_bool.h"
#include "yas_ui_collider.h"

using namespace yas;

struct ui::collider::impl : base::impl, renderable_collider::impl {
    ui::collider::args args;

    impl() {
    }

    impl(collider::args &&args) : args(std::move(args)) {
    }

    bool hit_test(ui::point const &loc) {
        auto const &shape = args.shape;

        if (!to_bool(shape)) {
            return false;
        } else if (shape == ui::collider_shape::anywhere) {
            return true;
        }

        auto pos = simd::float4x4(matrix_invert(_matrix)) * simd::float4{loc.x, loc.y, 0, 1};

        if (shape == ui::collider_shape::circle) {
            return std::powf(pos.x - args.center.x, 2) + std::powf(pos.y - args.center.y, 2) <
                   std::powf(args.radius, 2);
        } else if (shape == ui::collider_shape::square) {
            return contains(
                {-args.radius + args.center.x, -args.radius + args.center.y, args.radius * 2.0f, args.radius * 2.0f},
                {pos.x, pos.y});
        }

        return false;
    }

    simd::float4x4 const &matrix() const override {
        return _matrix;
    }

    void set_matrix(simd::float4x4 &&matrix) override {
        _matrix = std::move(matrix);
    }

   private:
    simd::float4x4 _matrix = matrix_identity_float4x4;
};

ui::collider::collider() : base(std::make_shared<impl>()) {
}

ui::collider::collider(collider::args args) : base(std::make_shared<impl>(std::move(args))) {
}

ui::collider::collider(std::nullptr_t) : base(nullptr) {
}

void ui::collider::set_shape(collider_shape shape) {
    impl_ptr<impl>()->args.shape = std::move(shape);
}

void ui::collider::set_center(ui::point center) {
    impl_ptr<impl>()->args.center = std::move(center);
}

void ui::collider::set_radius(float const radius) {
    impl_ptr<impl>()->args.radius = radius;
}

ui::collider_shape ui::collider::shape() const {
    return impl_ptr<impl>()->args.shape;
}

ui::point const &ui::collider::center() const {
    return impl_ptr<impl>()->args.center;
}

float ui::collider::radius() const {
    return impl_ptr<impl>()->args.radius;
}

bool ui::collider::hit_test(ui::point const &pos) const {
    return impl_ptr<impl>()->hit_test(pos);
}

ui::renderable_collider &ui::collider::renderable() {
    if (!_renderable) {
        _renderable = ui::renderable_collider{impl_ptr<ui::renderable_collider::impl>()};
    }
    return _renderable;
}

#pragma mark -

std::string yas::to_string(ui::collider_shape const &shape) {
    switch (shape) {
        case ui::collider_shape::none:
            return "none";
        case ui::collider_shape::anywhere:
            return "anywhere";
        case ui::collider_shape::circle:
            return "circle";
        case ui::collider_shape::square:
            return "square";
    }
}

std::ostream &operator<<(std::ostream &os, yas::ui::collider_shape const &shape) {
    os << to_string(shape);
    return os;
}
<commit_msg>fix collider<commit_after>//
//  yas_ui_collider.cpp
//

#include "yas_to_bool.h"
#include "yas_ui_collider.h"

using namespace yas;

struct ui::collider::impl : base::impl, renderable_collider::impl {
    ui::collider::args args;

    impl() {
    }

    impl(collider::args &&args) : args(std::move(args)) {
    }

    bool hit_test(ui::point const &loc) {
        auto const &shape = args.shape;

        if (!to_bool(shape)) {
            return false;
        } else if (shape == ui::collider_shape::anywhere) {
            return true;
        }

        auto pos = simd::float4x4(matrix_invert(_matrix)) * simd::float4{loc.x, loc.y, 0.0f, 1.0f};

        if (shape == ui::collider_shape::circle) {
            return std::powf(pos.x - args.center.x, 2.0f) + std::powf(pos.y - args.center.y, 2.0f) <
                   std::powf(args.radius, 2.0f);
        } else if (shape == ui::collider_shape::square) {
            return contains(
                {-args.radius + args.center.x, -args.radius + args.center.y, args.radius * 2.0f, args.radius * 2.0f},
                {pos.x, pos.y});
        }

        return false;
    }

    simd::float4x4 const &matrix() const override {
        return _matrix;
    }

    void set_matrix(simd::float4x4 &&matrix) override {
        _matrix = std::move(matrix);
    }

   private:
    simd::float4x4 _matrix = matrix_identity_float4x4;
};

ui::collider::collider() : base(std::make_shared<impl>()) {
}

ui::collider::collider(collider::args args) : base(std::make_shared<impl>(std::move(args))) {
}

ui::collider::collider(std::nullptr_t) : base(nullptr) {
}

void ui::collider::set_shape(collider_shape shape) {
    impl_ptr<impl>()->args.shape = std::move(shape);
}

void ui::collider::set_center(ui::point center) {
    impl_ptr<impl>()->args.center = std::move(center);
}

void ui::collider::set_radius(float const radius) {
    impl_ptr<impl>()->args.radius = radius;
}

ui::collider_shape ui::collider::shape() const {
    return impl_ptr<impl>()->args.shape;
}

ui::point const &ui::collider::center() const {
    return impl_ptr<impl>()->args.center;
}

float ui::collider::radius() const {
    return impl_ptr<impl>()->args.radius;
}

bool ui::collider::hit_test(ui::point const &pos) const {
    return impl_ptr<impl>()->hit_test(pos);
}

ui::renderable_collider &ui::collider::renderable() {
    if (!_renderable) {
        _renderable = ui::renderable_collider{impl_ptr<ui::renderable_collider::impl>()};
    }
    return _renderable;
}

#pragma mark -

std::string yas::to_string(ui::collider_shape const &shape) {
    switch (shape) {
        case ui::collider_shape::none:
            return "none";
        case ui::collider_shape::anywhere:
            return "anywhere";
        case ui::collider_shape::circle:
            return "circle";
        case ui::collider_shape::square:
            return "square";
    }
}

std::ostream &operator<<(std::ostream &os, yas::ui::collider_shape const &shape) {
    os << to_string(shape);
    return os;
}
<|endoftext|>


<commit_before>/***********************************************************************
    created:    28/9/2014
    author:     David Reepmeyer
*************************************************************************/
/***************************************************************************

    Permission is hereby granted, free of charge, to any person obtaining
    a copy of this software and associated documentation files (the
    "Software"), to deal in the Software without restriction, including
    without limitation the rights to use, copy, modify, merge, publish,
    distribute, sublicense, and/or sell copies of the Software, and to
    permit persons to whom the Software is furnished to do so, subject to
    the following conditions:

    The above copyright notice and this permission notice shall be
    included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
    IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
    OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
    ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
    OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__HAIKU__)
# include <unistd.h>
#endif

#include "CEGUISamplesConfig.h"
#include "CEGuiEGLBaseApplication.h"
#include "SampleBrowserBase.h"
#include "CEGUI/CEGUI.h"

#include <stdexcept>
#include <sstream>

#include <CEGUI/RendererModules/OpenGL/GLES2Renderer.h>

//----------------------------------------------------------------------------//
CEGuiEGLBaseApplication* CEGuiEGLBaseApplication::d_appInstance = 0;

//----------------------------------------------------------------------------//
CEGuiEGLBaseApplication::CEGuiEGLBaseApplication() :
    d_display(EGL_NO_DISPLAY),
    d_surface(EGL_NO_SURFACE),
    d_context(EGL_NO_CONTEXT),
    d_width(0),
    d_height(0),
    d_contextInitialised(false),
    d_contextValid(false),
    d_glesVersion(0)
{
    if(d_appInstance)
        throw CEGUI::InvalidRequestException("CEGuiEGLBaseApplication instance already exists!");

    d_appInstance = this;
    AndroidAppHelper::createWindow();
    d_renderer = &CEGUI::GLES2Renderer::create();
}

//----------------------------------------------------------------------------//
CEGuiEGLBaseApplication::~CEGuiEGLBaseApplication()
{
    terminate();
}

CEGuiEGLBaseApplication& CEGuiEGLBaseApplication::getSingleton()
{
    return (*d_appInstance);
}

//----------------------------------------------------------------------------//
void CEGuiEGLBaseApplication::run()
{

    d_sampleApp->initialise();

    d_windowSized = false; //The resize callback is being called immediately after setting it in this version of glfw
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    clock_gettime(CLOCK_MONOTONIC, &start_timespec);

    while(!d_sampleApp->isQuitting())
    {
        drawFrame();

#ifdef __ANDROID__

        if(!AndroidAppHelper::processEvents())
        {
            d_sampleApp->setQuitting(true);
            terminate();
        }

#endif

        if(d_windowSized)
        {
            d_windowSized = false;
            //CEGUI::System::getSingleton().notifyDisplaySizeChanged(
            //CEGUI::Sizef(static_cast<float>(d_newWindowWidth),
            //static_cast<float>(d_newWindowHeight)));
        }

    }

    d_sampleApp->deinitialise();
}

//----------------------------------------------------------------------------//
SampleBrowserBase* CEGuiEGLBaseApplication::getSampleApp()
{
    return d_sampleApp;
}

//----------------------------------------------------------------------------//
void CEGuiEGLBaseApplication::initialiseResourceGroupDirectories()
{
    // initialise the required dirs for the DefaultResourceProvider
    CEGUI::DefaultResourceProvider* rp =
        static_cast<CEGUI::DefaultResourceProvider*>
        (CEGUI::System::getSingleton().getResourceProvider());
#ifdef __ANDROID__
    const char* dataPathPrefix = "datafiles";
#else
    const char* dataPathPrefix = getDataPathPrefix();
#endif
    char resourcePath[PATH_MAX];

    // for each resource type, set a resource group directory
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "schemes");
    rp->setResourceGroupDirectory("schemes", resourcePath);
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "imagesets");
    rp->setResourceGroupDirectory("imagesets", resourcePath);
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "fonts");
    rp->setResourceGroupDirectory("fonts", resourcePath);
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "layouts");
    rp->setResourceGroupDirectory("layouts", resourcePath);
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "looknfeel");
    rp->setResourceGroupDirectory("looknfeels", resourcePath);
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "lua_scripts");
    rp->setResourceGroupDirectory("lua_scripts", resourcePath);
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "xml_schemas");
    rp->setResourceGroupDirectory("schemas", resourcePath);
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "animations");
    rp->setResourceGroupDirectory("animations", resourcePath);
}

//----------------------------------------------------------------------------//
void CEGuiEGLBaseApplication::destroyWindow()
{
    terminate();
}

//----------------------------------------------------------------------------//
void CEGuiEGLBaseApplication::beginRendering(const float /*elapsed*/)
{
    clearFrame();
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    glViewport(0, 0, d_width, d_height);
}

//----------------------------------------------------------------------------//
void CEGuiEGLBaseApplication::endRendering()
{
    swap();
}
//----------------------------------------------------------------------------//
void CEGuiEGLBaseApplication::clearFrame()
{
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}

//----------------------------------------------------------------------------//
void CEGuiEGLBaseApplication::drawFrame()
{
    d_appInstance->renderSingleFrame(static_cast<float>(getElapsedTime()));
}

double CEGuiEGLBaseApplication::getElapsedTime()
{
    timespec now_timespec;
    clock_gettime(CLOCK_MONOTONIC, &now_timespec);
    double elapsed = (now_timespec.tv_sec - start_timespec.tv_sec);
    elapsed += ((double)(now_timespec.tv_nsec - start_timespec.tv_nsec)) / ((double) 1000000000L);
    start_timespec = now_timespec;
    return elapsed;
}

//----------------------------------------------------------------------------//
bool CEGuiEGLBaseApplication::init(ANativeWindow* window, int openglesVersion = 2)
{
    d_glesVersion = openglesVersion;

    if(d_contextInitialised)
        return true;

    window_ = window;
    initEGLSurface();
    initEGLContext();

    d_contextInitialised = true;

    return true;
}

//----------------------------------------------------------------------------//
bool CEGuiEGLBaseApplication::initEGLSurface()
{
    d_display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
    eglInitialize(d_display, 0, 0);

    const EGLint attribs[] = { EGL_RENDERABLE_TYPE,
                               EGL_OPENGL_ES2_BIT, //Request opengl ES2.0
                               EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_BLUE_SIZE, 8, EGL_GREEN_SIZE, 8,
                               EGL_RED_SIZE, 8, EGL_DEPTH_SIZE, 24, EGL_NONE
                             };
    int32_t color_size_ = 8;
    int32_t depth_size_ = 24;

    EGLint num_configs;
    eglChooseConfig(d_display, attribs, &d_config, 1, &num_configs);

    if(!num_configs)
    {
        //Fall back to 16bit depth buffer
        const EGLint attribs[] = { EGL_RENDERABLE_TYPE,
                                   EGL_OPENGL_ES2_BIT, //Request opengl ES2.0
                                   EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_BLUE_SIZE, 8, EGL_GREEN_SIZE, 8,
                                   EGL_RED_SIZE, 8, EGL_DEPTH_SIZE, 16, EGL_NONE
                                 };
        eglChooseConfig(d_display, attribs, &d_config, 1, &num_configs);
        depth_size_ = 16;
    }

    if(!num_configs)
    {
        CEGUI::Logger::getSingleton().logEvent("Unable to retrieve EGL config");
        return false;
    }

    d_surface = eglCreateWindowSurface(d_display, d_config, window_, NULL);
    eglQuerySurface(d_display, d_surface, EGL_WIDTH, &d_width);
    eglQuerySurface(d_display, d_surface, EGL_HEIGHT, &d_height);
    EGLint format;
    eglGetConfigAttrib(d_display, d_config, EGL_NATIVE_VISUAL_ID, &format);
    ANativeWindow_setBuffersGeometry(window_, 0, 0, format);
    return true;
}

//----------------------------------------------------------------------------//
bool CEGuiEGLBaseApplication::initEGLContext()
{
    const EGLint d_contextattribs[] =
    {
        EGL_CONTEXT_CLIENT_VERSION, d_glesVersion, //Request opengl es version (2/3)
        EGL_NONE
    };

    d_context = eglCreateContext(d_display, d_config, NULL, d_contextattribs);

    if(eglMakeCurrent(d_display, d_surface, d_surface, d_context) == EGL_FALSE)
    {
        CEGUI::Logger::getSingleton().logEvent("Unable to eglMakeCurrent");
        return false;
    }

    d_contextValid = true;
    return true;
}

//----------------------------------------------------------------------------//
EGLint CEGuiEGLBaseApplication::swap()
{
    bool b = eglSwapBuffers(d_display, d_surface);

    if(!b)
    {
        CEGUI::Logger::getSingleton().logEvent("eglSwapBuffers failed");
        EGLint err = eglGetError();

        if(err == EGL_BAD_SURFACE)
        {
            //Recreate surface
            initEGLSurface();
            return EGL_SUCCESS; //Still consider glContext is valid
        }
        else if(err == EGL_CONTEXT_LOST || err == EGL_BAD_CONTEXT)
        {
            //Context has been lost!!
            d_contextValid = false;
            terminate();
            initEGLContext();
        }

        return err;
    }

    return EGL_SUCCESS;
}

//----------------------------------------------------------------------------//
void CEGuiEGLBaseApplication::terminate()
{
    if(d_display != EGL_NO_DISPLAY)
    {
        eglMakeCurrent(d_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);

        if(d_context != EGL_NO_CONTEXT)
        {
            eglDestroyContext(d_display, d_context);
        }

        if(d_surface != EGL_NO_SURFACE)
        {
            eglDestroySurface(d_display, d_surface);
        }

        eglTerminate(d_display);
    }

    d_display = EGL_NO_DISPLAY;
    d_context = EGL_NO_CONTEXT;
    d_surface = EGL_NO_SURFACE;
    d_contextValid = false;

}

//----------------------------------------------------------------------------//
EGLint CEGuiEGLBaseApplication::resume(ANativeWindow* window)
{
    if(d_contextInitialised == false)
    {
        init(window);
        return EGL_SUCCESS;
    }

    int32_t original_widhth = d_width;
    int32_t original_height = d_height;

    //Create surface
    window_ = window;
    d_surface = eglCreateWindowSurface(d_display, d_config, window_, NULL);
    eglQuerySurface(d_display, d_surface, EGL_WIDTH, &d_width);
    eglQuerySurface(d_display, d_surface, EGL_HEIGHT, &d_height);

    if(d_width != original_widhth || d_height != original_height)
    {
        CEGUI::Logger::getSingleton().logEvent("Screen Resized");
    }

    if(eglMakeCurrent(d_display, d_surface, d_surface, d_context) == EGL_TRUE)
        return EGL_SUCCESS;

    EGLint err = eglGetError();
    CEGUI::Logger::getSingleton().logEvent("Unable to eglMakeCurrent");

    if(err == EGL_CONTEXT_LOST)
    {
        //Recreate context
        CEGUI::Logger::getSingleton().logEvent("Recreating EGL context");
        initEGLContext();
    }
    else
    {
        //Recreate surface
        terminate();
        initEGLSurface();
        initEGLContext();
    }

    return err;
}

//----------------------------------------------------------------------------//
void CEGuiEGLBaseApplication::suspend()
{
    if(d_surface != EGL_NO_SURFACE)
    {
        eglDestroySurface(d_display, d_surface);
        d_surface = EGL_NO_SURFACE;
    }
}

//----------------------------------------------------------------------------//
bool CEGuiEGLBaseApplication::invalidate()
{
    terminate();

    d_contextInitialised = false;
    return true;
}

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

<commit_msg>removed logging from egl to cegui logger since cegui system is not yet intialized<commit_after>/***********************************************************************
    created:    28/9/2014
    author:     David Reepmeyer
*************************************************************************/
/***************************************************************************

    Permission is hereby granted, free of charge, to any person obtaining
    a copy of this software and associated documentation files (the
    "Software"), to deal in the Software without restriction, including
    without limitation the rights to use, copy, modify, merge, publish,
    distribute, sublicense, and/or sell copies of the Software, and to
    permit persons to whom the Software is furnished to do so, subject to
    the following conditions:

    The above copyright notice and this permission notice shall be
    included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
    IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
    OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
    ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
    OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__HAIKU__)
# include <unistd.h>
#endif

#include "CEGUISamplesConfig.h"
#include "CEGuiEGLBaseApplication.h"
#include "SampleBrowserBase.h"
#include "CEGUI/CEGUI.h"

#include <stdexcept>
#include <sstream>

#include <CEGUI/RendererModules/OpenGL/GLES2Renderer.h>

//----------------------------------------------------------------------------//
CEGuiEGLBaseApplication* CEGuiEGLBaseApplication::d_appInstance = 0;

//----------------------------------------------------------------------------//
CEGuiEGLBaseApplication::CEGuiEGLBaseApplication() :
    d_display(EGL_NO_DISPLAY),
    d_surface(EGL_NO_SURFACE),
    d_context(EGL_NO_CONTEXT),
    d_width(0),
    d_height(0),
    d_contextInitialised(false),
    d_contextValid(false),
    d_glesVersion(0)
{
    if(d_appInstance)
        throw CEGUI::InvalidRequestException("CEGuiEGLBaseApplication instance already exists!");

    d_appInstance = this;
    AndroidAppHelper::createWindow();
    d_renderer = &CEGUI::GLES2Renderer::create();
}

//----------------------------------------------------------------------------//
CEGuiEGLBaseApplication::~CEGuiEGLBaseApplication()
{
    terminate();
}

CEGuiEGLBaseApplication& CEGuiEGLBaseApplication::getSingleton()
{
    return (*d_appInstance);
}

//----------------------------------------------------------------------------//
void CEGuiEGLBaseApplication::run()
{

    d_sampleApp->initialise();

    d_windowSized = false; //The resize callback is being called immediately after setting it in this version of glfw
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    clock_gettime(CLOCK_MONOTONIC, &start_timespec);

    while(!d_sampleApp->isQuitting())
    {
        drawFrame();

#ifdef __ANDROID__

        if(!AndroidAppHelper::processEvents())
        {
            d_sampleApp->setQuitting(true);
            terminate();
        }

#endif
        if(d_windowSized)
        {
            d_windowSized = false;
            //CEGUI::System::getSingleton().notifyDisplaySizeChanged(
            //CEGUI::Sizef(static_cast<float>(d_newWindowWidth),
            //static_cast<float>(d_newWindowHeight)));
        }

    }

    d_sampleApp->deinitialise();
}

//----------------------------------------------------------------------------//
SampleBrowserBase* CEGuiEGLBaseApplication::getSampleApp()
{
    return d_sampleApp;
}

//----------------------------------------------------------------------------//
void CEGuiEGLBaseApplication::initialiseResourceGroupDirectories()
{
    // initialise the required dirs for the DefaultResourceProvider
    CEGUI::DefaultResourceProvider* rp =
        static_cast<CEGUI::DefaultResourceProvider*>
        (CEGUI::System::getSingleton().getResourceProvider());
#ifdef __ANDROID__
    const char* dataPathPrefix = "datafiles";
#else
    const char* dataPathPrefix = getDataPathPrefix();
#endif
    char resourcePath[PATH_MAX];

    // for each resource type, set a resource group directory
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "schemes");
    rp->setResourceGroupDirectory("schemes", resourcePath);
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "imagesets");
    rp->setResourceGroupDirectory("imagesets", resourcePath);
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "fonts");
    rp->setResourceGroupDirectory("fonts", resourcePath);
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "layouts");
    rp->setResourceGroupDirectory("layouts", resourcePath);
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "looknfeel");
    rp->setResourceGroupDirectory("looknfeels", resourcePath);
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "lua_scripts");
    rp->setResourceGroupDirectory("lua_scripts", resourcePath);
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "xml_schemas");
    rp->setResourceGroupDirectory("schemas", resourcePath);
    sprintf(resourcePath, "%s/%s", dataPathPrefix, "animations");
    rp->setResourceGroupDirectory("animations", resourcePath);
}

//----------------------------------------------------------------------------//
void CEGuiEGLBaseApplication::destroyWindow()
{
    terminate();
}

//----------------------------------------------------------------------------//
void CEGuiEGLBaseApplication::beginRendering(const float /*elapsed*/)
{
    clearFrame();
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    glViewport(0, 0, d_width, d_height);
}

//----------------------------------------------------------------------------//
void CEGuiEGLBaseApplication::endRendering()
{
    swap();
}
//----------------------------------------------------------------------------//
void CEGuiEGLBaseApplication::clearFrame()
{
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}

//----------------------------------------------------------------------------//
void CEGuiEGLBaseApplication::drawFrame()
{
    d_appInstance->renderSingleFrame(static_cast<float>(getElapsedTime()));
}

double CEGuiEGLBaseApplication::getElapsedTime()
{
    timespec now_timespec;
    clock_gettime(CLOCK_MONOTONIC, &now_timespec);
    double elapsed = (now_timespec.tv_sec - start_timespec.tv_sec);
    elapsed += ((double)(now_timespec.tv_nsec - start_timespec.tv_nsec)) / ((double) 1000000000L);
    start_timespec = now_timespec;
    return elapsed;
}

//----------------------------------------------------------------------------//
bool CEGuiEGLBaseApplication::init(ANativeWindow* window, int openglesVersion = 2)
{
    d_glesVersion = openglesVersion;

    if(d_contextInitialised)
        return true;

    window_ = window;
    initEGLSurface();
    initEGLContext();

    d_contextInitialised = true;

    return true;
}

//----------------------------------------------------------------------------//
bool CEGuiEGLBaseApplication::initEGLSurface()
{
    d_display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
    eglInitialize(d_display, 0, 0);

    const EGLint attribs[] = { EGL_RENDERABLE_TYPE,
                               EGL_OPENGL_ES2_BIT, //Request opengl ES2.0
                               EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_BLUE_SIZE, 8, EGL_GREEN_SIZE, 8,
                               EGL_RED_SIZE, 8, EGL_DEPTH_SIZE, 24, EGL_NONE
                             };
    int32_t color_size_ = 8;
    int32_t depth_size_ = 24;

    EGLint num_configs;
    eglChooseConfig(d_display, attribs, &d_config, 1, &num_configs);

    if(!num_configs)
    {
        //Fall back to 16bit depth buffer
        const EGLint attribs[] = { EGL_RENDERABLE_TYPE,
                                   EGL_OPENGL_ES2_BIT, //Request opengl ES2.0
                                   EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_BLUE_SIZE, 8, EGL_GREEN_SIZE, 8,
                                   EGL_RED_SIZE, 8, EGL_DEPTH_SIZE, 16, EGL_NONE
                                 };
        eglChooseConfig(d_display, attribs, &d_config, 1, &num_configs);
        depth_size_ = 16;
    }

    if(!num_configs)
    {
        return false;
    }

    d_surface = eglCreateWindowSurface(d_display, d_config, window_, NULL);
    eglQuerySurface(d_display, d_surface, EGL_WIDTH, &d_width);
    eglQuerySurface(d_display, d_surface, EGL_HEIGHT, &d_height);
    EGLint format;
    eglGetConfigAttrib(d_display, d_config, EGL_NATIVE_VISUAL_ID, &format);
    ANativeWindow_setBuffersGeometry(window_, 0, 0, format);
    return true;
}

//----------------------------------------------------------------------------//
bool CEGuiEGLBaseApplication::initEGLContext()
{
    const EGLint d_contextattribs[] =
    {
        EGL_CONTEXT_CLIENT_VERSION, d_glesVersion, //Request opengl es version (2/3)
        EGL_NONE
    };

    d_context = eglCreateContext(d_display, d_config, NULL, d_contextattribs);

    if(eglMakeCurrent(d_display, d_surface, d_surface, d_context) == EGL_FALSE)
    {
        return false;
    }

    d_contextValid = true;
    return true;
}

//----------------------------------------------------------------------------//
EGLint CEGuiEGLBaseApplication::swap()
{
    bool b = eglSwapBuffers(d_display, d_surface);

    if(!b)
    {
        EGLint err = eglGetError();

        if(err == EGL_BAD_SURFACE)
        {
            //Recreate surface
            initEGLSurface();
            return EGL_SUCCESS; //Still consider glContext is valid
        }
        else if(err == EGL_CONTEXT_LOST || err == EGL_BAD_CONTEXT)
        {
            //Context has been lost!!
            d_contextValid = false;
            terminate();
            initEGLContext();
        }

        return err;
    }

    return EGL_SUCCESS;
}

//----------------------------------------------------------------------------//
void CEGuiEGLBaseApplication::terminate()
{
    if(d_display != EGL_NO_DISPLAY)
    {
        eglMakeCurrent(d_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);

        if(d_context != EGL_NO_CONTEXT)
        {
            eglDestroyContext(d_display, d_context);
        }

        if(d_surface != EGL_NO_SURFACE)
        {
            eglDestroySurface(d_display, d_surface);
        }

        eglTerminate(d_display);
    }

    d_display = EGL_NO_DISPLAY;
    d_context = EGL_NO_CONTEXT;
    d_surface = EGL_NO_SURFACE;
    d_contextValid = false;

}

//----------------------------------------------------------------------------//
EGLint CEGuiEGLBaseApplication::resume(ANativeWindow* window)
{
    if(d_contextInitialised == false)
    {
        init(window);
        return EGL_SUCCESS;
    }

    int32_t original_widhth = d_width;
    int32_t original_height = d_height;

    //Create surface
    window_ = window;
    d_surface = eglCreateWindowSurface(d_display, d_config, window_, NULL);
    eglQuerySurface(d_display, d_surface, EGL_WIDTH, &d_width);
    eglQuerySurface(d_display, d_surface, EGL_HEIGHT, &d_height);

    if(eglMakeCurrent(d_display, d_surface, d_surface, d_context) == EGL_TRUE)
        return EGL_SUCCESS;

    EGLint err = eglGetError();

    if(err == EGL_CONTEXT_LOST)
    {
        //Recreate context
        initEGLContext();
    }
    else
    {
        //Recreate surface
        terminate();
        initEGLSurface();
        initEGLContext();
    }

    return err;
}

//----------------------------------------------------------------------------//
void CEGuiEGLBaseApplication::suspend()
{
    if(d_surface != EGL_NO_SURFACE)
    {
        eglDestroySurface(d_display, d_surface);
        d_surface = EGL_NO_SURFACE;
    }
}

//----------------------------------------------------------------------------//
bool CEGuiEGLBaseApplication::invalidate()
{
    terminate();

    d_contextInitialised = false;
    return true;
}

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

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: controlpropertyhdl.cxx,v $
 *
 *  $Revision: 1.18 $
 *
 *  last change: $Author: obo $ $Date: 2006-10-12 14:42:46 $
 *
 *  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_xmloff.hxx"

#ifndef _XMLOFF_FORMS_CONTROLPROPERTYHDL_HXX_
#include "controlpropertyhdl.hxx"
#endif
#ifndef _COM_SUN_STAR_AWT_TEXTALIGN_HPP_
#include <com/sun/star/awt/TextAlign.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_FONTWIDTH_HPP_
#include <com/sun/star/awt/FontWidth.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_FONTEMPHASISMARK_HPP_
#include <com/sun/star/awt/FontEmphasisMark.hpp>
#endif
#ifndef _XMLOFF_XMLTYPES_HXX
#include "xmltypes.hxx"
#endif
#ifndef _XMLOFF_FORMENUMS_HXX_
#include "formenums.hxx"
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _XMLOFF_FORMS_CALLBACKS_HXX_
#include "callbacks.hxx"
#endif
#ifndef _XMLOFF_XMLCONSTANTSPROPERTYHANDLER_HXX
#include "XMLConstantsPropertyHandler.hxx"
#endif

//.........................................................................
namespace xmloff
{
//.........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::awt;
    using namespace ::com::sun::star::beans;
    using namespace ::xmloff::token;

    //=====================================================================
    //= OControlPropertyHandlerFactory
    //=====================================================================
    //---------------------------------------------------------------------
    OControlPropertyHandlerFactory::OControlPropertyHandlerFactory()
        :m_pTextAlignHandler(NULL)
        ,m_pControlBorderStyleHandler(NULL)
        ,m_pControlBorderColorHandler(NULL)
        ,m_pRotationAngleHandler(NULL)
        ,m_pFontWidthHandler(NULL)
        ,m_pFontEmphasisHandler(NULL)
        ,m_pFontReliefHandler(NULL)
    {
    }

    //---------------------------------------------------------------------
    OControlPropertyHandlerFactory::~OControlPropertyHandlerFactory()
    {
        delete m_pTextAlignHandler;
        delete m_pControlBorderStyleHandler;
        delete m_pControlBorderColorHandler;
        delete m_pRotationAngleHandler;
        delete m_pFontWidthHandler;
        delete m_pFontEmphasisHandler;
        delete m_pFontReliefHandler;
    }

    //---------------------------------------------------------------------
    const XMLPropertyHandler* OControlPropertyHandlerFactory::GetPropertyHandler(sal_Int32 _nType) const
    {
        const XMLPropertyHandler* pHandler = NULL;

        switch (_nType)
        {
            case XML_TYPE_TEXT_ALIGN:
                if (!m_pTextAlignHandler)
                    m_pTextAlignHandler = new XMLConstantsPropertyHandler(OEnumMapper::getEnumMap(OEnumMapper::epTextAlign), XML_TOKEN_INVALID );
                pHandler = m_pTextAlignHandler;
                break;

            case XML_TYPE_CONTROL_BORDER:
                if (!m_pControlBorderStyleHandler)
                    m_pControlBorderStyleHandler = new OControlBorderStyleHandler;
                pHandler = m_pControlBorderStyleHandler;
                break;

            case XML_TYPE_CONTROL_BORDER_COLOR:
                if ( !m_pControlBorderColorHandler )
                    m_pControlBorderColorHandler = new OControlBorderColorHandler;
                pHandler = m_pControlBorderColorHandler;
                break;

            case XML_TYPE_ROTATION_ANGLE:
                if (!m_pRotationAngleHandler)
                    m_pRotationAngleHandler = new ORotationAngleHandler;
                pHandler = m_pRotationAngleHandler;
                break;

            case XML_TYPE_FONT_WIDTH:
                if (!m_pFontWidthHandler)
                    m_pFontWidthHandler = new OFontWidthHandler;
                pHandler = m_pFontWidthHandler;
                break;

            case XML_TYPE_CONTROL_TEXT_EMPHASIZE:
                if (!m_pFontEmphasisHandler)
                    m_pFontEmphasisHandler = new XMLConstantsPropertyHandler( OEnumMapper::getEnumMap(OEnumMapper::epFontEmphasis), XML_NONE );
                pHandler = m_pFontEmphasisHandler;
                break;

            case XML_TYPE_TEXT_FONT_RELIEF:
                if (!m_pFontReliefHandler)
                    m_pFontReliefHandler = new XMLConstantsPropertyHandler( OEnumMapper::getEnumMap(OEnumMapper::epFontRelief), XML_NONE );
                pHandler = m_pFontReliefHandler;
                break;
        }

        if (!pHandler)
            pHandler = XMLPropertyHandlerFactory::GetPropertyHandler(_nType);
        return pHandler;
    }

    //=====================================================================
    //= OControlTextEmphasisHandler
    //=====================================================================
    OControlTextEmphasisHandler::OControlTextEmphasisHandler()
    {
    }

    //---------------------------------------------------------------------
    sal_Bool OControlTextEmphasisHandler::exportXML( ::rtl::OUString& _rStrExpValue, const Any& _rValue, const SvXMLUnitConverter& ) const
    {
        ::rtl::OUStringBuffer aReturn;
        sal_Bool bSuccess = sal_False;
        sal_Int16 nFontEmphasis = sal_Int16();
        if (_rValue >>= nFontEmphasis)
        {
            // the type
            sal_Int16 nType = nFontEmphasis & ~(FontEmphasisMark::ABOVE | FontEmphasisMark::BELOW);
            // the position of the mark
            sal_Bool bBelow = 0 != (nFontEmphasis & FontEmphasisMark::BELOW);

            // convert
            bSuccess = SvXMLUnitConverter::convertEnum(aReturn, nType, OEnumMapper::getEnumMap(OEnumMapper::epFontEmphasis), XML_NONE);
            if (bSuccess)
            {
                aReturn.append( (sal_Unicode)' ' );
                aReturn.append( GetXMLToken(bBelow ? XML_BELOW : XML_ABOVE) );

                _rStrExpValue = aReturn.makeStringAndClear();
            }
        }

        return bSuccess;
    }

    //---------------------------------------------------------------------
    sal_Bool OControlTextEmphasisHandler::importXML( const ::rtl::OUString& _rStrImpValue, Any& _rValue, const SvXMLUnitConverter& ) const
    {
        sal_Bool bSuccess = sal_True;
        sal_uInt16 nEmphasis = FontEmphasisMark::NONE;

        sal_Bool bBelow = sal_False;
        sal_Bool bHasPos = sal_False, bHasType = sal_False;

        ::rtl::OUString sToken;
        SvXMLTokenEnumerator aTokenEnum(_rStrImpValue);
        while (aTokenEnum.getNextToken(sToken))
        {
            if (!bHasPos)
            {
                if (IsXMLToken(sToken, XML_ABOVE))
                {
                    bBelow = sal_False;
                    bHasPos = sal_True;
                }
                else if (IsXMLToken(sToken, XML_BELOW))
                {
                    bBelow = sal_True;
                    bHasPos = sal_True;
                }
            }
            if (!bHasType)
            {
                if (SvXMLUnitConverter::convertEnum(nEmphasis, sToken, OEnumMapper::getEnumMap(OEnumMapper::epFontEmphasis)))
                {
                    bHasType = sal_True;
                }
                else
                {
                    bSuccess = sal_False;
                    break;
                }
            }
        }

        if (bSuccess)
        {
            nEmphasis |= bBelow ? FontEmphasisMark::BELOW : FontEmphasisMark::ABOVE;
            _rValue <<= (sal_Int16)nEmphasis;
        }

        return bSuccess;
    }

    //=====================================================================
    //= OControlBorderHandlerFactory
    //=====================================================================
    //---------------------------------------------------------------------
    const XMLPropertyHandler* OControlBorderHandlerFactory::createBorderHandler()
    {
        return new OControlBorderStyleHandler;
    }

    //---------------------------------------------------------------------
    const XMLPropertyHandler* OControlBorderHandlerFactory::createBorderColorHandler()
    {
        return new OControlBorderColorHandler;
    }

    //=====================================================================
    //= OControlBorderHandlerBase
    //=====================================================================
    //---------------------------------------------------------------------
    OControlBorderHandlerBase::OControlBorderHandlerBase()
    {
    }

    //---------------------------------------------------------------------
    sal_Bool OControlBorderHandlerBase::importXML( const ::rtl::OUString& _rStrImpValue, Any& _rValue, const SvXMLUnitConverter& ) const
    {
        ::rtl::OUString sToken;
        SvXMLTokenEnumerator aTokens(_rStrImpValue);

        sal_uInt16 nStyle = 1;
        Color aColor;

        sal_Bool bFoundStyle = sal_False;
        sal_Bool bFoundColor = sal_False;

        while   (   !( bFoundStyle && bFoundColor ) // did not yet find both aspects
                &&  aTokens.getNextToken(sToken)    // have a new token
                &&  (0 != sToken.getLength())       // really have a new token
                )
        {
            // is it a valid enum value?
            if ( !bFoundStyle )
                bFoundStyle = SvXMLUnitConverter::convertEnum(nStyle, sToken, OEnumMapper::getEnumMap(OEnumMapper::epBorderWidth));
            // is it a color value?
            if ( !bFoundColor )
                bFoundColor = SvXMLUnitConverter::convertColor( aColor, sToken );
        }

        if ( !bFoundStyle && !bFoundColor )
            return sal_False;

        // if we're here, the string could have had more or less than the requested 3 tokens, but we ignore this.
        // At least we have a valid style or a valid, which is everything we're interested in.
        pickOne( aColor, (sal_Int16)nStyle, _rValue );
        return sal_True;
    }

    //=====================================================================
    //= OControlBorderStyleHandler
    //=====================================================================
    //---------------------------------------------------------------------
    OControlBorderStyleHandler::OControlBorderStyleHandler()
    {
    }

    //---------------------------------------------------------------------
    sal_Bool OControlBorderStyleHandler::exportXML( ::rtl::OUString& _rStrExpValue, const Any& _rValue, const SvXMLUnitConverter& ) const
    {
        sal_Bool bSuccess = sal_False;
        sal_Int16 nBorder = 0;

        ::rtl::OUStringBuffer aOut;
        bSuccess =  (_rValue >>= nBorder)
                &&  SvXMLUnitConverter::convertEnum(aOut, nBorder, OEnumMapper::getEnumMap(OEnumMapper::epBorderWidth));

        if ( _rStrExpValue.getLength() )
            _rStrExpValue += ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( " " ) );
        _rStrExpValue += aOut.makeStringAndClear();
        return bSuccess;
    }

    //---------------------------------------------------------------------
    void OControlBorderStyleHandler::pickOne( const Color&, sal_Int16 _nStyle, Any& _rValue ) const
    {
        _rValue <<= _nStyle;
    }

    //=====================================================================
    //= OControlBorderColorHandler
    //=====================================================================
    //---------------------------------------------------------------------
    OControlBorderColorHandler::OControlBorderColorHandler()
    {
    }

    //---------------------------------------------------------------------
    sal_Bool OControlBorderColorHandler::exportXML( ::rtl::OUString& _rStrExpValue, const Any& _rValue, const SvXMLUnitConverter& ) const
    {
        sal_Bool bSuccess = sal_False;
        sal_Int32 nBorderColor = 0;

        ::rtl::OUStringBuffer aOut;
        if ( _rValue >>= nBorderColor )
        {
            SvXMLUnitConverter::convertColor( aOut, Color( nBorderColor ) );
            bSuccess = sal_True;
        }

        if ( _rStrExpValue.getLength() )
            _rStrExpValue += ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( " " ) );
        _rStrExpValue += aOut.makeStringAndClear();
        return bSuccess;
    }

    //---------------------------------------------------------------------
    void OControlBorderColorHandler::pickOne( const Color& _rColor, sal_Int16 /*_nStyle*/, Any& _rValue ) const
    {
        _rValue <<= (sal_Int32)_rColor.GetColor();
    }

    //=====================================================================
    //= OFontWidthHandler
    //=====================================================================
    //---------------------------------------------------------------------
    OFontWidthHandler::OFontWidthHandler()
    {
    }

    //---------------------------------------------------------------------
    sal_Bool OFontWidthHandler::importXML( const ::rtl::OUString& _rStrImpValue, Any& _rValue, const SvXMLUnitConverter& ) const
    {
        sal_Int32 nWidth = 0;
        sal_Bool bSuccess = SvXMLUnitConverter::convertMeasure(nWidth, _rStrImpValue, MAP_POINT);
        if (bSuccess)
            _rValue <<= (sal_Int16)nWidth;

        return bSuccess;
    }

    //---------------------------------------------------------------------
    sal_Bool OFontWidthHandler::exportXML( ::rtl::OUString& _rStrExpValue, const Any& _rValue, const SvXMLUnitConverter& ) const
    {
        sal_Int16 nWidth = 0;
        ::rtl::OUStringBuffer aResult;
        if (_rValue >>= nWidth)
            SvXMLUnitConverter::convertMeasure(aResult, nWidth, MAP_POINT, MAP_POINT);
        _rStrExpValue = aResult.makeStringAndClear();

        return _rStrExpValue.getLength() != 0;
    }

    //=====================================================================
    //= ORotationAngleHandler
    //=====================================================================
    //---------------------------------------------------------------------
    ORotationAngleHandler::ORotationAngleHandler()
    {
    }

    //---------------------------------------------------------------------
    sal_Bool ORotationAngleHandler::importXML( const ::rtl::OUString& _rStrImpValue, Any& _rValue, const SvXMLUnitConverter& ) const
    {
        double fValue;
        sal_Bool bSucces =
            SvXMLUnitConverter::convertDouble(fValue, _rStrImpValue);
        if (bSucces)
        {
            fValue *= 10;
            _rValue <<= (float)fValue;
        }

        return bSucces;
    }

    //---------------------------------------------------------------------
    sal_Bool ORotationAngleHandler::exportXML( ::rtl::OUString& _rStrExpValue, const Any& _rValue, const SvXMLUnitConverter& ) const
    {
        float fAngle;
        sal_Bool bSuccess = (_rValue >>= fAngle);

        if (bSuccess)
        {
            rtl::OUStringBuffer sValue;
            SvXMLUnitConverter::convertDouble(sValue, ((double)fAngle) / 10);
            _rStrExpValue = sValue.makeStringAndClear();
        }

        return bSuccess;
    }

//.........................................................................
}   // namespace xmloff
//.........................................................................

<commit_msg>INTEGRATION: CWS pj65 (1.18.12); FILE MERGED 2006/10/31 14:02:57 pjanik 1.18.12.1: #i71027#: prevent warnings on Mac OS X with gcc 4.0.1.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: controlpropertyhdl.cxx,v $
 *
 *  $Revision: 1.19 $
 *
 *  last change: $Author: vg $ $Date: 2006-11-21 17:34:18 $
 *
 *  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_xmloff.hxx"

#ifndef _XMLOFF_FORMS_CONTROLPROPERTYHDL_HXX_
#include "controlpropertyhdl.hxx"
#endif
#ifndef _COM_SUN_STAR_AWT_TEXTALIGN_HPP_
#include <com/sun/star/awt/TextAlign.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_FONTWIDTH_HPP_
#include <com/sun/star/awt/FontWidth.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_FONTEMPHASISMARK_HPP_
#include <com/sun/star/awt/FontEmphasisMark.hpp>
#endif
#ifndef _XMLOFF_XMLTYPES_HXX
#include "xmltypes.hxx"
#endif
#ifndef _XMLOFF_FORMENUMS_HXX_
#include "formenums.hxx"
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _XMLOFF_FORMS_CALLBACKS_HXX_
#include "callbacks.hxx"
#endif
#ifndef _XMLOFF_XMLCONSTANTSPROPERTYHANDLER_HXX
#include "XMLConstantsPropertyHandler.hxx"
#endif

//.........................................................................
namespace xmloff
{
//.........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::awt;
    using namespace ::com::sun::star::beans;
    using namespace ::xmloff::token;

    //=====================================================================
    //= OControlPropertyHandlerFactory
    //=====================================================================
    //---------------------------------------------------------------------
    OControlPropertyHandlerFactory::OControlPropertyHandlerFactory()
        :m_pTextAlignHandler(NULL)
        ,m_pControlBorderStyleHandler(NULL)
        ,m_pControlBorderColorHandler(NULL)
        ,m_pRotationAngleHandler(NULL)
        ,m_pFontWidthHandler(NULL)
        ,m_pFontEmphasisHandler(NULL)
        ,m_pFontReliefHandler(NULL)
    {
    }

    //---------------------------------------------------------------------
    OControlPropertyHandlerFactory::~OControlPropertyHandlerFactory()
    {
        delete m_pTextAlignHandler;
        delete m_pControlBorderStyleHandler;
        delete m_pControlBorderColorHandler;
        delete m_pRotationAngleHandler;
        delete m_pFontWidthHandler;
        delete m_pFontEmphasisHandler;
        delete m_pFontReliefHandler;
    }

    //---------------------------------------------------------------------
    const XMLPropertyHandler* OControlPropertyHandlerFactory::GetPropertyHandler(sal_Int32 _nType) const
    {
        const XMLPropertyHandler* pHandler = NULL;

        switch (_nType)
        {
            case XML_TYPE_TEXT_ALIGN:
                if (!m_pTextAlignHandler)
                    m_pTextAlignHandler = new XMLConstantsPropertyHandler(OEnumMapper::getEnumMap(OEnumMapper::epTextAlign), XML_TOKEN_INVALID );
                pHandler = m_pTextAlignHandler;
                break;

            case XML_TYPE_CONTROL_BORDER:
                if (!m_pControlBorderStyleHandler)
                    m_pControlBorderStyleHandler = new OControlBorderStyleHandler;
                pHandler = m_pControlBorderStyleHandler;
                break;

            case XML_TYPE_CONTROL_BORDER_COLOR:
                if ( !m_pControlBorderColorHandler )
                    m_pControlBorderColorHandler = new OControlBorderColorHandler;
                pHandler = m_pControlBorderColorHandler;
                break;

            case XML_TYPE_ROTATION_ANGLE:
                if (!m_pRotationAngleHandler)
                    m_pRotationAngleHandler = new ORotationAngleHandler;
                pHandler = m_pRotationAngleHandler;
                break;

            case XML_TYPE_FONT_WIDTH:
                if (!m_pFontWidthHandler)
                    m_pFontWidthHandler = new OFontWidthHandler;
                pHandler = m_pFontWidthHandler;
                break;

            case XML_TYPE_CONTROL_TEXT_EMPHASIZE:
                if (!m_pFontEmphasisHandler)
                    m_pFontEmphasisHandler = new XMLConstantsPropertyHandler( OEnumMapper::getEnumMap(OEnumMapper::epFontEmphasis), XML_NONE );
                pHandler = m_pFontEmphasisHandler;
                break;

            case XML_TYPE_TEXT_FONT_RELIEF:
                if (!m_pFontReliefHandler)
                    m_pFontReliefHandler = new XMLConstantsPropertyHandler( OEnumMapper::getEnumMap(OEnumMapper::epFontRelief), XML_NONE );
                pHandler = m_pFontReliefHandler;
                break;
        }

        if (!pHandler)
            pHandler = XMLPropertyHandlerFactory::GetPropertyHandler(_nType);
        return pHandler;
    }

    //=====================================================================
    //= OControlTextEmphasisHandler
    //=====================================================================
    OControlTextEmphasisHandler::OControlTextEmphasisHandler()
    {
    }

    //---------------------------------------------------------------------
    sal_Bool OControlTextEmphasisHandler::exportXML( ::rtl::OUString& _rStrExpValue, const Any& _rValue, const SvXMLUnitConverter& ) const
    {
        ::rtl::OUStringBuffer aReturn;
        sal_Bool bSuccess = sal_False;
        sal_Int16 nFontEmphasis = sal_Int16();
        if (_rValue >>= nFontEmphasis)
        {
            // the type
            sal_Int16 nType = nFontEmphasis & ~(FontEmphasisMark::ABOVE | FontEmphasisMark::BELOW);
            // the position of the mark
            sal_Bool bBelow = 0 != (nFontEmphasis & FontEmphasisMark::BELOW);

            // convert
            bSuccess = SvXMLUnitConverter::convertEnum(aReturn, nType, OEnumMapper::getEnumMap(OEnumMapper::epFontEmphasis), XML_NONE);
            if (bSuccess)
            {
                aReturn.append( (sal_Unicode)' ' );
                aReturn.append( GetXMLToken(bBelow ? XML_BELOW : XML_ABOVE) );

                _rStrExpValue = aReturn.makeStringAndClear();
            }
        }

        return bSuccess;
    }

    //---------------------------------------------------------------------
    sal_Bool OControlTextEmphasisHandler::importXML( const ::rtl::OUString& _rStrImpValue, Any& _rValue, const SvXMLUnitConverter& ) const
    {
        sal_Bool bSuccess = sal_True;
        sal_uInt16 nEmphasis = FontEmphasisMark::NONE;

        sal_Bool bBelow = sal_False;
        sal_Bool bHasPos = sal_False, bHasType = sal_False;

        ::rtl::OUString sToken;
        SvXMLTokenEnumerator aTokenEnum(_rStrImpValue);
        while (aTokenEnum.getNextToken(sToken))
        {
            if (!bHasPos)
            {
                if (IsXMLToken(sToken, XML_ABOVE))
                {
                    bBelow = sal_False;
                    bHasPos = sal_True;
                }
                else if (IsXMLToken(sToken, XML_BELOW))
                {
                    bBelow = sal_True;
                    bHasPos = sal_True;
                }
            }
            if (!bHasType)
            {
                if (SvXMLUnitConverter::convertEnum(nEmphasis, sToken, OEnumMapper::getEnumMap(OEnumMapper::epFontEmphasis)))
                {
                    bHasType = sal_True;
                }
                else
                {
                    bSuccess = sal_False;
                    break;
                }
            }
        }

        if (bSuccess)
        {
            nEmphasis |= bBelow ? FontEmphasisMark::BELOW : FontEmphasisMark::ABOVE;
            _rValue <<= (sal_Int16)nEmphasis;
        }

        return bSuccess;
    }

    //=====================================================================
    //= OControlBorderHandlerFactory
    //=====================================================================
    //---------------------------------------------------------------------
    const XMLPropertyHandler* OControlBorderHandlerFactory::createBorderHandler()
    {
        return new OControlBorderStyleHandler;
    }

    //---------------------------------------------------------------------
    const XMLPropertyHandler* OControlBorderHandlerFactory::createBorderColorHandler()
    {
        return new OControlBorderColorHandler;
    }

    //=====================================================================
    //= OControlBorderHandlerBase
    //=====================================================================
    //---------------------------------------------------------------------
    OControlBorderHandlerBase::OControlBorderHandlerBase()
    {
    }

    //---------------------------------------------------------------------
    sal_Bool OControlBorderHandlerBase::importXML( const ::rtl::OUString& _rStrImpValue, Any& _rValue, const SvXMLUnitConverter& ) const
    {
        ::rtl::OUString sToken;
        SvXMLTokenEnumerator aTokens(_rStrImpValue);

        sal_uInt16 nStyle = 1;
        Color aColor;

        sal_Bool bFoundStyle = sal_False;
        sal_Bool bFoundColor = sal_False;

        while   (   !( bFoundStyle && bFoundColor ) // did not yet find both aspects
                &&  aTokens.getNextToken(sToken)    // have a new token
                &&  (0 != sToken.getLength())       // really have a new token
                )
        {
            // is it a valid enum value?
            if ( !bFoundStyle )
                bFoundStyle = SvXMLUnitConverter::convertEnum(nStyle, sToken, OEnumMapper::getEnumMap(OEnumMapper::epBorderWidth));
            // is it a color value?
            if ( !bFoundColor )
                bFoundColor = SvXMLUnitConverter::convertColor( aColor, sToken );
        }

        if ( !bFoundStyle && !bFoundColor )
            return sal_False;

        // if we're here, the string could have had more or less than the requested 3 tokens, but we ignore this.
        // At least we have a valid style or a valid, which is everything we're interested in.
        pickOne( aColor, (sal_Int16)nStyle, _rValue );
        return sal_True;
    }

    //=====================================================================
    //= OControlBorderStyleHandler
    //=====================================================================
    //---------------------------------------------------------------------
    OControlBorderStyleHandler::OControlBorderStyleHandler()
    {
    }

    //---------------------------------------------------------------------
    sal_Bool OControlBorderStyleHandler::exportXML( ::rtl::OUString& _rStrExpValue, const Any& _rValue, const SvXMLUnitConverter& ) const
    {
        sal_Bool bSuccess = sal_False;
        sal_Int16 nBorder = 0;

        ::rtl::OUStringBuffer aOut;
        bSuccess =  (_rValue >>= nBorder)
                &&  SvXMLUnitConverter::convertEnum(aOut, nBorder, OEnumMapper::getEnumMap(OEnumMapper::epBorderWidth));

        if ( _rStrExpValue.getLength() )
            _rStrExpValue += ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( " " ) );
        _rStrExpValue += aOut.makeStringAndClear();
        return bSuccess;
    }

    //---------------------------------------------------------------------
    void OControlBorderStyleHandler::pickOne( const Color&, sal_Int16 _nStyle, Any& _rValue ) const
    {
        _rValue <<= _nStyle;
    }

    //=====================================================================
    //= OControlBorderColorHandler
    //=====================================================================
    //---------------------------------------------------------------------
    OControlBorderColorHandler::OControlBorderColorHandler()
    {
    }

    //---------------------------------------------------------------------
    sal_Bool OControlBorderColorHandler::exportXML( ::rtl::OUString& _rStrExpValue, const Any& _rValue, const SvXMLUnitConverter& ) const
    {
        sal_Bool bSuccess = sal_False;
        sal_Int32 nBorderColor = 0;

        ::rtl::OUStringBuffer aOut;
        if ( _rValue >>= nBorderColor )
        {
            SvXMLUnitConverter::convertColor( aOut, Color( nBorderColor ) );
            bSuccess = sal_True;
        }

        if ( _rStrExpValue.getLength() )
            _rStrExpValue += ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( " " ) );
        _rStrExpValue += aOut.makeStringAndClear();
        return bSuccess;
    }

    //---------------------------------------------------------------------
    void OControlBorderColorHandler::pickOne( const Color& _rColor, sal_Int16 /*_nStyle*/, Any& _rValue ) const
    {
        _rValue <<= (sal_Int32)_rColor.GetColor();
    }

    //=====================================================================
    //= OFontWidthHandler
    //=====================================================================
    //---------------------------------------------------------------------
    OFontWidthHandler::OFontWidthHandler()
    {
    }

    //---------------------------------------------------------------------
    sal_Bool OFontWidthHandler::importXML( const ::rtl::OUString& _rStrImpValue, Any& _rValue, const SvXMLUnitConverter& ) const
    {
        sal_Int32 nWidth = 0;
        sal_Bool bSuccess = SvXMLUnitConverter::convertMeasure(nWidth, _rStrImpValue, MAP_POINT);
        if (bSuccess)
            _rValue <<= (sal_Int16)nWidth;

        return bSuccess;
    }

    //---------------------------------------------------------------------
    sal_Bool OFontWidthHandler::exportXML( ::rtl::OUString& _rStrExpValue, const Any& _rValue, const SvXMLUnitConverter& ) const
    {
        sal_Int16 nWidth = 0;
        ::rtl::OUStringBuffer aResult;
        if (_rValue >>= nWidth)
            SvXMLUnitConverter::convertMeasure(aResult, nWidth, MAP_POINT, MAP_POINT);
        _rStrExpValue = aResult.makeStringAndClear();

        return _rStrExpValue.getLength() != 0;
    }

    //=====================================================================
    //= ORotationAngleHandler
    //=====================================================================
    //---------------------------------------------------------------------
    ORotationAngleHandler::ORotationAngleHandler()
    {
    }

    //---------------------------------------------------------------------
    sal_Bool ORotationAngleHandler::importXML( const ::rtl::OUString& _rStrImpValue, Any& _rValue, const SvXMLUnitConverter& ) const
    {
        double fValue;
        sal_Bool bSucces =
            SvXMLUnitConverter::convertDouble(fValue, _rStrImpValue);
        if (bSucces)
        {
            fValue *= 10;
            _rValue <<= (float)fValue;
        }

        return bSucces;
    }

    //---------------------------------------------------------------------
    sal_Bool ORotationAngleHandler::exportXML( ::rtl::OUString& _rStrExpValue, const Any& _rValue, const SvXMLUnitConverter& ) const
    {
        float fAngle = 0;
        sal_Bool bSuccess = (_rValue >>= fAngle);

        if (bSuccess)
        {
            rtl::OUStringBuffer sValue;
            SvXMLUnitConverter::convertDouble(sValue, ((double)fAngle) / 10);
            _rStrExpValue = sValue.makeStringAndClear();
        }

        return bSuccess;
    }

//.........................................................................
}   // namespace xmloff
//.........................................................................

<|endoftext|>