<commit_before>/**
 * \file
 *
 * \date   9 Aug 2011
 * \author Ben Gray (\@benjamg)
 */

#ifndef ZMQPP_SOCKET_HPP_
#define ZMQPP_SOCKET_HPP_

#include <string>
#include <list>

#include <zmq.h>

#include "compatibility.hpp"

#include "socket_types.hpp"
#include "socket_options.hpp"

namespace zmqpp
{

class context;
class message;

typedef std::string endpoint_t;
typedef context     context_t;
typedef message     message_t;

/*!
 * The socket class represents the zmq sockets.
 *
 * A socket can be bound and/or connected to as many endpoints as required
 * with the sole exception of a ::pair socket.
 *
 * The routing is handled by zmq based on the type set.
 *
 * The bound side of an inproc connection must occur first and inproc can only
 * connect to other inproc sockets of the same context.
 *
 * This class is c++0x move supporting and cannot be copied.
 */
class socket
{
public:
	static const int NORMAL     = 0;            /*!< /brief default send type, no flags set */
	static const int DONT_WAIT  = ZMQ_DONTWAIT; /*!< /brief don't block if sending is not currently possible  */
	static const int SEND_MORE  = ZMQ_SNDMORE;  /*!< /brief more parts will follow this one */
	static const int SEND_LABEL = ZMQ_SNDLABEL; /*!< /brief this message part is an internal zmq label */

	/*!
	 * Create a socket for a given type.
	 *
	 * \param context the zmq context under which the socket will live
	 * \param type a valid ::socket_type for the socket
	 */
	socket(context_t const& context, socket_type const& type);

	/*!
	 * This will close any socket still open before returning
	 */
	~socket();

	/*!
	 * Asynchronously binds to an endpoint.
	 *
	 * \param endpoint the zmq endpoint to bind to
	 */
	void bind(endpoint_t const& endpoint);

	/*!
	 * Asynchronously connects to an endpoint.
	 * If the endpoint is not inproc then zmq will happily keep trying
	 * to connect until there is something there.
	 *
	 * Inproc sockets must have a valid target already bound before connection
	 * will work.
	 *
	 * \param endpoint the zmq endpoint to connect to
	 */
	void connect(endpoint_t const& endpoint);

	/*!
	 * Closes the internal zmq socket and marks this instance
	 * as invalid.
	 */
	void close();

	/*!
	 * Sends the message over the connection, this may be a multipart message.
	 *
	 * If dont_block is true and we are unable to add a new message then this
	 * function will return false.
	 *
	 * \param message message to send
	 * \param dont_block boolean to dictate if we wait while sending.
	 * \return true if message sent, false if it would have blocked
	 */
	bool send(message_t& message, bool const& dont_block = false);

	/*!
	 * Gets a message from the connection, this may be a multipart message.
	 *
	 * If dont_block is true and we are unable to get a message then this
	 * function will return false.
	 *
	 * \param message reference to fill with received data
	 * \param dont_block boolean to dictate if we wait for data.
	 * \return true if message sent, false if it would have blocked
	 */
	bool receive(message_t& message, bool const& dont_block = false);

	/*!
	 * Sends the byte data held by the string as the next message part.
	 *
	 * If the socket::DONT_WAIT flag and we are unable to add a new message to
	 * socket then this function will return false.
	 *
	 * \param string message part to send
	 * \param flags message send flags
	 * \return true if message part sent, false if it would have blocked
	 */
	bool send(std::string const& string, int const& flags = NORMAL);

	/*!
	 * If there is a message ready then get the next part as a string
	 *
	 * If the socket::DONT_WAIT flag and there is no message ready to receive
	 * then this function will return false.
	 *
	 * \param string message part to receive into
	 * \param flags message receive flags
	 * \return true if message part received, false if it would have blocked
	 */
	bool receive(std::string& string, int const& flags = NORMAL);

	/*!
	 * Sends the byte data pointed to by buffer as the next part of the message.
	 *
	 * If the socket::DONT_WAIT flag and we are unable to add a new message to
	 * socket then this function will return false.
	 *
	 * \param buffer byte buffer pointer to start writing from
	 * \param length max length of the buffer
	 * \param flags message send flags
	 * \return true if message part sent, false if it would have blocked
	 */
	bool send_raw(char const* buffer, int const& length, int const& flags = NORMAL);

	/*!
	 * \warning If the buffer is not large enough for the message part then the
	 *       data will be truncated. The rest of the part is lost forever.
	 *
	 * If there is a message ready then get the next part of it as a raw
	 * byte buffer.
	 *
	 * If the socket::DONT_WAIT flag and there is no message ready to receive
	 * then this function will return false.
	 *
	 * \param buffer byte buffer pointer to start writing to
	 * \param length max length of the buffer
	 * \param flags message receive flags
	 * \return true if message part received, false if it would have blocked
	 */
	bool receive_raw(char* buffer, int& length, int const& flags = NORMAL);

	/*!
	 * Subscribe to a topic
	 *
	 * Helper function that is equivalent of calling
	 * \code
	 * set(zmqpp::socket_option::subscribe, topic);
	 * \endcode
	 *
	 * This method is only useful for subscribe type sockets.
	 *
	 * \param topic the topic to subscribe to.
	 */
	void subscribe(std::string const& topic);

	/*!
	 * Unsubscribe from a topic
	 *
	 * Helper function that is equivalent of calling
	 * \code
	 * set(zmqpp::socket_option::unsubscribe, topic);
	 * \endcode
	 *
	 * This method is only useful for subscribe type sockets.
	 *
	 * \param topic the topic to subscribe to.
	 */
	void unsubscribe(std::string const& topic);

	/*!
	 * If the last receive part call to the socket resulted
	 * in a label or a non-terminating part of a multipart
	 * message this will return true.
	 *
	 * \return true if there are more parts
	 */
	bool has_more_parts();

	/*!
	 * Set the value of an option in the underlaying zmq socket.
	 *
	 * \param option a valid ::socket_option
	 * \param value to set the option to
	 */
	void set(socket_option const& option, int const& value);

	/*!
	 * Set the value of an option in the underlaying zmq socket.
	 *
	 * \param option a valid ::socket_option
	 * \param value to set the option to
	 */
	void set(socket_option const& option, uint64_t const& value);

	/*!
	 * Set the value of an option in the underlaying zmq socket.
	 *
	 * \param option a valid ::socket_option
	 * \param value to set the option to
	 */
	void set(socket_option const& option, std::string const& value);

	/*!
	 * Get a socket option from the underlaying zmq socket.
	 *
	 * \param option a valid ::socket_option
	 * \param value referenced int to return value in
	 */
	void get(socket_option const& option, int& value) const;

	/*!
	 * Get a socket option from the underlaying zmq socket.
	 *
	 * \param option a valid ::socket_option
	 * \param value referenced bool to return value in
	 */
	void get(socket_option const& option, bool& value) const;

	/*!
	 * Get a socket option from the underlaying zmq socket.
	 *
	 * \param option a valid ::socket_option
	 * \param value referenced uint64_t to return value in
	 */
	void get(socket_option const& option, uint64_t& value) const;

	/*!
	 * Get a socket option from the underlaying zmq socket.
	 *
	 * \param option a valid ::socket_option
	 * \param value referenced std::string to return value in
	 */
	void get(socket_option const& option, std::string& value) const;

	/*!
	 * For those that don't want to get into a referenced value this templated method
	 * will return the value instead.
	 *
	 * \param option a valid ::socket_option
	 * \return socket option value
	 */
	template<typename Type>
	Type get(socket_option const& option) const
	{
		Type value;
		get(option, value);
		return value;
	}

	/*!
	 * Move constructor
	 *
	 * Moves the internals of source to this object, there is no guaranty
	 * that source will be left in a valid state.
	 *
	 * This constructor is noexcept and so will not throw exceptions
	 *
	 * \param source target socket to steal internals from
	 */
	socket(socket&& source) noexcept;

	/*!
	 * Move operator
	 *
	 * Moves the internals of source to this object, there is no guaranty
	 * that source will be left in a valid state.
	 *
	 * This function is noexcept and so will not throw exceptions
	 *
	 * \param source target socket to steal internals from
	 * \return socket reference to this
	 */
	socket& operator=(socket&& source) noexcept;

	/*!
	 * Check the socket is still valid
	 *
	 * This tests the internal state of the socket.
	 * If creation failed for some reason or if the move functions were used
	 * to move the socket internals to another instance this will return false.
	 *
	 * \return true if the socket is valid
	 */
	operator bool() const;

	/*!
	 * Access to the raw 0mq context
	 *
	 * \return void pointer to the underlying 0mq socket
	 */
	operator void*() const;

private:
	void* _socket;
	socket_type _type;
	zmq_msg_t _recv_buffer;

	// No copy
	socket(socket const&) noexcept;
	socket& operator=(socket const&) noexcept;

	void track_message(message_t const&, uint32_t const&, bool&);
};

}

#endif /* ZMQPP_SOCKET_HPP_ */
<commit_msg>helper for mulitple connects<commit_after>/**
 * \file
 *
 * \date   9 Aug 2011
 * \author Ben Gray (\@benjamg)
 */

#ifndef ZMQPP_SOCKET_HPP_
#define ZMQPP_SOCKET_HPP_

#include <string>
#include <list>

#include <zmq.h>

#include "compatibility.hpp"

#include "socket_types.hpp"
#include "socket_options.hpp"

namespace zmqpp
{

class context;
class message;

typedef std::string endpoint_t;
typedef context     context_t;
typedef message     message_t;

/*!
 * The socket class represents the zmq sockets.
 *
 * A socket can be bound and/or connected to as many endpoints as required
 * with the sole exception of a ::pair socket.
 *
 * The routing is handled by zmq based on the type set.
 *
 * The bound side of an inproc connection must occur first and inproc can only
 * connect to other inproc sockets of the same context.
 *
 * This class is c++0x move supporting and cannot be copied.
 */
class socket
{
public:
	static const int NORMAL     = 0;            /*!< /brief default send type, no flags set */
	static const int DONT_WAIT  = ZMQ_DONTWAIT; /*!< /brief don't block if sending is not currently possible  */
	static const int SEND_MORE  = ZMQ_SNDMORE;  /*!< /brief more parts will follow this one */
	static const int SEND_LABEL = ZMQ_SNDLABEL; /*!< /brief this message part is an internal zmq label */

	/*!
	 * Create a socket for a given type.
	 *
	 * \param context the zmq context under which the socket will live
	 * \param type a valid ::socket_type for the socket
	 */
	socket(context_t const& context, socket_type const& type);

	/*!
	 * This will close any socket still open before returning
	 */
	~socket();

	/*!
	 * Asynchronously binds to an endpoint.
	 *
	 * \param endpoint the zmq endpoint to bind to
	 */
	void bind(endpoint_t const& endpoint);

	/*!
	 * Asynchronously connects to an endpoint.
	 * If the endpoint is not inproc then zmq will happily keep trying
	 * to connect until there is something there.
	 *
	 * Inproc sockets must have a valid target already bound before connection
	 * will work.
	 *
	 * \param endpoint the zmq endpoint to connect to
	 */
	void connect(endpoint_t const& endpoint);

	/*!
	 * Asynchronously connects to multiple endpoints.
	 * If the endpoint is not inproc then zmq will happily keep trying
	 * to connect until there is something there.
	 *
	 * Inproc sockets must have a valid target already bound before connection
	 * will work.
	 *
	 * This is a helper function that wraps the single item connect in a loop
	 *
	 * \param iteratorable the container of zmq endpoints to connect to
	 */
	template<typename Iteratorable>
	void connect(Iteratorable const& iteratorable)
	{
		for(auto it = iteratorable.begin(); it != iteratorable.end(); ++it)
		{
			connect(*it);
		}
	}

	/*!
	 * Closes the internal zmq socket and marks this instance
	 * as invalid.
	 */
	void close();

	/*!
	 * Sends the message over the connection, this may be a multipart message.
	 *
	 * If dont_block is true and we are unable to add a new message then this
	 * function will return false.
	 *
	 * \param message message to send
	 * \param dont_block boolean to dictate if we wait while sending.
	 * \return true if message sent, false if it would have blocked
	 */
	bool send(message_t& message, bool const& dont_block = false);

	/*!
	 * Gets a message from the connection, this may be a multipart message.
	 *
	 * If dont_block is true and we are unable to get a message then this
	 * function will return false.
	 *
	 * \param message reference to fill with received data
	 * \param dont_block boolean to dictate if we wait for data.
	 * \return true if message sent, false if it would have blocked
	 */
	bool receive(message_t& message, bool const& dont_block = false);

	/*!
	 * Sends the byte data held by the string as the next message part.
	 *
	 * If the socket::DONT_WAIT flag and we are unable to add a new message to
	 * socket then this function will return false.
	 *
	 * \param string message part to send
	 * \param flags message send flags
	 * \return true if message part sent, false if it would have blocked
	 */
	bool send(std::string const& string, int const& flags = NORMAL);

	/*!
	 * If there is a message ready then get the next part as a string
	 *
	 * If the socket::DONT_WAIT flag and there is no message ready to receive
	 * then this function will return false.
	 *
	 * \param string message part to receive into
	 * \param flags message receive flags
	 * \return true if message part received, false if it would have blocked
	 */
	bool receive(std::string& string, int const& flags = NORMAL);

	/*!
	 * Sends the byte data pointed to by buffer as the next part of the message.
	 *
	 * If the socket::DONT_WAIT flag and we are unable to add a new message to
	 * socket then this function will return false.
	 *
	 * \param buffer byte buffer pointer to start writing from
	 * \param length max length of the buffer
	 * \param flags message send flags
	 * \return true if message part sent, false if it would have blocked
	 */
	bool send_raw(char const* buffer, int const& length, int const& flags = NORMAL);

	/*!
	 * \warning If the buffer is not large enough for the message part then the
	 *       data will be truncated. The rest of the part is lost forever.
	 *
	 * If there is a message ready then get the next part of it as a raw
	 * byte buffer.
	 *
	 * If the socket::DONT_WAIT flag and there is no message ready to receive
	 * then this function will return false.
	 *
	 * \param buffer byte buffer pointer to start writing to
	 * \param length max length of the buffer
	 * \param flags message receive flags
	 * \return true if message part received, false if it would have blocked
	 */
	bool receive_raw(char* buffer, int& length, int const& flags = NORMAL);

	/*!
	 * Subscribe to a topic
	 *
	 * Helper function that is equivalent of calling
	 * \code
	 * set(zmqpp::socket_option::subscribe, topic);
	 * \endcode
	 *
	 * This method is only useful for subscribe type sockets.
	 *
	 * \param topic the topic to subscribe to.
	 */
	void subscribe(std::string const& topic);

	/*!
	 * Unsubscribe from a topic
	 *
	 * Helper function that is equivalent of calling
	 * \code
	 * set(zmqpp::socket_option::unsubscribe, topic);
	 * \endcode
	 *
	 * This method is only useful for subscribe type sockets.
	 *
	 * \param topic the topic to subscribe to.
	 */
	void unsubscribe(std::string const& topic);

	/*!
	 * If the last receive part call to the socket resulted
	 * in a label or a non-terminating part of a multipart
	 * message this will return true.
	 *
	 * \return true if there are more parts
	 */
	bool has_more_parts();

	/*!
	 * Set the value of an option in the underlaying zmq socket.
	 *
	 * \param option a valid ::socket_option
	 * \param value to set the option to
	 */
	void set(socket_option const& option, int const& value);

	/*!
	 * Set the value of an option in the underlaying zmq socket.
	 *
	 * \param option a valid ::socket_option
	 * \param value to set the option to
	 */
	void set(socket_option const& option, uint64_t const& value);

	/*!
	 * Set the value of an option in the underlaying zmq socket.
	 *
	 * \param option a valid ::socket_option
	 * \param value to set the option to
	 */
	void set(socket_option const& option, std::string const& value);

	/*!
	 * Get a socket option from the underlaying zmq socket.
	 *
	 * \param option a valid ::socket_option
	 * \param value referenced int to return value in
	 */
	void get(socket_option const& option, int& value) const;

	/*!
	 * Get a socket option from the underlaying zmq socket.
	 *
	 * \param option a valid ::socket_option
	 * \param value referenced bool to return value in
	 */
	void get(socket_option const& option, bool& value) const;

	/*!
	 * Get a socket option from the underlaying zmq socket.
	 *
	 * \param option a valid ::socket_option
	 * \param value referenced uint64_t to return value in
	 */
	void get(socket_option const& option, uint64_t& value) const;

	/*!
	 * Get a socket option from the underlaying zmq socket.
	 *
	 * \param option a valid ::socket_option
	 * \param value referenced std::string to return value in
	 */
	void get(socket_option const& option, std::string& value) const;

	/*!
	 * For those that don't want to get into a referenced value this templated method
	 * will return the value instead.
	 *
	 * \param option a valid ::socket_option
	 * \return socket option value
	 */
	template<typename Type>
	Type get(socket_option const& option) const
	{
		Type value;
		get(option, value);
		return value;
	}

	/*!
	 * Move constructor
	 *
	 * Moves the internals of source to this object, there is no guaranty
	 * that source will be left in a valid state.
	 *
	 * This constructor is noexcept and so will not throw exceptions
	 *
	 * \param source target socket to steal internals from
	 */
	socket(socket&& source) noexcept;

	/*!
	 * Move operator
	 *
	 * Moves the internals of source to this object, there is no guaranty
	 * that source will be left in a valid state.
	 *
	 * This function is noexcept and so will not throw exceptions
	 *
	 * \param source target socket to steal internals from
	 * \return socket reference to this
	 */
	socket& operator=(socket&& source) noexcept;

	/*!
	 * Check the socket is still valid
	 *
	 * This tests the internal state of the socket.
	 * If creation failed for some reason or if the move functions were used
	 * to move the socket internals to another instance this will return false.
	 *
	 * \return true if the socket is valid
	 */
	operator bool() const;

	/*!
	 * Access to the raw 0mq context
	 *
	 * \return void pointer to the underlying 0mq socket
	 */
	operator void*() const;

private:
	void* _socket;
	socket_type _type;
	zmq_msg_t _recv_buffer;

	// No copy
	socket(socket const&) noexcept;
	socket& operator=(socket const&) noexcept;

	void track_message(message_t const&, uint32_t const&, bool&);
};

}

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


<commit_before><commit_msg>Update rest.cpp<commit_after><|endoftext|>


<commit_before><commit_msg>send.cppを追加<commit_after><|endoftext|>


<commit_before><commit_msg>made cas default<commit_after><|endoftext|>


<commit_before><commit_msg>Only kill on apple<commit_after><|endoftext|>


<commit_before>#include <nano/lib/rpc_handler_interface.hpp>
#include <nano/rpc/rpc.hpp>
#include <nano/rpc/rpc_connection.hpp>

#include <boost/format.hpp>

#ifdef NANO_SECURE_RPC
#include <nano/rpc/rpc_secure.hpp>
#endif

nano::rpc::rpc (boost::asio::io_context & io_ctx_a, nano::rpc_config const & config_a, nano::rpc_handler_interface & rpc_handler_interface_a) :
config (config_a),
acceptor (io_ctx_a),
logger (std::chrono::milliseconds (0)),
io_ctx (io_ctx_a),
rpc_handler_interface (rpc_handler_interface_a)
{
	rpc_handler_interface.rpc_instance (*this);
}

nano::rpc::~rpc ()
{
	if (!stopped)
	{
		stop ();
	}
}

void nano::rpc::start ()
{
	auto endpoint (boost::asio::ip::tcp::endpoint (config.address, config.port));
	acceptor.open (endpoint.protocol ());
	acceptor.set_option (boost::asio::ip::tcp::acceptor::reuse_address (true));

	boost::system::error_code ec;
	acceptor.bind (endpoint, ec);
	if (ec)
	{
		logger.always_log (boost::str (boost::format ("Error while binding for RPC on port %1%: %2%") % endpoint.port () % ec.message ()));
		throw std::runtime_error (ec.message ());
	}
	acceptor.listen ();
	accept ();
}

void nano::rpc::accept ()
{
	auto connection (std::make_shared<nano::rpc_connection> (config, io_ctx, logger, rpc_handler_interface));
	acceptor.async_accept (connection->socket, boost::asio::bind_executor (connection->strand, [this, connection](boost::system::error_code const & ec) {
		if (ec != boost::asio::error::operation_aborted && acceptor.is_open ())
		{
			accept ();
		}
		if (!ec)
		{
			connection->parse_connection ();
		}
		else
		{
			logger.always_log (boost::str (boost::format ("Error accepting RPC connections: %1% (%2%)") % ec.message () % ec.value ()));
		}
	}));
}

void nano::rpc::stop ()
{
	stopped = true;
	acceptor.close ();
}

std::unique_ptr<nano::rpc> nano::get_rpc (boost::asio::io_context & io_ctx_a, nano::rpc_config const & config_a, nano::rpc_handler_interface & rpc_handler_interface_a)
{
	std::unique_ptr<rpc> impl;

	if (config_a.secure.enable)
	{
#ifdef NANO_SECURE_RPC
		impl = std::make_unique<rpc_secure> (io_ctx_a, config_a, rpc_handler_interface_a);
#else
		std::cerr << "RPC configured for TLS, but the node is not compiled with TLS support" << std::endl;
#endif
	}
	else
	{
		impl = std::make_unique<rpc> (io_ctx_a, config_a, rpc_handler_interface_a);
	}

	return impl;
}
<commit_msg>Warn if control is enabled with non-local bind address (#2401)<commit_after>#include <nano/lib/rpc_handler_interface.hpp>
#include <nano/rpc/rpc.hpp>
#include <nano/rpc/rpc_connection.hpp>

#include <boost/format.hpp>

#ifdef NANO_SECURE_RPC
#include <nano/rpc/rpc_secure.hpp>
#endif

nano::rpc::rpc (boost::asio::io_context & io_ctx_a, nano::rpc_config const & config_a, nano::rpc_handler_interface & rpc_handler_interface_a) :
config (config_a),
acceptor (io_ctx_a),
logger (std::chrono::milliseconds (0)),
io_ctx (io_ctx_a),
rpc_handler_interface (rpc_handler_interface_a)
{
	rpc_handler_interface.rpc_instance (*this);
}

nano::rpc::~rpc ()
{
	if (!stopped)
	{
		stop ();
	}
}

void nano::rpc::start ()
{
	auto endpoint (boost::asio::ip::tcp::endpoint (config.address, config.port));
	if (!endpoint.address ().is_loopback () && config.enable_control)
	{
		auto warning = boost::str (boost::format ("WARNING: control-level RPCs are enabled on non-local address %1%, potentially allowing wallet access outside local computer") % endpoint.address ().to_string ());
		std::cout << warning << std::endl;
		logger.always_log (warning);
	}
	acceptor.open (endpoint.protocol ());
	acceptor.set_option (boost::asio::ip::tcp::acceptor::reuse_address (true));

	boost::system::error_code ec;
	acceptor.bind (endpoint, ec);
	if (ec)
	{
		logger.always_log (boost::str (boost::format ("Error while binding for RPC on port %1%: %2%") % endpoint.port () % ec.message ()));
		throw std::runtime_error (ec.message ());
	}
	acceptor.listen ();
	accept ();
}

void nano::rpc::accept ()
{
	auto connection (std::make_shared<nano::rpc_connection> (config, io_ctx, logger, rpc_handler_interface));
	acceptor.async_accept (connection->socket, boost::asio::bind_executor (connection->strand, [this, connection](boost::system::error_code const & ec) {
		if (ec != boost::asio::error::operation_aborted && acceptor.is_open ())
		{
			accept ();
		}
		if (!ec)
		{
			connection->parse_connection ();
		}
		else
		{
			logger.always_log (boost::str (boost::format ("Error accepting RPC connections: %1% (%2%)") % ec.message () % ec.value ()));
		}
	}));
}

void nano::rpc::stop ()
{
	stopped = true;
	acceptor.close ();
}

std::unique_ptr<nano::rpc> nano::get_rpc (boost::asio::io_context & io_ctx_a, nano::rpc_config const & config_a, nano::rpc_handler_interface & rpc_handler_interface_a)
{
	std::unique_ptr<rpc> impl;

	if (config_a.secure.enable)
	{
#ifdef NANO_SECURE_RPC
		impl = std::make_unique<rpc_secure> (io_ctx_a, config_a, rpc_handler_interface_a);
#else
		std::cerr << "RPC configured for TLS, but the node is not compiled with TLS support" << std::endl;
#endif
	}
	else
	{
		impl = std::make_unique<rpc> (io_ctx_a, config_a, rpc_handler_interface_a);
	}

	return impl;
}
<|endoftext|>


<commit_before>#include "hudview.h"

// osg
#include <osgUtil/Optimizer>
#include <osgText/Text>
#include <osg/Material>
#include <osg/Geode>
#include <osg/BlendFunc>
#include <osg/Depth>
#include <osg/PolygonOffset>
#include <osg/MatrixTransform>
//#include <osg/Camera>
#include <osg/RenderInfo>
#include <osgText/Text>
#include <osgViewer/ViewerEventHandlers>
#include <osgViewer/View>
#include <osgGA/NodeTrackerManipulator>
#include <osg/Quat>
// troen
#include "../constants.h"

using namespace troen;

HUDView::HUDView(): m_trackNode(nullptr)
{
	AbstractView();
	m_speedText = new osgText::Text();
	m_healthText = new osgText::Text();
	m_pointsText = new osgText::Text();

	m_node = new osg::Group();

	m_node->addChild(createHUD());
	m_node->addChild(createRadar());
}

osg::Camera* HUDView::createHUD()
{
	// create a camera to set up the projection and model view matrices, and the subgraph to draw in the HUD
	m_camera = new osg::Camera;

	// set the projection matrix
	m_camera->setProjectionMatrix(osg::Matrix::ortho2D(0, DEFAULT_WINDOW_HEIGHT, 0, DEFAULT_WINDOW_WIDTH));
	m_camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
	m_camera->setViewMatrix(osg::Matrix::identity());
	m_camera->setClearMask(GL_DEPTH_BUFFER_BIT);
	// draw subgraph after main camera view.
	m_camera->setRenderOrder(osg::Camera::POST_RENDER);
	m_camera->setAllowEventFocus(false);

	{
		osg::Geode* geode = new osg::Geode();
		m_savedGeode = geode;

		osgText::Font *timesFont = osgText::readFontFile("fonts/arial.ttf");

		// turn lighting off for the text and disable depth test to ensure it's always ontop.
		osg::StateSet* stateset = geode->getOrCreateStateSet();
		stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF);

		osg::Vec3 position(500.f, 0, 0);
		osg::Vec3 delta(0.0f, -100.0f, 0.0f);

		{
			geode->addDrawable(m_speedText);

			m_speedText->setFont(timesFont);
			m_speedText->setPosition(position);
			setSpeedText(80);
			// m_speedText->setAlignment(osgText::Text::AlignmentType::RIGHT_BOTTOM);

			position += delta;
		}
		{
			geode->addDrawable(m_healthText);

			m_healthText->setFont(timesFont);
			m_healthText->setPosition(osg::Vec3(0.f, 0.f, 0.f));
			setHealthText(100);
			// m_speedText->setAlignment(osgText::Text::AlignmentType::RIGHT_BOTTOM);

			position += delta;
		}
		{
			geode->addDrawable(m_pointsText);

			m_pointsText->setFont(timesFont);
			m_pointsText->setPosition(osg::Vec3(0.f, 900.f, 0.f));
			setPointsText(0);
			// m_speedText->setAlignment(osgText::Text::AlignmentType::RIGHT_BOTTOM);

			position += delta;
		}

		{
			//osg::BoundingBox bb;
			//for (unsigned int i = 0; i<geode->getNumDrawables(); ++i)
			//{
			//	bb.expandBy(geode->getDrawable(i)->getBound());
			//}

			//osg::Geometry* geom = new osg::Geometry;

			//osg::Vec3Array* vertices = new osg::Vec3Array;
			//float depth = bb.zMin() - 0.1;
			//vertices->push_back(osg::Vec3(bb.xMin(), bb.yMax(), depth));
			//vertices->push_back(osg::Vec3(bb.xMin(), bb.yMin(), depth));
			//vertices->push_back(osg::Vec3(bb.xMax(), bb.yMin(), depth));
			//vertices->push_back(osg::Vec3(bb.xMax(), bb.yMax(), depth));
			//geom->setVertexArray(vertices);

			//osg::Vec3Array* normals = new osg::Vec3Array;
			//normals->push_back(osg::Vec3(0.0f, 0.0f, 1.0f));
			//geom->setNormalArray(normals);
			//geom->setNormalBinding(osg::Geometry::BIND_OVERALL);

			//osg::Vec4Array* colors = new osg::Vec4Array;
			//colors->push_back(osg::Vec4(1.0f, 1.0, 0.8f, 0.2f));
			//geom->setColorArray(colors);
			//geom->setColorBinding(osg::Geometry::BIND_OVERALL);

			//geom->addPrimitiveSet(new osg::DrawArrays(GL_QUADS, 0, 4));

			//osg::StateSet* stateset = geom->getOrCreateStateSet();
			//stateset->setMode(GL_BLEND, osg::StateAttribute::ON);
			////stateset->setAttribute(new osg::PolygonOffset(1.0f,1.0f),osg::StateAttribute::ON);
			//stateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);

			//geode->addDrawable(geom);
		}

		m_camera->addChild(geode);
	}

	return m_camera;
}

void HUDView::resize(int width, int height)
{
	m_camera->setViewport(new osg::Viewport(0, 0, width, height));
	int offset = height / 20;
	int size = height / 2.5;
	m_radarCamera->setViewport(new osg::Viewport(offset, offset, size, size));
}

osg::Camera* HUDView::createRadar()
{
	m_radarCamera = new osg::Camera;
	m_radarCamera->setClearColor(osg::Vec4(0.0f, 1.f, 0.0f, .5f));
	m_radarCamera->setRenderOrder(osg::Camera::POST_RENDER);
	m_radarCamera->setAllowEventFocus(false);
	m_radarCamera->setClearMask(GL_DEPTH_BUFFER_BIT);
	m_radarCamera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
	m_radarCamera->setViewport(DEFAULT_WINDOW_HEIGHT / 20, DEFAULT_WINDOW_HEIGHT / 20, DEFAULT_WINDOW_HEIGHT / 2.5, DEFAULT_WINDOW_HEIGHT / 2.5);

	m_radarCamera->setViewMatrix(osg::Matrixd::lookAt(osg::Vec3(0.0f, 0.0f, 500.0f), osg::Vec3(0.f, 0.f, 0.f), osg::Y_AXIS));
	m_radarCamera->setProjectionMatrix(osg::Matrixd::ortho(-3000, 3000, -3000, 3000,1.f,600));
	m_radarCamera->setCullMask(CAMERA_MASK_RADAR);

	return m_radarCamera;
}

void HUDView::attachSceneToRadarCamera(osg::Group* scene)
{
	osg::ref_ptr<osg::Group> hudGroup = new osg::Group;

	osg::StateSet* stateset = hudGroup->getOrCreateStateSet();
	stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
	stateset->setMode(GL_BLEND, osg::StateAttribute::ON);
	stateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);

	hudGroup->addChild(scene);
	m_radarCamera->addChild(hudGroup);
}

// helper class to retrieve the position of a node in world coordinates
// could potentially be in it's own header file
class getWorldCoordOfNodeVisitor : public osg::NodeVisitor
{
public:
    getWorldCoordOfNodeVisitor():
    osg::NodeVisitor(NodeVisitor::TRAVERSE_PARENTS), done(false)
    {
        wcMatrix= new osg::Matrixd();
    }
    virtual void apply(osg::Node &node)
    {
        if (!done)
        {
            if ( 0 == node.getNumParents() ) // no parents
            {
                wcMatrix->set( osg::computeLocalToWorld(this->getNodePath()) );
                done = true;
            }
            traverse(node);
        }
    }
    osg::Matrixd* worldCoordinatesMatrix()
    {
        return wcMatrix;
    }
private:
    bool done;
    osg::Matrix* wcMatrix;
};

void HUDView::updateRadarCamera()
{
        osg::Matrixd* worldCoordinateMatrix = nullptr;
		getWorldCoordOfNodeVisitor ncv;

        ((osg::Group *)m_trackNode)->accept(ncv);
        worldCoordinateMatrix = ncv.worldCoordinatesMatrix();

        osg::Vec3d position = worldCoordinateMatrix->getTrans();
        osg::Quat rotationQuat = worldCoordinateMatrix->getRotate();
		float z = rotationQuat.z();
		float w = rotationQuat.w();
        float mag = sqrt(w*w + z*z);
        rotationQuat.set(0, 0, z/mag, w/mag);

        osg::Vec3 up = rotationQuat * osg::Y_AXIS;

        osg::Matrixd viewMatrix = osg::Matrixd::lookAt(osg::Vec3(position.x(), position.y(), 500.0f), osg::Vec3(position.x(), position.y(), 0.f), up);
        m_radarCamera->setViewMatrix(viewMatrix);
}

void HUDView::setTrackNode(osg::Node* trackNode)
{
    m_trackNode = trackNode;
}

void HUDView::setSpeedText(float speed)
{
	std::string speedString = std::to_string((int) speed);
	m_speedText->setText("Speed: " + speedString + " km/h");
}

void HUDView::setHealthText(float health)
{
	std::string healthString = std::to_string((int)health);
	m_healthText->setText("Health: " + healthString);
}

void HUDView::setPointsText(float points)
{
	std::string pointsString = std::to_string((int)points);
	m_pointsText->setText("Points: " + pointsString);
}<commit_msg>troen font working<commit_after>#include "hudview.h"

// osg
#include <osgUtil/Optimizer>
#include <osgText/Text>
#include <osg/Material>
#include <osg/Geode>
#include <osg/BlendFunc>
#include <osg/Depth>
#include <osg/PolygonOffset>
#include <osg/MatrixTransform>
//#include <osg/Camera>
#include <osg/RenderInfo>
#include <osgText/Text>
#include <osgViewer/ViewerEventHandlers>
#include <osgViewer/View>
#include <osgGA/NodeTrackerManipulator>
#include <osg/Quat>
// troen
#include "../constants.h"

using namespace troen;

HUDView::HUDView(): m_trackNode(nullptr)
{
	AbstractView();
	m_speedText = new osgText::Text();
	m_healthText = new osgText::Text();
	m_pointsText = new osgText::Text();

	m_node = new osg::Group();

	m_node->addChild(createHUD());
	m_node->addChild(createRadar());
}

osg::Camera* HUDView::createHUD()
{
	// create a camera to set up the projection and model view matrices, and the subgraph to draw in the HUD
	m_camera = new osg::Camera;

	// set the projection matrix
	m_camera->setProjectionMatrix(osg::Matrix::ortho2D(0, DEFAULT_WINDOW_HEIGHT, 0, DEFAULT_WINDOW_WIDTH));
	m_camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
	m_camera->setViewMatrix(osg::Matrix::identity());
	m_camera->setClearMask(GL_DEPTH_BUFFER_BIT);
	// draw subgraph after main camera view.
	m_camera->setRenderOrder(osg::Camera::POST_RENDER);
	m_camera->setAllowEventFocus(false);

	{
		osg::Geode* geode = new osg::Geode();
		m_savedGeode = geode;

		osgText::Font *timesFont = osgText::readFontFile("data/fonts/tr2n.ttf");

		// turn lighting off for the text and disable depth test to ensure it's always ontop.
		osg::StateSet* stateset = geode->getOrCreateStateSet();
		stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF);

		osg::Vec3 position(500.f, 0, 0);
		osg::Vec3 delta(0.0f, -100.0f, 0.0f);

		{
			geode->addDrawable(m_speedText);

			m_speedText->setFont(timesFont);
			m_speedText->setPosition(position);
			setSpeedText(80);
			// m_speedText->setAlignment(osgText::Text::AlignmentType::RIGHT_BOTTOM);

			position += delta;
		}
		{
			geode->addDrawable(m_healthText);

			m_healthText->setFont(timesFont);
			m_healthText->setPosition(osg::Vec3(0.f, 0.f, 0.f));
			setHealthText(100);
			// m_speedText->setAlignment(osgText::Text::AlignmentType::RIGHT_BOTTOM);

			position += delta;
		}
		{
			geode->addDrawable(m_pointsText);

			m_pointsText->setFont(timesFont);
			m_pointsText->setPosition(osg::Vec3(0.f, 900.f, 0.f));
			setPointsText(0);
			// m_speedText->setAlignment(osgText::Text::AlignmentType::RIGHT_BOTTOM);

			position += delta;
		}

		{
			//osg::BoundingBox bb;
			//for (unsigned int i = 0; i<geode->getNumDrawables(); ++i)
			//{
			//	bb.expandBy(geode->getDrawable(i)->getBound());
			//}

			//osg::Geometry* geom = new osg::Geometry;

			//osg::Vec3Array* vertices = new osg::Vec3Array;
			//float depth = bb.zMin() - 0.1;
			//vertices->push_back(osg::Vec3(bb.xMin(), bb.yMax(), depth));
			//vertices->push_back(osg::Vec3(bb.xMin(), bb.yMin(), depth));
			//vertices->push_back(osg::Vec3(bb.xMax(), bb.yMin(), depth));
			//vertices->push_back(osg::Vec3(bb.xMax(), bb.yMax(), depth));
			//geom->setVertexArray(vertices);

			//osg::Vec3Array* normals = new osg::Vec3Array;
			//normals->push_back(osg::Vec3(0.0f, 0.0f, 1.0f));
			//geom->setNormalArray(normals);
			//geom->setNormalBinding(osg::Geometry::BIND_OVERALL);

			//osg::Vec4Array* colors = new osg::Vec4Array;
			//colors->push_back(osg::Vec4(1.0f, 1.0, 0.8f, 0.2f));
			//geom->setColorArray(colors);
			//geom->setColorBinding(osg::Geometry::BIND_OVERALL);

			//geom->addPrimitiveSet(new osg::DrawArrays(GL_QUADS, 0, 4));

			//osg::StateSet* stateset = geom->getOrCreateStateSet();
			//stateset->setMode(GL_BLEND, osg::StateAttribute::ON);
			////stateset->setAttribute(new osg::PolygonOffset(1.0f,1.0f),osg::StateAttribute::ON);
			//stateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);

			//geode->addDrawable(geom);
		}

		m_camera->addChild(geode);
	}

	return m_camera;
}

void HUDView::resize(int width, int height)
{
	m_camera->setViewport(new osg::Viewport(0, 0, width, height));
	int offset = height / 20;
	int size = height / 2.5;
	m_radarCamera->setViewport(new osg::Viewport(offset, offset, size, size));
}

osg::Camera* HUDView::createRadar()
{
	m_radarCamera = new osg::Camera;
	m_radarCamera->setClearColor(osg::Vec4(0.0f, 1.f, 0.0f, .5f));
	m_radarCamera->setRenderOrder(osg::Camera::POST_RENDER);
	m_radarCamera->setAllowEventFocus(false);
	m_radarCamera->setClearMask(GL_DEPTH_BUFFER_BIT);
	m_radarCamera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
	m_radarCamera->setViewport(DEFAULT_WINDOW_HEIGHT / 20, DEFAULT_WINDOW_HEIGHT / 20, DEFAULT_WINDOW_HEIGHT / 2.5, DEFAULT_WINDOW_HEIGHT / 2.5);

	m_radarCamera->setViewMatrix(osg::Matrixd::lookAt(osg::Vec3(0.0f, 0.0f, 500.0f), osg::Vec3(0.f, 0.f, 0.f), osg::Y_AXIS));
	m_radarCamera->setProjectionMatrix(osg::Matrixd::ortho(-3000, 3000, -3000, 3000,1.f,600));
	m_radarCamera->setCullMask(CAMERA_MASK_RADAR);

	return m_radarCamera;
}

void HUDView::attachSceneToRadarCamera(osg::Group* scene)
{
	osg::ref_ptr<osg::Group> hudGroup = new osg::Group;

	osg::StateSet* stateset = hudGroup->getOrCreateStateSet();
	stateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
	stateset->setMode(GL_BLEND, osg::StateAttribute::ON);
	stateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);

	hudGroup->addChild(scene);
	m_radarCamera->addChild(hudGroup);
}

// helper class to retrieve the position of a node in world coordinates
// could potentially be in it's own header file
class getWorldCoordOfNodeVisitor : public osg::NodeVisitor
{
public:
    getWorldCoordOfNodeVisitor():
    osg::NodeVisitor(NodeVisitor::TRAVERSE_PARENTS), done(false)
    {
        wcMatrix= new osg::Matrixd();
    }
    virtual void apply(osg::Node &node)
    {
        if (!done)
        {
            if ( 0 == node.getNumParents() ) // no parents
            {
                wcMatrix->set( osg::computeLocalToWorld(this->getNodePath()) );
                done = true;
            }
            traverse(node);
        }
    }
    osg::Matrixd* worldCoordinatesMatrix()
    {
        return wcMatrix;
    }
private:
    bool done;
    osg::Matrix* wcMatrix;
};

void HUDView::updateRadarCamera()
{
        osg::Matrixd* worldCoordinateMatrix = nullptr;
		getWorldCoordOfNodeVisitor ncv;

        ((osg::Group *)m_trackNode)->accept(ncv);
        worldCoordinateMatrix = ncv.worldCoordinatesMatrix();

        osg::Vec3d position = worldCoordinateMatrix->getTrans();
        osg::Quat rotationQuat = worldCoordinateMatrix->getRotate();
		float z = rotationQuat.z();
		float w = rotationQuat.w();
        float mag = sqrt(w*w + z*z);
        rotationQuat.set(0, 0, z/mag, w/mag);

        osg::Vec3 up = rotationQuat * osg::Y_AXIS;

        osg::Matrixd viewMatrix = osg::Matrixd::lookAt(osg::Vec3(position.x(), position.y(), 500.0f), osg::Vec3(position.x(), position.y(), 0.f), up);
        m_radarCamera->setViewMatrix(viewMatrix);
}

void HUDView::setTrackNode(osg::Node* trackNode)
{
    m_trackNode = trackNode;
}

void HUDView::setSpeedText(float speed)
{
	std::string speedString = std::to_string((int) speed);
	m_speedText->setText("Speed: " + speedString + " km/h");
}

void HUDView::setHealthText(float health)
{
	std::string healthString = std::to_string((int)health);
	m_healthText->setText("Health: " + healthString);
}

void HUDView::setPointsText(float points)
{
	std::string pointsString = std::to_string((int)points);
	m_pointsText->setText("Points: " + pointsString);
}<|endoftext|>


<commit_before><commit_msg>Rename backup when move destination contained a folder with same name<commit_after><|endoftext|>


<commit_before><commit_msg>fix calls to countRelations<commit_after><|endoftext|>


<commit_before>#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
#include <chrono>
#include <sstream>
#include <cmath>
#include <cstdio>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/msg.h>
#include <unistd.h>

#include "entity.h"
#include "character.h"
#include "monster.h"
#include "spell.h"
#include "item.h"
#include "tile.h"
#include "timetable.h"
#include "mailbox.h"

using namespace std;

//Structure for HTTP form data
struct FormInfo{
	string Key;
	string Value;
};

vector<Tile> Map; //[][]
vector<Enemy> SpawnedEnemies; // []
vector<Character> Players;

//Vector to hold Key / Value pairs after processing
vector<FormInfo> FormData;

void getFormData(string Env);
string GetValueFromKey(string FindKey);

int main(){
	//Setup Game state
	TimeTable TimeTable;
	Mailbox Mailbox;
	bool Done = false;
	string FormData;
	string Action;

	//Load maps

	//Load definitions
	cout << "Beginning main loop\n" << flush;
	cout << "Mailbox: " << Mailbox.SetupSuccessful() << "\n" << flush;
	//Main Loop
	while (!Done){
		FormData.clear();

		//Check Time table.  Perform function for all expired times

		//Check and Process Messages
		FormData = Mailbox.GetNextMessage();
		if (FormData.size() > 5) { cout << FormData; }
		getFormData(FormData);
		Action = GetValueFromKey("Action");

		if (Action == "EnterGame"){
			Character NewChar(GetValueFromKey("u"), GetValueFromKey("c"), stoi(GetValueFromKey("Box")));
			Mailbox.OpenUserBox(NewChar.Box);
			Mailbox.BroadcastMessage("This is a test of the server.");
			Mailbox.SendMessageToBox("Specific User Message", NewChar.Box);
			cout << "Intelligence:" << .GetStat(Intelligence, true);
			Players.push_back(NewChar);
		}

		if (Action == "LeaveGame"){
		}

		if (Action == "Move"){
		}

		if (Action == "CastSpell"){
		}

		if (Action == "EquipItem"){
		}

		if (Action == "UseItem"){
		}

		if (Action == "Attack"){
		}
		//Game in progress action

		//Perform a character action

		//Perform an inventory action

		//Perform a world action

		//Perform targetting action

		//Sleep 10 milliseconds before looping again.

	}

}

string GetValueFromKey(string FindKey){
	for (int i = 0; i < FormData.size(); i++){
		if (!FormData[i].Key.compare(FindKey)){ return FormData[i].Value; }
	}
	return "";
}

void getFormData(string Env){
	int EnvLen = Env.size();
	int Start = 1;
	int Mid = 0;
	FormInfo NewData;

	//Split Key-Value pairs and place in the FormData structure.
	for (int i = 1; i < EnvLen; i++){
	if (Env[i] == '='){Mid = i + 1;}
		if (Env[i] == '&' || i == EnvLen - 1){
			if (i == EnvLen - 1) i++;  //Get last character
			NewData.Key = Env.substr(Start,Mid-Start-1);
			NewData.Value = Env.substr(Mid, i - Mid);
			FormData.push_back(NewData);
			Start = i + 1;
		}
	}
}

<commit_msg>Setting up server-client comms<commit_after>#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
#include <chrono>
#include <sstream>
#include <cmath>
#include <cstdio>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/msg.h>
#include <unistd.h>

#include "entity.h"
#include "character.h"
#include "monster.h"
#include "spell.h"
#include "item.h"
#include "tile.h"
#include "timetable.h"
#include "mailbox.h"

using namespace std;

//Structure for HTTP form data
struct FormInfo{
	string Key;
	string Value;
};

vector<Tile> Map; //[][]
vector<Enemy> SpawnedEnemies; // []
vector<Character> Players;

//Vector to hold Key / Value pairs after processing
vector<FormInfo> FormData;

void getFormData(string Env);
string GetValueFromKey(string FindKey);

int main(){
	//Setup Game state
	TimeTable TimeTable;
	Mailbox Mailbox;
	bool Done = false;
	string FormData;
	string Action;

	//Load maps

	//Load definitions
	cout << "Beginning main loop\n" << flush;
	cout << "Mailbox: " << Mailbox.SetupSuccessful() << "\n" << flush;
	//Main Loop
	while (!Done){
		FormData.clear();

		//Check Time table.  Perform function for all expired times

		//Check and Process Messages
		FormData = Mailbox.GetNextMessage();
		if (FormData.size() > 5) { cout << FormData; }
		getFormData(FormData);
		Action = GetValueFromKey("Action");

		if (Action == "EnterGame"){
			Character NewChar(GetValueFromKey("u"), GetValueFromKey("c"), stoi(GetValueFromKey("Box")));
			Mailbox.OpenUserBox(NewChar.Box);
			Mailbox.BroadcastMessage("This is a test of the server.");
			Mailbox.SendMessageToBox("Specific User Message", NewChar.Box);
			cout << "Intelligence:" << NewChar.GetStat(Intelligence, true);
			Players.push_back(NewChar);
		}

		if (Action == "LeaveGame"){
		}

		if (Action == "Move"){
		}

		if (Action == "CastSpell"){
		}

		if (Action == "EquipItem"){
		}

		if (Action == "UseItem"){
		}

		if (Action == "Attack"){
		}
		//Game in progress action

		//Perform a character action

		//Perform an inventory action

		//Perform a world action

		//Perform targetting action

		//Sleep 10 milliseconds before looping again.

	}

}

string GetValueFromKey(string FindKey){
	for (int i = 0; i < FormData.size(); i++){
		if (!FormData[i].Key.compare(FindKey)){ return FormData[i].Value; }
	}
	return "";
}

void getFormData(string Env){
	int EnvLen = Env.size();
	int Start = 1;
	int Mid = 0;
	FormInfo NewData;

	//Split Key-Value pairs and place in the FormData structure.
	for (int i = 1; i < EnvLen; i++){
	if (Env[i] == '='){Mid = i + 1;}
		if (Env[i] == '&' || i == EnvLen - 1){
			if (i == EnvLen - 1) i++;  //Get last character
			NewData.Key = Env.substr(Start,Mid-Start-1);
			NewData.Value = Env.substr(Mid, i - Mid);
			FormData.push_back(NewData);
			Start = i + 1;
		}
	}
}

<|endoftext|>


<commit_before>#include <LuaContext.hpp>
#include <gtest/gtest.h>

TEST(FunctionsWrite, NativeFunctions) {
    struct Foo {
        static int increment(int x)
        {
            return x + 1;
        }
    };

    LuaContext context;

    context.writeVariable("f", &Foo::increment);
    context.writeFunction<int (int)>("g", &Foo::increment);
    context.writeFunction("h", &Foo::increment);

    EXPECT_EQ(3, context.executeCode<int>("return f(2)"));
    EXPECT_EQ(13, context.executeCode<int>("return g(12)"));
    EXPECT_EQ(9, context.executeCode<int>("return h(8)"));
    EXPECT_THROW(context.executeCode<int>("return f(true)"), LuaContext::ExecutionErrorException);
}

TEST(FunctionsWrite, ConstRefParameters)
{
    struct Foo {
        static int length(const std::string& x)
        {
            EXPECT_EQ("test", x);
            return x.length();
        }
    };

    LuaContext context;

    context.writeVariable("f", &Foo::length);
    EXPECT_EQ(4, context.executeCode<int>("return f('test')"));
}

TEST(FunctionsWrite, VariantParameters)
{
    LuaContext context;

    struct Foo {};
    context.writeVariable("foo", Foo{});
    context.writeFunction("f", [](const boost::variant<int, Foo&>& val) { return val.which(); });

    EXPECT_EQ(1, context.executeCode<int>("return f(foo)"));
    EXPECT_EQ(0, context.executeCode<int>("return f(3)"));
}

TEST(FunctionsWrite, FunctionObjects) {
    struct Foo {
        int operator()(int x) {
            return x + 1;
        }

        double operator()(double) {
            EXPECT_TRUE(false);
            return 0;
        }
    };

    LuaContext context;

    context.writeVariable("f", std::function<int (int)>(Foo{}));
    context.writeFunction<int (int)>("g", Foo{});

    EXPECT_EQ(3, context.executeCode<int>("return f(2)"));
    EXPECT_EQ(13, context.executeCode<int>("return g(12)"));
}

TEST(FunctionsWrite, FunctionObjectsConst) {
    struct Foo {
        int operator()(int x) {
            return x + 1;
        }

        int operator()(int x) const {
            return x + 1;
        }
    };

    LuaContext context;

    context.writeVariable("f", std::function<int (int)>(Foo{}));
    context.writeFunction<int (int)>("g", Foo{});

    EXPECT_EQ(3, context.executeCode<int>("return f(2)"));
    EXPECT_EQ(13, context.executeCode<int>("return g(12)"));
}

TEST(FunctionsWrite, FunctionObjectsAutodetect) {
    struct Foo {
        int operator()(int x) {
            return x + 1;
        }
    };

    LuaContext context;

    context.writeVariable("f", std::function<int (int)>(Foo{}));
    context.writeFunction<int (int)>("g", Foo{});
    context.writeFunction("h", Foo{});

    EXPECT_EQ(3, context.executeCode<int>("return f(2)"));
    EXPECT_EQ(13, context.executeCode<int>("return g(12)"));
    EXPECT_EQ(9, context.executeCode<int>("return h(8)"));
}

TEST(FunctionsWrite, Lambdas) {
    LuaContext context;

    const auto konst = 1;
    const auto lambda = [&](int x) { return x + konst; };
    context.writeVariable("f", std::function<int (int)>(lambda));
    context.writeFunction<int (int)>("g", lambda);
    context.writeFunction("h", lambda);

    EXPECT_EQ(3, context.executeCode<int>("return f(2)"));
    EXPECT_EQ(13, context.executeCode<int>("return g(12)"));
    EXPECT_EQ(9, context.executeCode<int>("return h(8)"));
}

TEST(FunctionsWrite, DestructorCalled) {
    struct Foo {
        int operator()(int x) {
            return x + 1;
        }

        std::shared_ptr<char> dummy;
    };

    auto foo = Foo{ std::make_shared<char>() };
    std::weak_ptr<char> dummy = foo.dummy;

    auto context = std::make_shared<LuaContext>();
    context->writeFunction("f", foo);
    foo.dummy.reset();

    EXPECT_FALSE(dummy.expired());
    context.reset();
    EXPECT_TRUE(dummy.expired());
}

TEST(FunctionsWrite, ReturningMultipleValues) {
    LuaContext context;

    context.writeFunction("f", [](int x) { return std::make_tuple(x, x+1, "hello"); });
    context.executeCode("a, b, c = f(2)");

    EXPECT_EQ(2, context.readVariable<int>("a"));
    EXPECT_EQ(3, context.readVariable<int>("b"));
    EXPECT_EQ("hello", context.readVariable<std::string>("c"));
}

TEST(FunctionsWrite, PolymorphicFunctions) {
    LuaContext context;

    context.writeFunction("f",
        [](boost::variant<int,bool,std::string> x) -> std::string
        {
            if (x.which() == 0)
                return "int";
            else if (x.which() == 1)
                return "bool";
            else
                return "string";
        }
    );

    EXPECT_EQ("int", context.executeCode<std::string>("return f(2)"));
    EXPECT_EQ("bool", context.executeCode<std::string>("return f(true)"));
    EXPECT_EQ("string", context.executeCode<std::string>("return f('test')"));
}

TEST(FunctionsWrite, VariadicFunctions) {
    LuaContext context;

    context.writeFunction("f",
        [](int a, boost::optional<int> b, boost::optional<double> c) -> int {
            return c.is_initialized() ? 3 : (b.is_initialized() ? 2 : 1);
        }
    );

    EXPECT_EQ(1, context.executeCode<int>("return f(12)"));
    EXPECT_EQ(2, context.executeCode<int>("return f(12, 24)"));
    EXPECT_THROW(context.executeCode<int>("return f(12, 24, \"hello\")"), LuaContext::ExecutionErrorException);
    EXPECT_EQ(3, context.executeCode<int>("return f(12, 24, 3.5)"));

    context.writeFunction("g", [](boost::optional<int> a, boost::optional<int> b, int c) -> int { return 3; });
    EXPECT_EQ(3, context.executeCode<int>("return g(10, 20, 30)"));
    EXPECT_THROW(context.executeCode<int>("return g(12, 24)"), LuaContext::ExecutionErrorException);
}

TEST(FunctionsWrite, AccessLuaFromWithinCallback) {
    LuaContext context;

    context.writeFunction("read", [&](const std::string& varName) {
        EXPECT_EQ(5, context.readVariable<int>(varName));
    });

    context.executeCode("x = 5; read(\"x\");");
}

TEST(FunctionsWrite, ExecuteLuaFromWithinCallback) {
    LuaContext context;

    context.writeFunction("exec", [&](const std::string& varName) {
        EXPECT_EQ("x", varName);
        context.executeCode("x = 10");
        EXPECT_EQ(10, context.readVariable<int>(varName));
    });

    context.executeCode("exec(\"x\")");
}
<commit_msg>test that VIR uses the right index for passed functions<commit_after>#include <LuaContext.hpp>
#include <gtest/gtest.h>

TEST(FunctionsWrite, NativeFunctions) {
    struct Foo {
        static int increment(int x)
        {
            return x + 1;
        }
    };

    LuaContext context;

    context.writeVariable("f", &Foo::increment);
    context.writeFunction<int (int)>("g", &Foo::increment);
    context.writeFunction("h", &Foo::increment);

    EXPECT_EQ(3, context.executeCode<int>("return f(2)"));
    EXPECT_EQ(13, context.executeCode<int>("return g(12)"));
    EXPECT_EQ(9, context.executeCode<int>("return h(8)"));
    EXPECT_THROW(context.executeCode<int>("return f(true)"), LuaContext::ExecutionErrorException);
}

TEST(FunctionsWrite, ConstRefParameters)
{
    struct Foo {
        static int length(const std::string& x)
        {
            EXPECT_EQ("test", x);
            return x.length();
        }
    };

    LuaContext context;

    context.writeVariable("f", &Foo::length);
    EXPECT_EQ(4, context.executeCode<int>("return f('test')"));
}

TEST(FunctionsWrite, VariantParameters)
{
    LuaContext context;

    struct Foo {};
    context.writeVariable("foo", Foo{});
    context.writeFunction("f", [](const boost::variant<int, Foo&>& val) { return val.which(); });

    EXPECT_EQ(1, context.executeCode<int>("return f(foo)"));
    EXPECT_EQ(0, context.executeCode<int>("return f(3)"));
}

TEST(FunctionsWrite, FunctionObjects) {
    struct Foo {
        int operator()(int x) {
            return x + 1;
        }

        double operator()(double) {
            EXPECT_TRUE(false);
            return 0;
        }
    };

    LuaContext context;

    context.writeVariable("f", std::function<int (int)>(Foo{}));
    context.writeFunction<int (int)>("g", Foo{});

    EXPECT_EQ(3, context.executeCode<int>("return f(2)"));
    EXPECT_EQ(13, context.executeCode<int>("return g(12)"));
}

TEST(FunctionsWrite, FunctionObjectsConst) {
    struct Foo {
        int operator()(int x) {
            return x + 1;
        }

        int operator()(int x) const {
            return x + 1;
        }
    };

    LuaContext context;

    context.writeVariable("f", std::function<int (int)>(Foo{}));
    context.writeFunction<int (int)>("g", Foo{});

    EXPECT_EQ(3, context.executeCode<int>("return f(2)"));
    EXPECT_EQ(13, context.executeCode<int>("return g(12)"));
}

TEST(FunctionsWrite, FunctionObjectsAutodetect) {
    struct Foo {
        int operator()(int x) {
            return x + 1;
        }
    };

    LuaContext context;

    context.writeVariable("f", std::function<int (int)>(Foo{}));
    context.writeFunction<int (int)>("g", Foo{});
    context.writeFunction("h", Foo{});

    EXPECT_EQ(3, context.executeCode<int>("return f(2)"));
    EXPECT_EQ(13, context.executeCode<int>("return g(12)"));
    EXPECT_EQ(9, context.executeCode<int>("return h(8)"));
}

TEST(FunctionsWrite, Lambdas) {
    LuaContext context;

    const auto konst = 1;
    const auto lambda = [&](int x) { return x + konst; };
    context.writeVariable("f", std::function<int (int)>(lambda));
    context.writeFunction<int (int)>("g", lambda);
    context.writeFunction("h", lambda);

    EXPECT_EQ(3, context.executeCode<int>("return f(2)"));
    EXPECT_EQ(13, context.executeCode<int>("return g(12)"));
    EXPECT_EQ(9, context.executeCode<int>("return h(8)"));
}

TEST(FunctionsWrite, DestructorCalled) {
    struct Foo {
        int operator()(int x) {
            return x + 1;
        }

        std::shared_ptr<char> dummy;
    };

    auto foo = Foo{ std::make_shared<char>() };
    std::weak_ptr<char> dummy = foo.dummy;

    auto context = std::make_shared<LuaContext>();
    context->writeFunction("f", foo);
    foo.dummy.reset();

    EXPECT_FALSE(dummy.expired());
    context.reset();
    EXPECT_TRUE(dummy.expired());
}

TEST(FunctionsWrite, ReturningMultipleValues) {
    LuaContext context;

    context.writeFunction("f", [](int x) { return std::make_tuple(x, x+1, "hello"); });
    context.executeCode("a, b, c = f(2)");

    EXPECT_EQ(2, context.readVariable<int>("a"));
    EXPECT_EQ(3, context.readVariable<int>("b"));
    EXPECT_EQ("hello", context.readVariable<std::string>("c"));
}

TEST(FunctionsWrite, PolymorphicFunctions) {
    LuaContext context;

    context.writeFunction("f",
        [](boost::variant<int,bool,std::string> x) -> std::string
        {
            if (x.which() == 0)
                return "int";
            else if (x.which() == 1)
                return "bool";
            else
                return "string";
        }
    );

    EXPECT_EQ("int", context.executeCode<std::string>("return f(2)"));
    EXPECT_EQ("bool", context.executeCode<std::string>("return f(true)"));
    EXPECT_EQ("string", context.executeCode<std::string>("return f('test')"));
}

TEST(FunctionsWrite, VariadicFunctions) {
    LuaContext context;

    context.writeFunction("f",
        [](int a, boost::optional<int> b, boost::optional<double> c) -> int {
            return c.is_initialized() ? 3 : (b.is_initialized() ? 2 : 1);
        }
    );

    EXPECT_EQ(1, context.executeCode<int>("return f(12)"));
    EXPECT_EQ(2, context.executeCode<int>("return f(12, 24)"));
    EXPECT_THROW(context.executeCode<int>("return f(12, 24, \"hello\")"), LuaContext::ExecutionErrorException);
    EXPECT_EQ(3, context.executeCode<int>("return f(12, 24, 3.5)"));

    context.writeFunction("g", [](boost::optional<int> a, boost::optional<int> b, int c) -> int { return 3; });
    EXPECT_EQ(3, context.executeCode<int>("return g(10, 20, 30)"));
    EXPECT_THROW(context.executeCode<int>("return g(12, 24)"), LuaContext::ExecutionErrorException);
}

TEST(FunctionsWrite, AccessLuaFromWithinCallback) {
    LuaContext context;

    context.writeFunction("read", [&](const std::string& varName) {
        EXPECT_EQ(5, context.readVariable<int>(varName));
    });

    context.executeCode("x = 5; read(\"x\");");
}

TEST(FunctionsWrite, ExecuteLuaFromWithinCallback) {
    LuaContext context;

    context.writeFunction("exec", [&](const std::string& varName) {
        EXPECT_EQ("x", varName);
        context.executeCode("x = 10");
        EXPECT_EQ(10, context.readVariable<int>(varName));
    });

    context.executeCode("exec(\"x\")");
}

TEST(FunctionsWrite, CallbackNotLastArgument) {
    LuaContext context;

    struct Foo {
        static int a(void)
        {
            return 1;
        }

        static int b(void)
        {
            return 2;
        }
    };

    context.writeFunction("foo", [](std::function<int(void)> a, std::function<int(void)> b) {
        return a();
    });

    EXPECT_EQ(1, context.executeCode<int>("function a() return 1 end function b() return 2 end return foo(a,b)"));
}
<|endoftext|>


<commit_before>//@author A0094446X
#include "stdafx.h"
#include <functional>
#include <QApplication>
#include <QList>
#include <set>
#include "session_manager.h"
#include "task_panel_manager.h"
#include "system_tray_manager.h"
#include "query_manager.h"
#include "main_window_messages.h"
#include "window_title.h"
#include "keywords.h"
#include "You-Controller/exception.h"

namespace You {
namespace GUI {

using Task = You::Controller::Task;

MainWindow::MainWindow(QWidget *parent)
	: QMainWindow(parent), sm(new MainWindow::SessionManager(this)),
		stm(new MainWindow::SystemTrayManager(this)),
		tpm(new MainWindow::TaskPanelManager(this)),
		qm(new MainWindow::QueryManager(this)),
		commandTextBox(new CommandTextBox(this)),
		taskList(new TaskList) {
	#pragma warning(push)
	#pragma warning(disable: 4127)
	Q_INIT_RESOURCE(yougui);
	#pragma warning(pop)
	ui.setupUi(this);
	ui.menuBar->setVisible(false);
	ui.mainToolBar->setVisible(false);
	setWindowTitle(QString::fromStdWString(WINDOW_TITLE));
	sm->setup();
	stm->setup();
	qm->setup();
	tpm->setup();
	ui.horizontalLayout->insertWidget(0, &*commandTextBox);
	commandTextBox->setup();
	connect(&*commandTextBox, SIGNAL(enterKey()),
		this, SLOT(commandEnterPressed()));
	connect(this, SIGNAL(updateRowNumbers()), &*tpm, SLOT(updateRowNumbers()));
	populateTaskPanel();
	statusBar()->insertPermanentWidget(
		0, ui.statusTasks, 0);
	updateTaskInfoBar();
	ui.taskDescriptor->setOpenLinks(false);
	ui.taskDescriptor->setOpenExternalLinks(false);
	connect(ui.taskDescriptor, SIGNAL(anchorClicked(const QUrl &)),
		this, SLOT(openURL(const QUrl &)));
}

MainWindow::~MainWindow() {
}

void MainWindow::closeEvent(QCloseEvent *event) {
	if (stm->trayIcon.isVisible()) {
		QMessageBox::information(this, tr("Systray"),
			tr("The program will keep running in the "
			"system tray. To terminate the program, "
			"choose Quit in the context menu "
			"of the system tray entry."));
		hide();
		event->ignore();
	} else {
		QMainWindow::closeEvent(event);
	}
}

void MainWindow::populateTaskPanel() {
	StatusUpdate update;
	try {
		TaskList tl = qm->getTasks();
		addTasks(tl);
	} catch (You::Controller::IOException& e) {
		update.setUpdate(RESOURCE_RED, QString("Error loading tasks."), &ui);
		showErrorAndExit(IO_EXCEPTION_MESSAGE,
			QString("Exception: File could not be opened."));
	} catch (You::Controller::NotWellFormedXmlException& e) {
		update.setUpdate(RESOURCE_RED, QString("Error loading tasks."), &ui);
		showErrorAndExit(NOT_WELL_FORMED_XML_MESSAGE,
			QString("Exception: XML is not well formed"));
	}
	tpm->repaintTasks();
	updateRowNumbers();
}

void MainWindow::setVisible(bool visible) {
	stm->minimizeAction->setEnabled(visible);
	stm->maximizeAction->setEnabled(!isMaximized());
	stm->restoreAction->setEnabled(isMaximized() || !visible);
	QWidget::setVisible(visible);
}

const TaskList& MainWindow::getTaskList() const {
	return *taskList;
}

void MainWindow::addTaskWithSubtasks(const Task& task, const TaskList& tl) {
	QTreeWidgetItem *item = tpm->addTaskTree(task).release();
	ui.taskTreePanel->addTopLevelItem(item);
	expandAllSubtasks(item);
}

void MainWindow::expandAllSubtasks(QTreeWidgetItem *item) {
	if (item->childCount() == 0) {
		return;
	} else {
		item->setExpanded(true);
		for (int i = 0; i < item->childCount(); i++) {
			expandAllSubtasks(item->child(i));
		}
	}
}

void MainWindow::addTask(const Task& task) {
	taskList->push_back(task);
	tpm->addTask(task);
}

void MainWindow::addTasks(const TaskList& tl) {
	std::for_each(tl.begin(), tl.end(),
		std::bind(&MainWindow::addTaskWithSubtasks, this, std::placeholders::_1, tl));
}

void MainWindow::deleteTask(Task::ID taskID) {
	TaskList::iterator i = std::find_if(taskList->begin(), taskList->end(),
		[=](Task& task) {
			return task.getID() == taskID;
		});

	assert(i != taskList->end());
	taskList->erase(i);
	tpm->deleteTask(taskID);
}

void MainWindow::editTask(const Task& task) {
	tpm->editTask(task);
	ui.taskTreePanel->viewport()->update();
	emit(taskSelected());
}

void MainWindow::sendQuery() {
	Task::ID curr = getSelectedTaskID();
	QString inputString = commandTextBox->toPlainText();
	QPixmap pixmap;
	pixmap.fill(Qt::transparent);
	pixmap.load(RESOURCE_GREEN, 0);
	QString message(READY_MESSAGE);
	ui.statusMessage->setText(message);
	try {
		qm->query(inputString, getTaskList());
	} catch (You::Controller::EmptyTaskDescriptionException& e) {
		ui.statusMessage->setText(EMPTY_TASK_DESCRIPTION_MESSAGE);
		pixmap.load(RESOURCE_RED, 0);
	} catch(You::Controller::TaskNotFoundException& e) {
		ui.statusMessage->setText(TASK_NOT_FOUND_MESSAGE);
		pixmap.load(RESOURCE_RED, 0);
	} catch (You::Controller::ParseErrorException& e) {
		ui.statusMessage->setText(PARSE_ERROR_MESSAGE);
		pixmap.load(RESOURCE_RED, 0);
	} catch (You::Controller::ContextIndexOutOfRangeException& e) {
		ui.statusMessage->setText(CONTEXT_INDEX_OUT_OF_RANGE_MESSAGE);
		pixmap.load(RESOURCE_RED, 0);
	} catch (You::Controller::ContextRequiredException& e) {
		ui.statusMessage->setText(CONTEXT_REQUIRED_MESSAGE);
		pixmap.load(RESOURCE_RED, 0);
	} catch (You::Controller::CircularDependencyException& e) {
		ui.statusMessage->setText(CIRCULAR_DEPENDENCY_MESSAGE);
		pixmap.load(RESOURCE_RED, 0);
	} catch (You::Controller::NotUndoAbleException& e) {
		ui.statusMessage->setText(NOT_UNDOABLE_MESSAGE);
		pixmap.load(RESOURCE_RED, 0);
	} catch (You::Controller::ParserTypeException& e) {
		ui.statusMessage->setText(PARSER_TYPE_MESSAGE);
		pixmap.load(RESOURCE_RED, 0);
	} catch (You::Controller::ParserException& e) {
		ui.statusMessage->setText(PARSER_EXCEPTION_MESSAGE);
		pixmap.load(RESOURCE_RED, 0);
	}

	/// Selects the item if it was originally selected and still exists
	QList<QTreeWidgetItem*> items = ui.taskTreePanel->findItems(
		boost::lexical_cast<QString>(curr), 0);
	if (items.size() != 0) {
		if (items.size() == 1) {
			ui.taskTreePanel->setCurrentItem(items.at(0));
		} else {
			assert(false);
		}
	}

	ui.statusIcon->setPixmap(pixmap);
	commandTextBox->setPlainText(QString());
	updateTaskInfoBar();
	updateRowNumbers();
	tpm->repaintTasks();
}

void MainWindow::commandEnterPressed() {
	sendQuery();
}

void MainWindow::commandEnterButtonClicked() {
	sendQuery();
}

void MainWindow::clearTasks() {
	taskList.reset(new TaskList);
	ui.taskTreePanel->clear();
	ui.taskDescriptor->clear();
	commandTextBox->clear();
	updateTaskInfoBar();
}

void MainWindow::taskSelected() {
	/// Find selected item and fill task box
	QList<QTreeWidgetItem*> selection = ui.taskTreePanel->selectedItems();
	QString contents = "";
	if (selection.size() == 0) {
		ui.taskDescriptor->setHtml(contents);
	} else {
		QTreeWidgetItem item = *selection.at(0);
		QString index = tpm->getIndexAsText(item);
		QString description = tpm->getDescriptionAsText(item);
		QString startdate = tpm->getStartDateAsText(item);
		QString deadline = tpm->getDeadlineAsText(item);
		QString priority = tpm->getPriorityAsText(item);
		QString dependencies = tpm->getDependenciesAsText(item);
		QString attachment = tpm->getAttachmentAsText(item);
		contents = "Index: " + index + "
"
			+ "Description: " + description + "
"
			+ "Start date: " + startdate + "
"
			+ "Deadline: " + deadline + "
"
			+ "Priority: " + priority + "
"
			+ "Dependencies: " + dependencies + "
"
			+ "Attachment: " + ""
			+ attachment + "

";
		ui.taskDescriptor->setHtml(contents);
	}
	tpm->repaintTasks();
}

Task::ID MainWindow::getSelectedTaskID() {
	QList<QTreeWidgetItem*> selection = ui.taskTreePanel->selectedItems();
	QString contents = "";
	if (selection.size() == 0) {
		return -1;
	} else {
		QTreeWidgetItem item = *selection.at(0);
		Task::ID index =
			boost::lexical_cast<Task::ID>(
			tpm->getHiddenIDAsText(item).toLongLong());
		return index;
	}
}

void MainWindow::contextAddTask() {
	commandTextBox->setPlainText(QString("/add "));
	commandTextBox->setFocus();
	commandTextBox->moveCursor(QTextCursor::End);
}

void MainWindow::contextDeleteTask(int id) {
	std::wstringstream wss;
	wss << L"/delete " << id;
	commandTextBox->setPlainText(QString::fromStdWString(wss.str()));
	commandTextBox->setFocus();
	commandTextBox->moveCursor(QTextCursor::End);
}

void MainWindow::contextEditTask(int id) {
	std::wstringstream wss;
	wss << L"/edit " << id << L" set ";
	commandTextBox->setPlainText(QString::fromStdWString(wss.str()));
	commandTextBox->setFocus();
	commandTextBox->moveCursor(QTextCursor::End);
}

void MainWindow::updateTaskInfoBar() {
	int dueSoon = 0;
	int overdue = 0;
	for (int i = 0; i < taskList->size(); i++) {
		if (tpm->isDueWithinExactly(taskList->at(i).getDeadline(), 7)) {
			dueSoon++;
		}
		if (tpm->isPastDue(taskList->at(i).getDeadline())
			&& !taskList->at(i).isCompleted()) {
			overdue++;
		}
	}
	std::wostringstream ss;
	ss << L"Overdue tasks: " << overdue << L". Tasks due soon: " << dueSoon;
	ui.statusTasks->setText(QString::fromStdWString(ss.str()));
}

void MainWindow::applicationExitRequested() {
	qApp->quit();
}

void MainWindow::resizeEvent(QResizeEvent* event) {
	double oldWidth = event->oldSize().width();
	double newWidth = event->size().width();
	double ratio = newWidth / oldWidth;
	for (int i = 0; i < ui.taskTreePanel->columnCount(); ++i) {
		double currWidth = ui.taskTreePanel->header()->sectionSize(i);
		double finalWidth = currWidth * ratio;
		if (finalWidth >75)
			ui.taskTreePanel->header()->resizeSection(i, currWidth * ratio);
	}
	QMainWindow::resizeEvent(event);
}

void MainWindow::openURL(const QUrl &url) {
	QDesktopServices::openUrl(url);
}

void MainWindow::showErrorAndExit(QString message, QString title) {
	QMessageBox messageBox;
	messageBox.setIcon(QMessageBox::Critical);
	messageBox.setWindowTitle(title);
	messageBox.setText(message);
	messageBox.setStandardButtons(QMessageBox::Ok);
	messageBox.exec();
	QTimer::singleShot(250, qApp, SLOT(quit()));
}

MainWindow::BaseManager::BaseManager(MainWindow* parentGUI)
	: parentGUI(parentGUI) {
}

}  // namespace GUI
}  // namespace You
<commit_msg>Fixes #383<commit_after>//@author A0094446X
#include "stdafx.h"
#include <functional>
#include <QApplication>
#include <QList>
#include <set>
#include "session_manager.h"
#include "task_panel_manager.h"
#include "system_tray_manager.h"
#include "query_manager.h"
#include "main_window_messages.h"
#include "window_title.h"
#include "keywords.h"
#include "You-Controller/exception.h"

namespace You {
namespace GUI {

using Task = You::Controller::Task;

MainWindow::MainWindow(QWidget *parent)
	: QMainWindow(parent), sm(new MainWindow::SessionManager(this)),
		stm(new MainWindow::SystemTrayManager(this)),
		tpm(new MainWindow::TaskPanelManager(this)),
		qm(new MainWindow::QueryManager(this)),
		commandTextBox(new CommandTextBox(this)),
		taskList(new TaskList) {
	#pragma warning(push)
	#pragma warning(disable: 4127)
	Q_INIT_RESOURCE(yougui);
	#pragma warning(pop)
	ui.setupUi(this);
	ui.menuBar->setVisible(false);
	ui.mainToolBar->setVisible(false);
	setWindowTitle(QString::fromStdWString(WINDOW_TITLE));
	sm->setup();
	stm->setup();
	qm->setup();
	tpm->setup();
	ui.horizontalLayout->insertWidget(0, &*commandTextBox);
	commandTextBox->setup();
	connect(&*commandTextBox, SIGNAL(enterKey()),
		this, SLOT(commandEnterPressed()));
	connect(this, SIGNAL(updateRowNumbers()), &*tpm, SLOT(updateRowNumbers()));
	populateTaskPanel();
	statusBar()->insertPermanentWidget(
		0, ui.statusTasks, 0);
	updateTaskInfoBar();
	ui.taskDescriptor->setOpenLinks(false);
	ui.taskDescriptor->setOpenExternalLinks(false);
	connect(ui.taskDescriptor, SIGNAL(anchorClicked(const QUrl &)),
		this, SLOT(openURL(const QUrl &)));
}

MainWindow::~MainWindow() {
}

void MainWindow::closeEvent(QCloseEvent *event) {
	if (stm->trayIcon.isVisible()) {
		QMessageBox::information(this, tr("Systray"),
			tr("The program will keep running in the "
			"system tray. To terminate the program, "
			"choose Quit in the context menu "
			"of the system tray entry."));
		hide();
		event->ignore();
	} else {
		QMainWindow::closeEvent(event);
	}
}

void MainWindow::populateTaskPanel() {
	StatusUpdate update;
	try {
		TaskList tl = qm->getTasks();
		addTasks(tl);
	} catch (You::Controller::IOException& e) {
		update.setUpdate(RESOURCE_RED, QString("Error loading tasks."), &ui);
		showErrorAndExit(IO_EXCEPTION_MESSAGE,
			QString("Exception: File could not be opened."));
	} catch (You::Controller::NotWellFormedXmlException& e) {
		update.setUpdate(RESOURCE_RED, QString("Error loading tasks."), &ui);
		showErrorAndExit(NOT_WELL_FORMED_XML_MESSAGE,
			QString("Exception: XML is not well formed"));
	}
	tpm->repaintTasks();
	updateRowNumbers();
}

void MainWindow::setVisible(bool visible) {
	stm->minimizeAction->setEnabled(visible);
	stm->maximizeAction->setEnabled(!isMaximized());
	stm->restoreAction->setEnabled(isMaximized() || !visible);
	QWidget::setVisible(visible);
}

const TaskList& MainWindow::getTaskList() const {
	return *taskList;
}

void MainWindow::addTaskWithSubtasks(const Task& task, const TaskList& tl) {
	QTreeWidgetItem *item = tpm->addTaskTree(task).release();
	ui.taskTreePanel->addTopLevelItem(item);
	expandAllSubtasks(item);
}

void MainWindow::expandAllSubtasks(QTreeWidgetItem *item) {
	if (item->childCount() == 0) {
		return;
	} else {
		item->setExpanded(true);
		for (int i = 0; i < item->childCount(); i++) {
			expandAllSubtasks(item->child(i));
		}
	}
}

void MainWindow::addTask(const Task& task) {
	taskList->push_back(task);
	tpm->addTask(task);
}

void MainWindow::addTasks(const TaskList& tl) {
	std::for_each(tl.begin(), tl.end(),
		std::bind(&MainWindow::addTaskWithSubtasks, this, std::placeholders::_1, tl));
}

void MainWindow::deleteTask(Task::ID taskID) {
	TaskList::iterator i = std::find_if(taskList->begin(), taskList->end(),
		[=](Task& task) {
			return task.getID() == taskID;
		});

	assert(i != taskList->end());
	taskList->erase(i);
	tpm->deleteTask(taskID);
}

void MainWindow::editTask(const Task& task) {
	tpm->editTask(task);
	ui.taskTreePanel->viewport()->update();
	emit(taskSelected());
}

void MainWindow::sendQuery() {
	Task::ID curr = getSelectedTaskID();
	QString inputString = commandTextBox->toPlainText();
	QPixmap pixmap;
	pixmap.fill(Qt::transparent);
	pixmap.load(RESOURCE_GREEN, 0);
	QString message(READY_MESSAGE);
	ui.statusMessage->setText(message);
	try {
		qm->query(inputString, getTaskList());
	} catch (You::Controller::EmptyTaskDescriptionException& e) {
		ui.statusMessage->setText(EMPTY_TASK_DESCRIPTION_MESSAGE);
		pixmap.load(RESOURCE_RED, 0);
	} catch(You::Controller::TaskNotFoundException& e) {
		ui.statusMessage->setText(TASK_NOT_FOUND_MESSAGE);
		pixmap.load(RESOURCE_RED, 0);
	} catch (You::Controller::ParseErrorException& e) {
		ui.statusMessage->setText(PARSE_ERROR_MESSAGE);
		pixmap.load(RESOURCE_RED, 0);
	} catch (You::Controller::ContextIndexOutOfRangeException& e) {
		ui.statusMessage->setText(CONTEXT_INDEX_OUT_OF_RANGE_MESSAGE);
		pixmap.load(RESOURCE_RED, 0);
	} catch (You::Controller::ContextRequiredException& e) {
		ui.statusMessage->setText(CONTEXT_REQUIRED_MESSAGE);
		pixmap.load(RESOURCE_RED, 0);
	} catch (You::Controller::CircularDependencyException& e) {
		ui.statusMessage->setText(CIRCULAR_DEPENDENCY_MESSAGE);
		pixmap.load(RESOURCE_RED, 0);
	} catch (You::Controller::NotUndoAbleException& e) {
		ui.statusMessage->setText(NOT_UNDOABLE_MESSAGE);
		pixmap.load(RESOURCE_RED, 0);
	} catch (You::Controller::ParserTypeException& e) {
		ui.statusMessage->setText(PARSER_TYPE_MESSAGE);
		pixmap.load(RESOURCE_RED, 0);
	} catch (You::Controller::ParserException& e) {
		ui.statusMessage->setText(PARSER_EXCEPTION_MESSAGE);
		pixmap.load(RESOURCE_RED, 0);
	} catch (You::Controller::IOException& e) {
		showErrorAndExit(IO_EXCEPTION_MESSAGE,
			QString("Exception: Tasks File could not be edited."));
	}

	/// Selects the item if it was originally selected and still exists
	QList<QTreeWidgetItem*> items = ui.taskTreePanel->findItems(
		boost::lexical_cast<QString>(curr), 0);
	if (items.size() != 0) {
		if (items.size() == 1) {
			ui.taskTreePanel->setCurrentItem(items.at(0));
		} else {
			assert(false);
		}
	}

	ui.statusIcon->setPixmap(pixmap);
	commandTextBox->setPlainText(QString());
	updateTaskInfoBar();
	updateRowNumbers();
	tpm->repaintTasks();
}

void MainWindow::commandEnterPressed() {
	sendQuery();
}

void MainWindow::commandEnterButtonClicked() {
	sendQuery();
}

void MainWindow::clearTasks() {
	taskList.reset(new TaskList);
	ui.taskTreePanel->clear();
	ui.taskDescriptor->clear();
	commandTextBox->clear();
	updateTaskInfoBar();
}

void MainWindow::taskSelected() {
	/// Find selected item and fill task box
	QList<QTreeWidgetItem*> selection = ui.taskTreePanel->selectedItems();
	QString contents = "";
	if (selection.size() == 0) {
		ui.taskDescriptor->setHtml(contents);
	} else {
		QTreeWidgetItem item = *selection.at(0);
		QString index = tpm->getIndexAsText(item);
		QString description = tpm->getDescriptionAsText(item);
		QString startdate = tpm->getStartDateAsText(item);
		QString deadline = tpm->getDeadlineAsText(item);
		QString priority = tpm->getPriorityAsText(item);
		QString dependencies = tpm->getDependenciesAsText(item);
		QString attachment = tpm->getAttachmentAsText(item);
		contents = "Index: " + index + "
"
			+ "Description: " + description + "
"
			+ "Start date: " + startdate + "
"
			+ "Deadline: " + deadline + "
"
			+ "Priority: " + priority + "
"
			+ "Dependencies: " + dependencies + "
"
			+ "Attachment: " + ""
			+ attachment + "

";
		ui.taskDescriptor->setHtml(contents);
	}
	tpm->repaintTasks();
}

Task::ID MainWindow::getSelectedTaskID() {
	QList<QTreeWidgetItem*> selection = ui.taskTreePanel->selectedItems();
	QString contents = "";
	if (selection.size() == 0) {
		return -1;
	} else {
		QTreeWidgetItem item = *selection.at(0);
		Task::ID index =
			boost::lexical_cast<Task::ID>(
			tpm->getHiddenIDAsText(item).toLongLong());
		return index;
	}
}

void MainWindow::contextAddTask() {
	commandTextBox->setPlainText(QString("/add "));
	commandTextBox->setFocus();
	commandTextBox->moveCursor(QTextCursor::End);
}

void MainWindow::contextDeleteTask(int id) {
	std::wstringstream wss;
	wss << L"/delete " << id;
	commandTextBox->setPlainText(QString::fromStdWString(wss.str()));
	commandTextBox->setFocus();
	commandTextBox->moveCursor(QTextCursor::End);
}

void MainWindow::contextEditTask(int id) {
	std::wstringstream wss;
	wss << L"/edit " << id << L" set ";
	commandTextBox->setPlainText(QString::fromStdWString(wss.str()));
	commandTextBox->setFocus();
	commandTextBox->moveCursor(QTextCursor::End);
}

void MainWindow::updateTaskInfoBar() {
	int dueSoon = 0;
	int overdue = 0;
	for (int i = 0; i < taskList->size(); i++) {
		if (tpm->isDueWithinExactly(taskList->at(i).getDeadline(), 7)) {
			dueSoon++;
		}
		if (tpm->isPastDue(taskList->at(i).getDeadline())
			&& !taskList->at(i).isCompleted()) {
			overdue++;
		}
	}
	std::wostringstream ss;
	ss << L"Overdue tasks: " << overdue << L". Tasks due soon: " << dueSoon;
	ui.statusTasks->setText(QString::fromStdWString(ss.str()));
}

void MainWindow::applicationExitRequested() {
	qApp->quit();
}

void MainWindow::resizeEvent(QResizeEvent* event) {
	double oldWidth = event->oldSize().width();
	double newWidth = event->size().width();
	double ratio = newWidth / oldWidth;
	for (int i = 0; i < ui.taskTreePanel->columnCount(); ++i) {
		double currWidth = ui.taskTreePanel->header()->sectionSize(i);
		double finalWidth = currWidth * ratio;
		if (finalWidth >75)
			ui.taskTreePanel->header()->resizeSection(i, currWidth * ratio);
	}
	QMainWindow::resizeEvent(event);
}

void MainWindow::openURL(const QUrl &url) {
	QDesktopServices::openUrl(url);
}

void MainWindow::showErrorAndExit(QString message, QString title) {
	QMessageBox messageBox;
	messageBox.setIcon(QMessageBox::Critical);
	messageBox.setWindowTitle(title);
	messageBox.setText(message);
	messageBox.setStandardButtons(QMessageBox::Ok);
	messageBox.exec();
	QTimer::singleShot(250, qApp, SLOT(quit()));
}

MainWindow::BaseManager::BaseManager(MainWindow* parentGUI)
	: parentGUI(parentGUI) {
}

}  // namespace GUI
}  // namespace You
<|endoftext|>


<commit_before>/*  This file is part of the KDE project
    Copyright (C) 2005-2007 Matthias Kretz <kretz@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

*/
#include "effect.h"
#include "effect_p.h"
#include "effectparameter.h"
#include "factory.h"

namespace Phonon
{
Effect::~Effect()
{
    delete k_ptr;
}

Effect::Effect(const AudioEffectDescription &description, QObject *parent)
    : QObject(parent)
    , k_ptr(new EffectPrivate)
{
    K_D(Effect);
    d->q_ptr = this;
    d->type = Effect::AudioEffect;
    d->id = description.index();
    d->createBackendObject();
}

Effect::Effect(const VideoEffectDescription &description, QObject *parent)
    : QObject(parent)
    , k_ptr(new EffectPrivate)
{
    K_D(Effect);
    d->q_ptr = this;
    d->type = Effect::VideoEffect;
    d->id = description.index();
    d->createBackendObject();
}

Effect::Effect(EffectPrivate &dd, QObject *parent)
    : QObject(parent)
    , k_ptr(&dd)
{
    K_D(Effect);
    d->q_ptr = this;
}

void EffectPrivate::createBackendObject()
{
    if (m_backendObject)
        return;
    Q_Q(Effect);
    switch (type) {
    case Effect::AudioEffect:
        m_backendObject = Factory::createAudioEffect(id, q);
        break;
    case Effect::VideoEffect:
        m_backendObject = Factory::createVideoEffect(id, q);
        break;
    }
    if (m_backendObject) {
        setupBackendObject();
    }
}

Effect::Type Effect::type() const
{
    K_D(const Effect);
    return d->type;
}

AudioEffectDescription Effect::audioDescription() const
{
    K_D(const Effect);
    if (d->type != Effect::AudioEffect)
        return AudioEffectDescription();
    return AudioEffectDescription::fromIndex(d->id);
}

VideoEffectDescription Effect::videoDescription() const
{
    K_D(const Effect);
    if (d->type != Effect::VideoEffect)
        return VideoEffectDescription();
    return VideoEffectDescription::fromIndex(d->id);
}

QList<EffectParameter> Effect::allDescriptions() const
{
    K_D(const Effect);
    QList<EffectParameter> ret;
    // there should be an iface object, but better be safe for those backend
    // switching corner-cases: when the backend switches the new backend might
    // not support this effect -> no iface object
    if (d->m_backendObject) {
        BACKEND_GET(QList<EffectParameter>, ret, "allDescriptions");
    }
    return ret;
}

EffectParameter Effect::description(int idx) const
{
    K_D(const Effect);
    EffectParameter ret;
    if (d->m_backendObject) {
        BACKEND_GET1(EffectParameter, ret, "description", int, idx);
    }
    return ret;
}

int Effect::parameterCount() const
{
    K_D(const Effect);
    int ret;
    if (d->m_backendObject) {
        BACKEND_GET(int, ret, "parameterCount");
    }
    return ret;
}

QVariant Effect::parameterValue(int index) const
{
    K_D(const Effect);
    if (!d->m_backendObject) {
        return d->parameterValues[index];
    }
    QVariant ret;
    BACKEND_GET1(QVariant, ret, "parameterValue", int, index);
    return ret;
}

void Effect::setParameterValue(int index, const QVariant &newValue)
{
    K_D(Effect);
    if (k_ptr->backendObject()) {
        BACKEND_CALL2("setParameterValue", int, index, QVariant, newValue);
    } else {
        d->parameterValues[index] = newValue;
    }
}

bool EffectPrivate::aboutToDeleteBackendObject()
{
    if (m_backendObject) {
        int count;
        pBACKEND_GET(int, count, "parameterCount");
        for (int i = 0; i < count; ++i) {
            pBACKEND_GET1(QVariant, parameterValues[i], "parameterValue", int, i);
        }
    }
    return true;
}

void EffectPrivate::setupBackendObject()
{
    Q_ASSERT(m_backendObject);

    // set up attributes
    int count;
    pBACKEND_GET(int, count, "parameterCount");
    for (int i = 0; i < count; ++i) {
        pBACKEND_CALL2("setParameterValue", int, i, QVariant, parameterValues[i]);
    }
}

} //namespace Phonon

#include "effect.moc"

// vim: sw=4 ts=4 tw=80
<commit_msg>don't return uninitialized value if there's no backend object: CID 3681<commit_after>/*  This file is part of the KDE project
    Copyright (C) 2005-2007 Matthias Kretz <kretz@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

*/
#include "effect.h"
#include "effect_p.h"
#include "effectparameter.h"
#include "factory.h"

namespace Phonon
{
Effect::~Effect()
{
    delete k_ptr;
}

Effect::Effect(const AudioEffectDescription &description, QObject *parent)
    : QObject(parent)
    , k_ptr(new EffectPrivate)
{
    K_D(Effect);
    d->q_ptr = this;
    d->type = Effect::AudioEffect;
    d->id = description.index();
    d->createBackendObject();
}

Effect::Effect(const VideoEffectDescription &description, QObject *parent)
    : QObject(parent)
    , k_ptr(new EffectPrivate)
{
    K_D(Effect);
    d->q_ptr = this;
    d->type = Effect::VideoEffect;
    d->id = description.index();
    d->createBackendObject();
}

Effect::Effect(EffectPrivate &dd, QObject *parent)
    : QObject(parent)
    , k_ptr(&dd)
{
    K_D(Effect);
    d->q_ptr = this;
}

void EffectPrivate::createBackendObject()
{
    if (m_backendObject)
        return;
    Q_Q(Effect);
    switch (type) {
    case Effect::AudioEffect:
        m_backendObject = Factory::createAudioEffect(id, q);
        break;
    case Effect::VideoEffect:
        m_backendObject = Factory::createVideoEffect(id, q);
        break;
    }
    if (m_backendObject) {
        setupBackendObject();
    }
}

Effect::Type Effect::type() const
{
    K_D(const Effect);
    return d->type;
}

AudioEffectDescription Effect::audioDescription() const
{
    K_D(const Effect);
    if (d->type != Effect::AudioEffect)
        return AudioEffectDescription();
    return AudioEffectDescription::fromIndex(d->id);
}

VideoEffectDescription Effect::videoDescription() const
{
    K_D(const Effect);
    if (d->type != Effect::VideoEffect)
        return VideoEffectDescription();
    return VideoEffectDescription::fromIndex(d->id);
}

QList<EffectParameter> Effect::allDescriptions() const
{
    K_D(const Effect);
    QList<EffectParameter> ret;
    // there should be an iface object, but better be safe for those backend
    // switching corner-cases: when the backend switches the new backend might
    // not support this effect -> no iface object
    if (d->m_backendObject) {
        BACKEND_GET(QList<EffectParameter>, ret, "allDescriptions");
    }
    return ret;
}

EffectParameter Effect::description(int idx) const
{
    K_D(const Effect);
    EffectParameter ret;
    if (d->m_backendObject) {
        BACKEND_GET1(EffectParameter, ret, "description", int, idx);
    }
    return ret;
}

int Effect::parameterCount() const
{
    K_D(const Effect);
    if (d->m_backendObject) {
        int ret;
        BACKEND_GET(int, ret, "parameterCount");
        return ret;
    }
    return 0;
}

QVariant Effect::parameterValue(int index) const
{
    K_D(const Effect);
    if (!d->m_backendObject) {
        return d->parameterValues[index];
    }
    QVariant ret;
    BACKEND_GET1(QVariant, ret, "parameterValue", int, index);
    return ret;
}

void Effect::setParameterValue(int index, const QVariant &newValue)
{
    K_D(Effect);
    if (k_ptr->backendObject()) {
        BACKEND_CALL2("setParameterValue", int, index, QVariant, newValue);
    } else {
        d->parameterValues[index] = newValue;
    }
}

bool EffectPrivate::aboutToDeleteBackendObject()
{
    if (m_backendObject) {
        int count;
        pBACKEND_GET(int, count, "parameterCount");
        for (int i = 0; i < count; ++i) {
            pBACKEND_GET1(QVariant, parameterValues[i], "parameterValue", int, i);
        }
    }
    return true;
}

void EffectPrivate::setupBackendObject()
{
    Q_ASSERT(m_backendObject);

    // set up attributes
    int count;
    pBACKEND_GET(int, count, "parameterCount");
    for (int i = 0; i < count; ++i) {
        pBACKEND_CALL2("setParameterValue", int, i, QVariant, parameterValues[i]);
    }
}

} //namespace Phonon

#include "effect.moc"

// vim: sw=4 ts=4 tw=80
<|endoftext|>


<commit_before>#include <string>
#include "entity.h"
#include "enums.h"

Entity::Entity(){}
Entity::~Entity(){}

void Entity::AlterExp (int Amount){
	//Use this method to add experience to an entity.  This can add experience
	//for a character, or be used to set the amount of experience an enemy
	//is worth.  (NOTE: A character's level cannot be manually set.  To manually
	//set an enemy's level, write a function in the enemy class to do so.)

	_Exp += Amount;
	SetLevel();
}

int Entity::GetExp(){
	//Basic getter function to return Experience.

	return _Exp;
}

int Entity::GetLevel(){
	//Basic getter function to return Level

	return _Level;
}

void Entity::AlterGold (int Amount){
	//Alter the amount of gold the entity has on hand.

	_Gold += Amount;
}

int Entity::GetGold(){
	//Basic getter function to return the amount of gold on hand.

	return _Gold;
}

int Entity::GetStat(Stats Stat, bool Max){
	//Getter function for any stats defined in the stats enum.
	//This is implemented this way to make it easier to interact with spells and items classes.

	return StatTable[Max ? Maximum : Current][(int) Stat];
}

void Entity::AlterStat (Stats Stat, bool Max, int Amount){
	//Relative setter function for stats.  (You can use this for absolute setting
	//by subtracting the existing value and adding the new value.)

	StatTable[Max ? Maximum : Current][(int) Stat] += Amount;
}

void Entity::SetStatToMax (Stats Stat){
	//Set the given stat's current value to it's max value.  Useful for healing,
	//mana replenishment, adverse effect restoration, etc.

	StatTable[Current][(int) Stat] = StatTable[Maximum][(int) Stat];
}

void Entity::SetAllStatsToMax()
{
	//Set All Stats - For initializing a new or restored entity (usually a player)
	for (int i = 0; i < 14; i++){
		StatTable[Current][i] = StatTable[Maximum][i];
	}
}

void Entity::SetLevel(){
	//Uses the current experience to set an entity's level.
	//If you want to manually set an enemy's level, write a
	//level setter function call and always call it after calling
	//AlterExp()

	int Prior;
	int Base = 100;
	double AugmentFactor = 0.35;
	int tExp = _Exp;

	_Level = 1;

	while (tExp > 1) {
		Prior = Prior * AugmentFactor + Base;
		tExp -= Prior;
		_Level++;
	}
}
<commit_msg>Server/Client setup<commit_after>#include <string>
#include "entity.h"
#include "enums.h"

Entity::Entity(){}
Entity::~Entity(){}

void Entity::AlterExp (int Amount){
	//Use this method to add experience to an entity.  This can add experience
	//for a character, or be used to set the amount of experience an enemy
	//is worth.  (NOTE: A character's level cannot be manually set.  To manually
	//set an enemy's level, write a function in the enemy class to do so.)

	_Exp += Amount;
	SetLevel();
}

int Entity::GetExp(){
	//Basic getter function to return Experience.

	return _Exp;
}

int Entity::GetLevel(){
	//Basic getter function to return Level

	return _Level;
}

void Entity::AlterGold (int Amount){
	//Alter the amount of gold the entity has on hand.

	_Gold += Amount;
}

int Entity::GetGold(){
	//Basic getter function to return the amount of gold on hand.

	return _Gold;
}

int Entity::GetStat(Stats Stat, bool Max){
	//Getter function for any stats defined in the stats enum.
	//This is implemented this way to make it easier to interact with spells and items classes.

	return StatTable[Max ? Maximum : Current][(int) Stat];
}

void Entity::AlterStat (Stats Stat, bool Max, int Amount){
	//Relative setter function for stats.  (You can use this for absolute setting
	//by subtracting the existing value and adding the new value.)

	StatTable[Max ? Maximum : Current][(int) Stat] += Amount;
}

void Entity::SetStatToMax (Stats Stat){
	//Set the given stat's current value to it's max value.  Useful for healing,
	//mana replenishment, adverse effect restoration, etc.

	StatTable[Current][(int) Stat] = StatTable[Maximum][(int) Stat];
}

void Entity::SetAllStatsToMax()
{
	//Set All Stats - For initializing a new or restored entity (usually a player)
	for (int i = 0; i < 14; i++){
		StatTable[Current][i] = StatTable[Maximum][i];
	}
}

void Entity::SetLevel(){
	//Uses the current experience to set an entity's level.
	//If you want to manually set an enemy's level, write a
	//level setter function call and always call it after calling
	//AlterExp()

	double Prior;
	double Base = 100;
	double AugmentFactor = 0.35;
	double tExp = (double)_Exp;

	_Level = 1;

	while (tExp > 1) {
		Prior = Prior * AugmentFactor + Base;
		tExp -= Prior;
		_Level++;
	}
}
<|endoftext|>


<commit_before>// Copyright (c) 2017-2019 Andrey Valyaev <dron.valyaev@gmail.com>
//
// This software may be modified and distributed under the terms
// of the MIT license.  See the LICENSE file for details.

#include "NamedTestTest.h"
#include <2out/2out.h>
#include "ReprTest.h"

using namespace std;
using namespace oout;

// @todo #365 ReprNamedTest should be named NamedTestText
class ReprNamedTest final : public Text {
public:
	explicit ReprNamedTest(const shared_ptr<const Test> &test)
		: test(test)
	{
	}

	string asString() const override
	{
		return JUnitXmlReport(test->result()).asString();
	}
private:
	const shared_ptr<const Test> test;
};

NamedTestTest::NamedTestTest()
	: tests(
		make_unique<NamedTest>(
			"NamedTestTest",
			make_shared<const NamedTest>(
				"NamedTest in TestNamed is a Suite",
				make_shared<ContainTest>(
					make_shared<ReprNamedTest>(
						make_unique<NamedTest>(
							"Root test",
							make_shared<const NamedTest>(
								"Concrete test",
								make_shared<EqualTest>("a", "a")
							)
						)
					),
					"Concrete test"
				)
			)
		)
	)
{
}

unique_ptr<const Result> NamedTestTest::result() const
{
	return tests->result();
}
<commit_msg>#375: ReprNamedText renamed to NamedTestText<commit_after>// Copyright (c) 2017-2019 Andrey Valyaev <dron.valyaev@gmail.com>
//
// This software may be modified and distributed under the terms
// of the MIT license.  See the LICENSE file for details.

#include "NamedTestTest.h"
#include <2out/2out.h>
#include "ReprTest.h"

using namespace std;
using namespace oout;

class NamedTestText final : public Text {
public:
	explicit NamedTestText(const shared_ptr<const Test> &test)
		: test(test)
	{
	}

	string asString() const override
	{
		return JUnitXmlReport(test->result()).asString();
	}
private:
	const shared_ptr<const Test> test;
};

NamedTestTest::NamedTestTest()
	: tests(
		make_unique<NamedTest>(
			"NamedTest test",
			make_shared<const NamedTest>(
				"NamedTest in TestNamed is a Suite",
				make_shared<ContainTest>(
					make_shared<NamedTestText>(
						make_unique<NamedTest>(
							"Root test",
							make_shared<const NamedTest>(
								"Concrete test",
								make_shared<EqualTest>("a", "a")
							)
						)
					),
					"Concrete test"
				)
			)
		)
	)
{
}

unique_ptr<const Result> NamedTestTest::result() const
{
	return tests->result();
}
<|endoftext|>


<commit_before>//It is our future main class

#include <iostream>
#include "graph.h"
#include "minion.h"

/**
* Classe qui représente la classe principale .
*/
using namespace std;

int getRandValue(int min, int max) {
    return (rand()/(int)RAND_MAX)*(max-min)+min;
}

/**
 * Méthode de commencement de la partie de chasse aux minions
 */
int main() {

    //Parametrage
    const int nbMinion = 29; // en minion
    int nbVille = 29; // en minion
    //int tpsVisite = 30;// en min
    //double evapPheromone = 10;
    int nbIteration = 0;

    Graph* graph = new Graph();

    Minion* lesMinions[nbMinion];

    for(int nbMimi = 0; nbMimi < nbMinion; ++nbMimi) {
        int firstPt = getRandValue(0, 29);
        Minion* mimi = new Minion("Serge", firstPt);
        lesMinions[nbMimi] = mimi;

        for(int lieu = 0; lieu < nbVille; ++lieu) {
            do {
                int pt = getRandValue(0, 29);
            }while(!mimi->addPts(pt));

        }
    }

    while(nbIteration != 100){

        for(int nbMimi = 0; nbMimi < nbMinion; ++nbMimi){
            /*pour chaque evenement non visité i :
                choisir une evenement dans la liste des evenements restants
            déposer des bananes sur le trajet*/

        }

        //eVAPORATION DE LA BANANE

        ++nbIteration;
    }

    return 0;
}
<commit_msg>Ajout de machin chose<commit_after>//It is our future main class

#include <iostream>
#include "graph.h"
#include "minion.h"

/**
* Classe qui représente la classe principale .
*/
using namespace std;

int getRandValue(int min, int max) {
    return (rand()/(int)RAND_MAX)*(max-min)+min;
}

/**
 * Méthode de commencement de la partie de chasse aux minions
 */
int main() {

    //Parametrage
    const int nbMinion = 29; // en minion
    const int nbVille = 29; // en minion
    //int tpsVisite = 30;// en min
    //double evapPheromone = 10;
    const int nbIteration = 0;

    Graph* graph = new Graph();

    Minion* lesMinions[nbMinion];

    for(int nbMimi = 0; nbMimi < nbMinion; ++nbMimi) {
        int firstPt = getRandValue(0, 29);
        Minion* mimi = new Minion("Serge", firstPt);
        lesMinions[nbMimi] = mimi;

        for(int lieu = 0; lieu < nbVille; ++lieu) {
            do {
                int pt = getRandValue(0, 29);
            }while(!mimi->addPts(pt));

        }
    }

    while(nbIteration != 100){

        for(int nbMimi = 0; nbMimi < nbMinion; ++nbMimi){
            /*pour chaque evenement non visité i :
                choisir une evenement dans la liste des evenements restants
            déposer des bananes sur le trajet*/

        }

        //eVAPORATION DE LA BANANE

        ++nbIteration;
    }

    return 0;
}
<|endoftext|>