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

#ifndef RJ_CORE_GAME_WINDOW_HPP
#define RJ_CORE_GAME_WINDOW_HPP

#include "game_updater.hpp"
#include <rectojump/shared/input.hpp>

#include <mlk/log/log.h>
#include <mlk/signals_slots/slot.h>
#include <mlk/time/time.h>
#include <mlk/types/types.h>

#include <SFML/Graphics.hpp>

namespace rj
{
	using window_style = int;

	class game_window
	{
		mlk::uint m_width, m_height;
		std::string m_title{"Recto Jump"};
		sf::RenderWindow m_window;
		window_style m_windowstyles;
		bool m_running{false};
		bool m_need_recreate{false};

		input& m_input{input::get()};

		game_updater m_game_updater;

	public:
		mlk::slot<> on_stop;

		game_window(const vec2u& size, bool fullscreen = false) :
			m_width{size.x},
			m_height{size.y}
		{
			this->set_fullscreen(fullscreen);
			this->init();
		}

		// interface
		void start()
		{
			if(m_running) return;

			this->prepare_start();
			while(m_running)
			{
				if(m_need_recreate)
					this->recreate();

				m_game_updater.start_pt();

				// update
				this->update_events();
				m_input.update(m_window.mapPixelToCoords(sf::Mouse::getPosition(m_window)));
				m_game_updater.update();

				// render
				m_window.clear();
				m_game_updater.render();
				m_window.display();

				m_game_updater.end_pt();
			}
		}

		void stop() noexcept
		{on_stop(); m_running = false;}

		template<typename... Args>
		void draw(Args&&... args)
		{m_window.draw(std::forward<Args>(args)...);}

		void toggle_fullscreen() noexcept
		{
			m_windowstyles ^= sf::Style::Fullscreen;
			m_need_recreate = true;
		}

		void toggle_titlebar() noexcept
		{
			m_windowstyles ^= sf::Style::Titlebar;
			m_need_recreate = true;
		}

		// setters
		void set_framereate_limit(mlk::uint limit) noexcept
		{m_window.setFramerateLimit(limit);}

		void set_size(const vec2u& size) noexcept
		{m_window.setSize(size);}

		void set_position(const vec2i& position) noexcept
		{m_window.setPosition(position);}

		void set_fullscreen(bool b) noexcept
		{
			if(b == (m_windowstyles & sf::Style::Fullscreen))
				return;
			b ? m_windowstyles |= sf::Style::Fullscreen : m_windowstyles &= ~sf::Style::Fullscreen;
			m_need_recreate = true;
		}

		void set_titlebar(bool b) noexcept
		{
			if(b == (m_windowstyles & sf::Style::Titlebar))
				return;
			b ? m_windowstyles |= sf::Style::Titlebar : m_windowstyles &= ~sf::Style::Titlebar;
			m_need_recreate = true;
		}

		void set_view(const sf::View& v) noexcept
		{m_window.setView(v);}

		// getters
		game_updater& get_updater() noexcept
		{return m_game_updater;}

		vec2u get_size() const noexcept
		{return m_window.getSize();}

		vec2i get_position() const noexcept
		{return m_window.getPosition();}

		bool get_fullscreen() const noexcept
		{return m_windowstyles & sf::Style::Fullscreen;}

		bool get_titlebar() const noexcept
		{return m_windowstyles & sf::Style::Titlebar;}

	private:
		void init()
		{
			m_windowstyles |= sf::Style::Default;
			this->recreate();
		}

		void prepare_start() noexcept
		{
			m_running = true;
			mlk::lout("rj::game_window", true) << "starting gamewindow";
		}

		void update_events() noexcept
		{
			sf::Event ev;
			while(m_window.pollEvent(ev))
			{
				switch(ev.type)
				{
				case sf::Event::EventType::Closed:
					this->stop();
					break;
				case sf::Event::EventType::KeyPressed:
					m_input.key_pressed(ev.key.code);
					break;
				case sf::Event::EventType::KeyReleased:
					m_input.key_released(ev.key.code);
					break;
				case sf::Event::EventType::MouseButtonPressed:
					m_input.btn_pressed(ev.mouseButton.button);
					break;
				case sf::Event::EventType::MouseButtonReleased:
					m_input.btn_released(ev.mouseButton.button);
					break;
				case sf::Event::EventType::MouseWheelMoved:
					m_input.mousewheel_moved(ev.mouseWheel.delta);
					break;
				default: break;
				}
			}
		}

		void recreate()
		{
			m_window.close();
			m_window.create({m_width, m_height}, m_title, m_windowstyles);
			m_need_recreate = false;
		}
	};
}

#endif // RJ_CORE_GAME_WINDOW_HPP
<commit_msg>game_window: added on_event (catching sfml events)<commit_after>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//

#ifndef RJ_CORE_GAME_WINDOW_HPP
#define RJ_CORE_GAME_WINDOW_HPP

#include "game_updater.hpp"
#include <rectojump/shared/input.hpp>

#include <mlk/log/log.h>
#include <mlk/signals_slots/slot.h>
#include <mlk/time/time.h>
#include <mlk/types/types.h>

#include <SFML/Graphics.hpp>

namespace rj
{
	using window_style = int;

	class game_window
	{
		mlk::uint m_width, m_height;
		std::string m_title{"Recto Jump"};
		sf::RenderWindow m_window;
		window_style m_windowstyles;
		bool m_running{false};
		bool m_need_recreate{false};

		game_updater m_game_updater;
		input& m_input{input::get()};

		mlk::event_delegates<sf::Event::EventType, sf::Event> m_on_event;

	public:
		mlk::slot<> on_stop;

		game_window(const vec2u& size, bool fullscreen = false) :
			m_width{size.x},
			m_height{size.y}
		{
			this->set_fullscreen(fullscreen);
			this->init();
		}

		// interface
		void start()
		{
			if(m_running) return;

			this->prepare_start();
			while(m_running)
			{
				if(m_need_recreate)
					this->recreate();

				m_game_updater.start_pt();

				// update
				this->update_events();
				m_input.update(m_window.mapPixelToCoords(sf::Mouse::getPosition(m_window)));
				m_game_updater.update();

				// render
				m_window.clear();
				m_game_updater.render();
				m_window.display();

				m_game_updater.end_pt();
			}
		}

		void stop() noexcept
		{on_stop(); m_running = false;}

		auto on_event(sf::Event::EventType type)
		-> decltype(m_on_event[type])&
		{return m_on_event[type];}

		template<typename... Args>
		void draw(Args&&... args)
		{m_window.draw(std::forward<Args>(args)...);}

		void toggle_fullscreen() noexcept
		{
			m_windowstyles ^= sf::Style::Fullscreen;
			m_need_recreate = true;
		}

		void toggle_titlebar() noexcept
		{
			m_windowstyles ^= sf::Style::Titlebar;
			m_need_recreate = true;
		}

		// setters
		void set_framereate_limit(mlk::uint limit) noexcept
		{m_window.setFramerateLimit(limit);}

		void set_size(const vec2u& size) noexcept
		{m_window.setSize(size);}

		void set_position(const vec2i& position) noexcept
		{m_window.setPosition(position);}

		void set_fullscreen(bool b) noexcept
		{
			if(b == (m_windowstyles & sf::Style::Fullscreen))
				return;
			b ? m_windowstyles |= sf::Style::Fullscreen : m_windowstyles &= ~sf::Style::Fullscreen;
			m_need_recreate = true;
		}

		void set_titlebar(bool b) noexcept
		{
			if(b == (m_windowstyles & sf::Style::Titlebar))
				return;
			b ? m_windowstyles |= sf::Style::Titlebar : m_windowstyles &= ~sf::Style::Titlebar;
			m_need_recreate = true;
		}

		void set_view(const sf::View& v) noexcept
		{m_window.setView(v);}

		// getters
		game_updater& get_updater() noexcept
		{return m_game_updater;}

		vec2u get_size() const noexcept
		{return m_window.getSize();}

		vec2i get_position() const noexcept
		{return m_window.getPosition();}

		bool get_fullscreen() const noexcept
		{return m_windowstyles & sf::Style::Fullscreen;}

		bool get_titlebar() const noexcept
		{return m_windowstyles & sf::Style::Titlebar;}

	private:
		void init()
		{
			m_windowstyles |= sf::Style::Default;
			this->recreate();
		}

		void prepare_start() noexcept
		{
			m_running = true;
			mlk::lout("rj::game_window", true) << "starting gamewindow";
		}

		void update_events() noexcept
		{
			sf::Event ev;
			while(m_window.pollEvent(ev))
			{
				switch(ev.type)
				{
				case sf::Event::EventType::Closed:
					this->stop();
					break;
				case sf::Event::EventType::KeyPressed:
					m_input.key_pressed(ev.key.code);
					break;
				case sf::Event::EventType::KeyReleased:
					m_input.key_released(ev.key.code);
					break;
				case sf::Event::EventType::MouseButtonPressed:
					m_input.btn_pressed(ev.mouseButton.button);
					break;
				case sf::Event::EventType::MouseButtonReleased:
					m_input.btn_released(ev.mouseButton.button);
					break;
				case sf::Event::EventType::MouseWheelMoved:
					m_input.mousewheel_moved(ev.mouseWheel.delta);
					break;
				default: break;
				}

				// call custom on_event
				m_on_event[ev.type](ev);
			}
		}

		void recreate()
		{
			m_window.close();
			m_window.create({m_width, m_height}, m_title, m_windowstyles);
			m_need_recreate = false;
		}
	};
}

#endif // RJ_CORE_GAME_WINDOW_HPP
<|endoftext|>


<commit_before>#pragma once
#include <staticjson/basic.hpp>

#include <limits>
#include <string>
#include <type_traits>

namespace staticjson
{

template <class IntType>
class IntegerHandler : public BaseHandler
{
    static_assert(std::is_arithmetic<IntType>::value, "Only arithmetic types are allowed");

protected:
    IntType* m_value;

    template <class AnotherIntType>
    bool is_out_of_range(AnotherIntType a)
    {
        typedef typename std::common_type<IntType, AnotherIntType>::type CommonType;
        bool this_signed = std::numeric_limits<IntType>::is_signed,
             that_signed = std::numeric_limits<AnotherIntType>::is_signed;

        if (this_signed == that_signed)
            return CommonType(a) < CommonType(std::numeric_limits<IntType>::min())
                || CommonType(a) > CommonType(std::numeric_limits<IntType>::max());

        if (this_signed)
            return CommonType(a) > CommonType(std::numeric_limits<IntType>::max());

        return a < 0 || CommonType(a) > CommonType(std::numeric_limits<IntType>::max());
    }

public:
    explicit IntegerHandler(IntType* value) : m_value(value) {}

    bool Int(int i) override
    {
        if (is_out_of_range(i))
            return set_out_of_range("int");
        *m_value = static_cast<IntType>(i);
        this->parsed = true;
        return true;
    }

    bool Uint(unsigned i) override
    {
        if (is_out_of_range(i))
            return set_out_of_range("unsigned int");
        *m_value = static_cast<IntType>(i);
        this->parsed = true;
        return true;
    }

    bool Int64(std::int64_t i) override
    {
        if (is_out_of_range(i))
            return set_out_of_range("std::int64_t");
        *m_value = static_cast<IntType>(i);
        this->parsed = true;
        return true;
    }

    bool Uint64(std::uint64_t i) override
    {
        if (is_out_of_range(i))
            return set_out_of_range("std::uint64_t");
        *m_value = static_cast<IntType>(i);
        this->parsed = true;
        return true;
    }

    bool Double(double d) override
    {
        *m_value = static_cast<IntType>(d);
        if (static_cast<double>(*m_value) != d)
            return set_out_of_range("double");
        this->parsed = true;
        return true;
    }

    bool write(IHandler* output) const override
    {
        if (std::numeric_limits<IntType>::is_signed)
        {
            return output->Int64(*m_value);
        }
        else
        {
            return output->Uint64(*m_value);
        }
    }

    void generate_schema(Value& output, MemoryPoolAllocator& alloc) const override
    {
        output.SetObject();
        output.AddMember(rapidjson::StringRef("type"), rapidjson::StringRef("integer"), alloc);
        Value minimum, maximum;
        if (std::numeric_limits<IntType>::is_signed)
        {
            minimum.SetInt64(std::numeric_limits<IntType>::min());
            maximum.SetInt64(std::numeric_limits<IntType>::max());
        }
        else
        {
            minimum.SetUint64(std::numeric_limits<IntType>::min());
            maximum.SetUint64(std::numeric_limits<IntType>::max());
        }
        output.AddMember(rapidjson::StringRef("minimum"), minimum, alloc);
        output.AddMember(rapidjson::StringRef("maximum"), maximum, alloc);
    }
};

template <>
class Handler<std::nullptr_t> : public BaseHandler
{
public:
    explicit Handler(std::nullptr_t*) {}

    bool Null() override { return true; }

    std::string type_name() const override { return "null"; }

    bool write(IHandler* output) const override { return output->Null(); }

    void generate_schema(Value& output, MemoryPoolAllocator& alloc) const override
    {
        output.SetObject();
        output.AddMember(rapidjson::StringRef("type"), rapidjson::StringRef("null"), alloc);
    }
};

template <>
class Handler<bool> : public BaseHandler
{
private:
    bool* m_value;

public:
    explicit Handler(bool* value) : m_value(value) {}

    bool Bool(bool v) override
    {
        *m_value = v;
        this->parsed = true;
        return true;
    }

    std::string type_name() const override { return "bool"; }

    bool write(IHandler* output) const override { return output->Bool(*m_value); }

    void generate_schema(Value& output, MemoryPoolAllocator& alloc) const override
    {
        output.SetObject();
        output.AddMember(rapidjson::StringRef("type"), rapidjson::StringRef("boolean"), alloc);
    }
};

template <>
class Handler<int> : public IntegerHandler<int>
{
public:
    explicit Handler(int* i) : IntegerHandler<int>(i) {}

    std::string type_name() const override { return "int"; }

    bool write(IHandler* output) const override { return output->Int(*m_value); }
};

template <>
class Handler<unsigned int> : public IntegerHandler<unsigned int>
{
public:
    explicit Handler(unsigned* i) : IntegerHandler<unsigned int>(i) {}

    std::string type_name() const override { return "unsigned int"; }

    bool write(IHandler* output) const override { return output->Uint(*m_value); }
};

template <>
class Handler<long> : public IntegerHandler<long>
{
public:
    explicit Handler(long* i) : IntegerHandler<long>(i) {}

    std::string type_name() const override { return "long"; }
};

template <>
class Handler<unsigned long> : public IntegerHandler<unsigned long>
{
public:
    explicit Handler(unsigned long* i) : IntegerHandler<unsigned long>(i) {}

    std::string type_name() const override { return "unsigned long"; }
};

template <>
class Handler<long long> : public IntegerHandler<long long>
{
public:
    explicit Handler(long long* i) : IntegerHandler<long long>(i) {}

    std::string type_name() const override { return "long long"; }
};

template <>
class Handler<unsigned long long> : public IntegerHandler<unsigned long long>
{
public:
    explicit Handler(unsigned long long* i) : IntegerHandler<unsigned long long>(i) {}

    std::string type_name() const override { return "unsigned long long"; }
};

// char is an alias for bool to work around the stupid `std::vector<bool>`
template <>
class Handler<char> : public BaseHandler
{
private:
    char* m_value;

public:
    explicit Handler(char* i) : m_value(i) {}

    std::string type_name() const override { return "bool"; }

    bool Bool(bool v) override
    {
        *this->m_value = v;
        this->parsed = true;
        return true;
    }

    bool write(IHandler* out) const override { return out->Bool(*m_value); }

    void generate_schema(Value& output, MemoryPoolAllocator& alloc) const override
    {
        output.SetObject();
        output.AddMember(rapidjson::StringRef("type"), rapidjson::StringRef("boolean"), alloc);
    }
};

template <>
class Handler<double> : public BaseHandler
{
private:
    double* m_value;

public:
    explicit Handler(double* v) : m_value(v) {}

    bool Int(int i) override
    {
        *m_value = i;
        this->parsed = true;
        return true;
    }

    bool Uint(unsigned i) override
    {
        *m_value = i;
        this->parsed = true;
        return true;
    }

    bool Int64(std::int64_t i) override
    {
        *m_value = static_cast<double>(i);
        if (static_cast<decltype(i)>(*m_value) != i)
            return set_out_of_range("std::int64_t");
        this->parsed = true;
        return true;
    }

    bool Uint64(std::uint64_t i) override
    {
        *m_value = static_cast<double>(i);
        if (static_cast<decltype(i)>(*m_value) != i)
            return set_out_of_range("std::uint64_t");
        this->parsed = true;
        return true;
    }

    bool Double(double d) override
    {
        *m_value = d;
        this->parsed = true;
        return true;
    }

    std::string type_name() const override { return "double"; }

    bool write(IHandler* out) const override { return out->Double(*m_value); }

    void generate_schema(Value& output, MemoryPoolAllocator& alloc) const override
    {
        output.SetObject();
        output.AddMember(rapidjson::StringRef("type"), rapidjson::StringRef("number"), alloc);
    }
};

template <>
class Handler<float> : public BaseHandler
{
private:
    float* m_value;

public:
    explicit Handler(float* v) : m_value(v) {}

    bool Int(int i) override
    {
        *m_value = i;
        if (static_cast<decltype(i)>(*m_value) != i)
            return set_out_of_range("int");
        this->parsed = true;
        return true;
    }

    bool Uint(unsigned i) override
    {
        *m_value = i;
        if (static_cast<decltype(i)>(*m_value) != i)
            return set_out_of_range("unsigned int");
        this->parsed = true;
        return true;
    }

    bool Int64(std::int64_t i) override
    {
        *m_value = static_cast<float>(i);
        if (static_cast<decltype(i)>(*m_value) != i)
            return set_out_of_range("std::int64_t");
        this->parsed = true;
        return true;
    }

    bool Uint64(std::uint64_t i) override
    {
        *m_value = static_cast<float>(i);
        if (static_cast<decltype(i)>(*m_value) != i)
            return set_out_of_range("std::uint64_t");
        this->parsed = true;
        return true;
    }

    bool Double(double d) override
    {
        *m_value = d;
        if (static_cast<decltype(d)>(*m_value) != d)
            return set_out_of_range("double");
        this->parsed = true;
        return true;
    }

    std::string type_name() const override { return "float"; }

    bool write(IHandler* out) const override { return out->Double(*m_value); }

    void generate_schema(Value& output, MemoryPoolAllocator& alloc) const override
    {
        output.SetObject();
        output.AddMember(rapidjson::StringRef("type"), rapidjson::StringRef("number"), alloc);
    }
};

template <>
class Handler<std::string> : public BaseHandler
{
private:
    std::string* m_value;

public:
    explicit Handler(std::string* v) : m_value(v) {}

    bool String(const char* str, SizeType length, bool) override
    {
        m_value->assign(str, length);
        this->parsed = true;
        return true;
    }

    std::string type_name() const override { return "string"; }

    bool write(IHandler* out) const override
    {
        return out->String(m_value->data(), SizeType(m_value->size()), true);
    }

    void generate_schema(Value& output, MemoryPoolAllocator& alloc) const override
    {
        output.SetObject();
        output.AddMember(rapidjson::StringRef("type"), rapidjson::StringRef("string"), alloc);
    }
};
}
<commit_msg>Reduced code duplication in IntegerHandler<commit_after>#pragma once
#include <staticjson/basic.hpp>

#include <limits>
#include <string>
#include <type_traits>

namespace staticjson
{

template <class IntType>
class IntegerHandler : public BaseHandler
{
    static_assert(std::is_arithmetic<IntType>::value, "Only arithmetic types are allowed");

protected:
    IntType* m_value;

    template <class AnotherIntType>
    bool is_out_of_range(AnotherIntType a)
    {
        typedef typename std::common_type<IntType, AnotherIntType>::type CommonType;
        bool this_signed = std::numeric_limits<IntType>::is_signed,
             that_signed = std::numeric_limits<AnotherIntType>::is_signed;

        if (this_signed == that_signed)
            return CommonType(a) < CommonType(std::numeric_limits<IntType>::min())
                || CommonType(a) > CommonType(std::numeric_limits<IntType>::max());

        if (this_signed)
            return CommonType(a) > CommonType(std::numeric_limits<IntType>::max());

        return a < 0 || CommonType(a) > CommonType(std::numeric_limits<IntType>::max());
    }

    template<class ReceiveIntType>
    bool recieve(ReceiveIntType r, const char* actual_type)
    {
        if (is_out_of_range(r))
            return set_out_of_range(actual_type);
        *m_value = static_cast<IntType>(r);
        this->parsed = true;
        return true;
    }

public:
    explicit IntegerHandler(IntType* value) : m_value(value) {}

    bool Int(int i) override
    {
        return recieve(i, "int");
    }

    bool Uint(unsigned i) override
    {
        return receive(i, "unsigned int");
    }

    bool Int64(std::int64_t i) override
    {
        return receive(i, "std::int64_t");
    }

    bool Uint64(std::uint64_t i) override
    {
        return receive(i, "std::uint64_t");
    }

    bool Double(double d) override
    {
        IntType val = static_cast<IntType>(d);
        if (static_cast<double>(val) != d)
            return set_out_of_range("double");
        *m_value = val;
        this->parsed = true;
        return true;
    }

    bool write(IHandler* output) const override
    {
        if (std::numeric_limits<IntType>::is_signed)
        {
            return output->Int64(*m_value);
        }
        else
        {
            return output->Uint64(*m_value);
        }
    }

    void generate_schema(Value& output, MemoryPoolAllocator& alloc) const override
    {
        output.SetObject();
        output.AddMember(rapidjson::StringRef("type"), rapidjson::StringRef("integer"), alloc);
        Value minimum, maximum;
        if (std::numeric_limits<IntType>::is_signed)
        {
            minimum.SetInt64(std::numeric_limits<IntType>::min());
            maximum.SetInt64(std::numeric_limits<IntType>::max());
        }
        else
        {
            minimum.SetUint64(std::numeric_limits<IntType>::min());
            maximum.SetUint64(std::numeric_limits<IntType>::max());
        }
        output.AddMember(rapidjson::StringRef("minimum"), minimum, alloc);
        output.AddMember(rapidjson::StringRef("maximum"), maximum, alloc);
    }
};

template <>
class Handler<std::nullptr_t> : public BaseHandler
{
public:
    explicit Handler(std::nullptr_t*) {}

    bool Null() override { return true; }

    std::string type_name() const override { return "null"; }

    bool write(IHandler* output) const override { return output->Null(); }

    void generate_schema(Value& output, MemoryPoolAllocator& alloc) const override
    {
        output.SetObject();
        output.AddMember(rapidjson::StringRef("type"), rapidjson::StringRef("null"), alloc);
    }
};

template <>
class Handler<bool> : public BaseHandler
{
private:
    bool* m_value;

public:
    explicit Handler(bool* value) : m_value(value) {}

    bool Bool(bool v) override
    {
        *m_value = v;
        this->parsed = true;
        return true;
    }

    std::string type_name() const override { return "bool"; }

    bool write(IHandler* output) const override { return output->Bool(*m_value); }

    void generate_schema(Value& output, MemoryPoolAllocator& alloc) const override
    {
        output.SetObject();
        output.AddMember(rapidjson::StringRef("type"), rapidjson::StringRef("boolean"), alloc);
    }
};

template <>
class Handler<int> : public IntegerHandler<int>
{
public:
    explicit Handler(int* i) : IntegerHandler<int>(i) {}

    std::string type_name() const override { return "int"; }

    bool write(IHandler* output) const override { return output->Int(*m_value); }
};

template <>
class Handler<unsigned int> : public IntegerHandler<unsigned int>
{
public:
    explicit Handler(unsigned* i) : IntegerHandler<unsigned int>(i) {}

    std::string type_name() const override { return "unsigned int"; }

    bool write(IHandler* output) const override { return output->Uint(*m_value); }
};

template <>
class Handler<long> : public IntegerHandler<long>
{
public:
    explicit Handler(long* i) : IntegerHandler<long>(i) {}

    std::string type_name() const override { return "long"; }
};

template <>
class Handler<unsigned long> : public IntegerHandler<unsigned long>
{
public:
    explicit Handler(unsigned long* i) : IntegerHandler<unsigned long>(i) {}

    std::string type_name() const override { return "unsigned long"; }
};

template <>
class Handler<long long> : public IntegerHandler<long long>
{
public:
    explicit Handler(long long* i) : IntegerHandler<long long>(i) {}

    std::string type_name() const override { return "long long"; }
};

template <>
class Handler<unsigned long long> : public IntegerHandler<unsigned long long>
{
public:
    explicit Handler(unsigned long long* i) : IntegerHandler<unsigned long long>(i) {}

    std::string type_name() const override { return "unsigned long long"; }
};

// char is an alias for bool to work around the stupid `std::vector<bool>`
template <>
class Handler<char> : public BaseHandler
{
private:
    char* m_value;

public:
    explicit Handler(char* i) : m_value(i) {}

    std::string type_name() const override { return "bool"; }

    bool Bool(bool v) override
    {
        *this->m_value = v;
        this->parsed = true;
        return true;
    }

    bool write(IHandler* out) const override { return out->Bool(*m_value); }

    void generate_schema(Value& output, MemoryPoolAllocator& alloc) const override
    {
        output.SetObject();
        output.AddMember(rapidjson::StringRef("type"), rapidjson::StringRef("boolean"), alloc);
    }
};

template <>
class Handler<double> : public BaseHandler
{
private:
    double* m_value;

public:
    explicit Handler(double* v) : m_value(v) {}

    bool Int(int i) override
    {
        *m_value = i;
        this->parsed = true;
        return true;
    }

    bool Uint(unsigned i) override
    {
        *m_value = i;
        this->parsed = true;
        return true;
    }

    bool Int64(std::int64_t i) override
    {
        *m_value = static_cast<double>(i);
        if (static_cast<decltype(i)>(*m_value) != i)
            return set_out_of_range("std::int64_t");
        this->parsed = true;
        return true;
    }

    bool Uint64(std::uint64_t i) override
    {
        *m_value = static_cast<double>(i);
        if (static_cast<decltype(i)>(*m_value) != i)
            return set_out_of_range("std::uint64_t");
        this->parsed = true;
        return true;
    }

    bool Double(double d) override
    {
        *m_value = d;
        this->parsed = true;
        return true;
    }

    std::string type_name() const override { return "double"; }

    bool write(IHandler* out) const override { return out->Double(*m_value); }

    void generate_schema(Value& output, MemoryPoolAllocator& alloc) const override
    {
        output.SetObject();
        output.AddMember(rapidjson::StringRef("type"), rapidjson::StringRef("number"), alloc);
    }
};

template <>
class Handler<float> : public BaseHandler
{
private:
    float* m_value;

public:
    explicit Handler(float* v) : m_value(v) {}

    bool Int(int i) override
    {
        *m_value = i;
        if (static_cast<decltype(i)>(*m_value) != i)
            return set_out_of_range("int");
        this->parsed = true;
        return true;
    }

    bool Uint(unsigned i) override
    {
        *m_value = i;
        if (static_cast<decltype(i)>(*m_value) != i)
            return set_out_of_range("unsigned int");
        this->parsed = true;
        return true;
    }

    bool Int64(std::int64_t i) override
    {
        *m_value = static_cast<float>(i);
        if (static_cast<decltype(i)>(*m_value) != i)
            return set_out_of_range("std::int64_t");
        this->parsed = true;
        return true;
    }

    bool Uint64(std::uint64_t i) override
    {
        *m_value = static_cast<float>(i);
        if (static_cast<decltype(i)>(*m_value) != i)
            return set_out_of_range("std::uint64_t");
        this->parsed = true;
        return true;
    }

    bool Double(double d) override
    {
        *m_value = d;
        if (static_cast<decltype(d)>(*m_value) != d)
            return set_out_of_range("double");
        this->parsed = true;
        return true;
    }

    std::string type_name() const override { return "float"; }

    bool write(IHandler* out) const override { return out->Double(*m_value); }

    void generate_schema(Value& output, MemoryPoolAllocator& alloc) const override
    {
        output.SetObject();
        output.AddMember(rapidjson::StringRef("type"), rapidjson::StringRef("number"), alloc);
    }
};

template <>
class Handler<std::string> : public BaseHandler
{
private:
    std::string* m_value;

public:
    explicit Handler(std::string* v) : m_value(v) {}

    bool String(const char* str, SizeType length, bool) override
    {
        m_value->assign(str, length);
        this->parsed = true;
        return true;
    }

    std::string type_name() const override { return "string"; }

    bool write(IHandler* out) const override
    {
        return out->String(m_value->data(), SizeType(m_value->size()), true);
    }

    void generate_schema(Value& output, MemoryPoolAllocator& alloc) const override
    {
        output.SetObject();
        output.AddMember(rapidjson::StringRef("type"), rapidjson::StringRef("string"), alloc);
    }
};
}
<|endoftext|>


<commit_before>// Copyright (c) 2017 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/

#ifndef TAOCPP_PEGTL_INCLUDE_INTERNAL_IF_APPLY_HH
#define TAOCPP_PEGTL_INCLUDE_INTERNAL_IF_APPLY_HH

#include "../config.hh"

#include "skip_control.hh"
#include "rule_match_one.hh"

namespace TAOCPP_PEGTL_NAMESPACE
{
   namespace internal
   {
      template< apply_mode A, typename Rule, typename ... Actions >
      struct if_apply_impl;

      template< typename Rule, typename ... Actions >
      struct if_apply_impl< apply_mode::ACTION, Rule, Actions ... >
      {
         template< rewind_mode, template< typename ... > class Action, template< typename ... > class Control, typename Input, typename ... States >
         static bool match( Input & in, States && ... st )
         {
            using action_t = typename Input::action_t;

            auto m = in.template mark< rewind_mode::REQUIRED >();

            if ( rule_match_one< Rule, apply_mode::ACTION, rewind_mode::ACTIVE, Action, Control >::match( in, st ... ) ) {
               const action_t i2( m.count(), in.begin(), in.source() );
               using swallow = bool[];
               (void)swallow{ ( Actions::apply( i2, st ... ), true ) ..., true };
               return m( true );
            }
            return false;
         }
      };

      template< typename Rule, typename ... Actions >
      struct if_apply_impl< apply_mode::NOTHING, Rule, Actions ... >
      {
         template< rewind_mode M, template< typename ... > class Action, template< typename ... > class Control, typename Input, typename ... States >
         static bool match( Input & in, States && ... st )
         {
            return rule_match_one< Rule, apply_mode::NOTHING, M, Action, Control >::match( in, st ... );
         }
      };

      template< typename Rule, typename ... Actions >
      struct if_apply
      {
         using analyze_t = typename Rule::analyze_t;

         template< apply_mode A, rewind_mode M, template< typename ... > class Action, template< typename ... > class Control, typename Input, typename ... States >
         static bool match( Input & in, States && ... st )
         {
            return if_apply_impl< A, Rule, Actions ... >::template match< M, Action, Control >( in, st ... );
         }
      };

      template< typename Rule, typename ... Actions >
      struct skip_control< if_apply< Rule, Actions ... > > : std::true_type {};

   } // namespace internal

} // namespace TAOCPP_PEGTL_NAMESPACE

#endif
<commit_msg>Consistency.<commit_after>// Copyright (c) 2017 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/

#ifndef TAOCPP_PEGTL_INCLUDE_INTERNAL_IF_APPLY_HH
#define TAOCPP_PEGTL_INCLUDE_INTERNAL_IF_APPLY_HH

#include "../config.hh"

#include "skip_control.hh"

namespace TAOCPP_PEGTL_NAMESPACE
{
   namespace internal
   {
      template< apply_mode A, typename Rule, typename ... Actions >
      struct if_apply_impl;

      template< typename Rule, typename ... Actions >
      struct if_apply_impl< apply_mode::ACTION, Rule, Actions ... >
      {
         template< rewind_mode, template< typename ... > class Action, template< typename ... > class Control, typename Input, typename ... States >
         static bool match( Input & in, States && ... st )
         {
            using action_t = typename Input::action_t;

            auto m = in.template mark< rewind_mode::REQUIRED >();

            if ( Control< Rule >::template match< apply_mode::ACTION, rewind_mode::ACTIVE, Action, Control >( in, st ... ) ) {
               const action_t i2( m.count(), in.begin(), in.source() );
               using swallow = bool[];
               (void)swallow{ ( Actions::apply( i2, st ... ), true ) ..., true };
               return m( true );
            }
            return false;
         }
      };

      template< typename Rule, typename ... Actions >
      struct if_apply_impl< apply_mode::NOTHING, Rule, Actions ... >
      {
         template< rewind_mode M, template< typename ... > class Action, template< typename ... > class Control, typename Input, typename ... States >
         static bool match( Input & in, States && ... st )
         {
            return Control< Rule >::template match< apply_mode::NOTHING, M, Action, Control >( in, st ... );
         }
      };

      template< typename Rule, typename ... Actions >
      struct if_apply
      {
         using analyze_t = typename Rule::analyze_t;

         template< apply_mode A, rewind_mode M, template< typename ... > class Action, template< typename ... > class Control, typename Input, typename ... States >
         static bool match( Input & in, States && ... st )
         {
            return if_apply_impl< A, Rule, Actions ... >::template match< M, Action, Control >( in, st ... );
         }
      };

      template< typename Rule, typename ... Actions >
      struct skip_control< if_apply< Rule, Actions ... > > : std::true_type {};

   } // namespace internal

} // namespace TAOCPP_PEGTL_NAMESPACE

#endif
<|endoftext|>


<commit_before>// Copyright (c) 2015, Tom Honermann
//
// This file is distributed under the MIT License. See the accompanying file
// LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms
// and conditions.

#ifndef TEXT_VIEW_CHARACTER_HPP // {
#define TEXT_VIEW_CHARACTER_HPP

#include <text_view_detail/concepts.hpp>
#include <text_view_detail/charsets/any_charset.hpp>

namespace std {
namespace experimental {
inline namespace text {

template<Character_set CST>
class character {
public:
    using character_set_type = CST;
    using code_point_type = typename character_set_type::code_point_type;

    character() = default;
    explicit character(code_point_type code_point)
        : code_point{code_point} {}

    friend bool operator==(
        const character &l,
        const character &r)
    {
        return l.code_point == r.code_point;
    }
    friend bool operator!=(
        const character &l,
        const character &r)
    {
        return !(l == r);
    }

    void set_code_point(code_point_type code_point) {
        this->code_point = code_point;
    }
    code_point_type get_code_point() const {
        return code_point;
    }

    static character_set_id get_character_set_id() {
        return std::experimental::text::get_character_set_id<CST>();
    }

private:
    code_point_type code_point = {};
};

/*
 * character specialization for the any_character_set character set.
 */
template<>
class character<any_character_set> {
public:
    using character_set_type = any_character_set;
    using code_point_type = typename character_set_type::code_point_type;

    character() = default;
    explicit character(code_point_type code_point)
        : cs_id{std::experimental::text::get_character_set_id<any_character_set>()}, code_point{code_point} {}
    character(character_set_id cs_id, code_point_type code_point)
        : cs_id{cs_id}, code_point{code_point} {}

    friend bool operator==(
        const character &l,
        const character &r)
    {
        return l.cs_id == r.cs_id
            && l.code_point == r.code_point;
    }
    friend bool operator!=(
        const character &l,
        const character &r)
    {
        return !(l == r);
    }

    void set_code_point(code_point_type code_point) {
        this->code_point = code_point;
    }
    code_point_type get_code_point() const {
        return code_point;
    }

    void set_character_set_id(character_set_id new_cs_id) {
        cs_id = new_cs_id;
    }
    character_set_id get_character_set_id() const {
        return cs_id;
    }

private:
    character_set_id cs_id = std::experimental::text::get_character_set_id<any_character_set>();
    code_point_type code_point = {};
};

template<Character_set CST>
bool operator==(
    const character<any_character_set> &c1,
    const character<CST> &c2)
{
    return c1.get_character_set_id() == c2.get_character_set_id()
        && c1.get_code_point() == c2.get_code_point();
}

template<Character_set CST>
bool operator==(
    const character<CST> &c1,
    const character<any_character_set> &c2)
{
    return c1.get_character_set_id() == c2.get_character_set_id()
        && c1.get_code_point() == c2.get_code_point();
}

template<Character_set CST>
bool operator!=(
    const character<any_character_set> &c1,
    const character<CST> &c2)
{
    return !(c1 == c2);
}

template<Character_set CST>
bool operator!=(
    const character<CST> &c1,
    const character<any_character_set> &c2)
{
    return !(c1 == c2);
}

} // inline namespace text
} // namespace experimental
} // namespace std

#endif // } TEXT_VIEW_CHARACTER_HPP
<commit_msg>Removed a redundant class data member initializer; line wrapping.<commit_after>// Copyright (c) 2015, Tom Honermann
//
// This file is distributed under the MIT License. See the accompanying file
// LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms
// and conditions.

#ifndef TEXT_VIEW_CHARACTER_HPP // {
#define TEXT_VIEW_CHARACTER_HPP

#include <text_view_detail/concepts.hpp>
#include <text_view_detail/charsets/any_charset.hpp>

namespace std {
namespace experimental {
inline namespace text {

template<Character_set CST>
class character {
public:
    using character_set_type = CST;
    using code_point_type = typename character_set_type::code_point_type;

    character() = default;
    explicit character(code_point_type code_point)
        : code_point{code_point} {}

    friend bool operator==(
        const character &l,
        const character &r)
    {
        return l.code_point == r.code_point;
    }
    friend bool operator!=(
        const character &l,
        const character &r)
    {
        return !(l == r);
    }

    void set_code_point(code_point_type code_point) {
        this->code_point = code_point;
    }
    code_point_type get_code_point() const {
        return code_point;
    }

    static character_set_id get_character_set_id() {
        return std::experimental::text::get_character_set_id<CST>();
    }

private:
    code_point_type code_point = {};
};

/*
 * character specialization for the any_character_set character set.
 */
template<>
class character<any_character_set> {
public:
    using character_set_type = any_character_set;
    using code_point_type = typename character_set_type::code_point_type;

    character() = default;
    explicit character(code_point_type code_point)
        : code_point{code_point} {}
    character(character_set_id cs_id, code_point_type code_point)
        : cs_id{cs_id}, code_point{code_point} {}

    friend bool operator==(
        const character &l,
        const character &r)
    {
        return l.cs_id == r.cs_id
            && l.code_point == r.code_point;
    }
    friend bool operator!=(
        const character &l,
        const character &r)
    {
        return !(l == r);
    }

    void set_code_point(code_point_type code_point) {
        this->code_point = code_point;
    }
    code_point_type get_code_point() const {
        return code_point;
    }

    void set_character_set_id(character_set_id new_cs_id) {
        cs_id = new_cs_id;
    }
    character_set_id get_character_set_id() const {
        return cs_id;
    }

private:
    character_set_id cs_id =
        std::experimental::text::get_character_set_id<any_character_set>();
    code_point_type code_point = {};
};

template<Character_set CST>
bool operator==(
    const character<any_character_set> &c1,
    const character<CST> &c2)
{
    return c1.get_character_set_id() == c2.get_character_set_id()
        && c1.get_code_point() == c2.get_code_point();
}

template<Character_set CST>
bool operator==(
    const character<CST> &c1,
    const character<any_character_set> &c2)
{
    return c1.get_character_set_id() == c2.get_character_set_id()
        && c1.get_code_point() == c2.get_code_point();
}

template<Character_set CST>
bool operator!=(
    const character<any_character_set> &c1,
    const character<CST> &c2)
{
    return !(c1 == c2);
}

template<Character_set CST>
bool operator!=(
    const character<CST> &c1,
    const character<any_character_set> &c2)
{
    return !(c1 == c2);
}

} // inline namespace text
} // namespace experimental
} // namespace std

#endif // } TEXT_VIEW_CHARACTER_HPP
<|endoftext|>


<commit_before>#ifndef _TOOLBOX_CPP_MAKE_REF_TUPLE_HPP_
#define _TOOLBOX_CPP_MAKE_REF_TUPLE_HPP_

#include <tuple>

namespace toolbox
{
namespace cpp
{

template<typename Head, typename... Tail>
auto make_ref_tuple(Head &&head, Tail&&... tail)
{
	// head is rvalue ref
	auto head_tuple = std::tuple<Head>(std::move(head));
	auto tail_tuple = make_ref_tuple(tail...);

	return std::tuple_cat(head_tuple, tail_tuple);
}

template<typename T>
auto make_ref_tuple(T &object)
{
	return std::tuple<T &>(object);
}

template<typename Head, typename... Tail>
auto make_ref_tuple(Head &head, Tail&&... tail)
{
	// head is lvalue ref
	auto head_tuple = std::tuple<Head &>(head);
	auto tail_tuple = make_ref_tuple(tail...);

	return std::tuple_cat(head_tuple, tail_tuple);
}

}
}

#endif
<commit_msg>Fix make_ref_tuple implementation<commit_after>#ifndef _TOOLBOX_CPP_MAKE_REF_TUPLE_HPP_
#define _TOOLBOX_CPP_MAKE_REF_TUPLE_HPP_

#include <tuple>

namespace toolbox
{
namespace cpp
{

template<typename T>
auto make_ref_tuple(T &&element)
{
	return std::tuple<T>(std::forward<T>(element));
}

template<typename Head, typename... Tail>
auto make_ref_tuple(Head &&head, Tail&&... tail)
{
	auto head_tuple = std::tuple<Head>(std::forward<Head>(head));
	auto tail_tuple = make_ref_tuple(std::forward<Tail>(tail)...);

	return std::tuple_cat(head_tuple, tail_tuple);
}

}
}

#endif
<|endoftext|>


<commit_before>#include "map/change_map.h"

#include "logconsole.h"
#include "entity_system.h"
#include "cli_change_map_req.h"
#include "srv_change_map_reply.h"
#include "chat/whisper_chat.h"
#include "cmapclient.h"

#include "components/basic_info.h"
#include "components/client.h"
#include "components/level.h"
#include "components/life.h"
#include "components/magic.h"

using namespace RoseCommon;
using namespace RoseCommon::Packet;

void Map::change_map_request(EntitySystem& entitySystem, Entity entity, const CliChangeMapReq&) {
    auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();
    logger->trace("Map::change_map_request");
    logger->trace("entity {}", entity);
    const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(entity);
    const auto& life = entitySystem.get_component<Component::Life>(entity);
    const auto& magic = entitySystem.get_component<Component::Magic>(entity);
    const auto& level = entitySystem.get_component<Component::Level>(entity);
    // force send the packet as the client isn't technically on the map yet
    entitySystem.send_to(entity, SrvChangeMapReply::create(
        basicInfo.id, life.hp, magic.mp, level.xp, level.penaltyXp,
        entitySystem.get_world_time(), basicInfo.teamId), true); // FIXME: teamId is uint32_t but the packet expects a uint16_t
    if (const auto client_ptr = entitySystem.try_get_component<Component::Client>(entity)) {
        if (auto client = client_ptr->client.lock()) {
            client->set_on_map();
        }
    }
    Chat::send_whisper(entitySystem, entity, fmt::format("You are client {}", basicInfo.id));
    entitySystem.send_nearby_except_me(entity, CMapClient::create_srv_player_char(entitySystem, entity));
    const auto& nearby_entities = entitySystem.get_nearby(entity);
    for (auto other : nearby_entities) {
        if (other != entity) {
            entitySystem.send_to_entity(entity, other);
        }
    }
}
<commit_msg>Update change_map.cpp<commit_after>#include "map/change_map.h"

#include "logconsole.h"
#include "entity_system.h"
#include "cli_change_map_req.h"
#include "srv_change_map_reply.h"
#include "chat/whisper_chat.h"
#include "cmapclient.h"

#include "components/basic_info.h"
#include "components/client.h"
#include "components/destination.h"
#include "components/level.h"
#include "components/life.h"
#include "components/magic.h"
#include "components/position.h"
#include "components/warpgate.h"

using namespace RoseCommon;
using namespace RoseCommon::Packet;

void Map::change_map_request(EntitySystem& entitySystem, Entity entity, const CliChangeMapReq&) {
    auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();
    logger->trace("Map::change_map_request");
    logger->trace("entity {}", entity);
    const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(entity);
    const auto& life = entitySystem.get_component<Component::Life>(entity);
    const auto& magic = entitySystem.get_component<Component::Magic>(entity);
    const auto& level = entitySystem.get_component<Component::Level>(entity);
    // force send the packet as the client isn't technically on the map yet
    entitySystem.send_to(entity, SrvChangeMapReply::create(
        basicInfo.id, life.hp, magic.mp, level.xp, level.penaltyXp,
        entitySystem.get_world_time(), basicInfo.teamId), true); // FIXME: teamId is uint32_t but the packet expects a uint16_t
    if (const auto client_ptr = entitySystem.try_get_component<Component::Client>(entity)) {
        if (auto client = client_ptr->client.lock()) {
            client->set_on_map();
        }
    }
    Chat::send_whisper(entitySystem, entity, fmt::format("You are client {}", basicInfo.id));
    entitySystem.send_nearby_except_me(entity, CMapClient::create_srv_player_char(entitySystem, entity));
    const auto& nearby_entities = entitySystem.get_nearby(entity);
    for (auto other : nearby_entities) {
        if (other != entity) {
            entitySystem.send_to_entity(entity, other);
        }
    }
}

void Map::teleport_request(EntitySystem& entitySystem, RoseCommon::Entity entity, const RoseCommon::Packet::CliTeleportReq& packet) {
    auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();
    logger->trace("Map::teleport_request");
    logger->trace("entity {}", entity);
    const auto& pos = entitySystem.get_component<Component::Position>(entity);
    for (const auto w : entitySystem.get_entities_with_components<Component::Warpgate>()) {
        // TODO: check for hack, do something with the warpgate center and the current position?
        const auto& warpgate = entitySystem.get_component<Component::Warpgate>(w);
        if (warpgate.id == packet.get_id()) {
            const auto& dest = entitySytem.get_component<Component::Destination>(w);
            entitySystem.teleport_entity(entity, dest.x, dest.y, warpgate.dest_map);
            break;
        }
    }
}
<|endoftext|>


<commit_before>/**
 * @file llpathfindingmanager.cpp
 * @author William Todd Stinson
 * @brief A state manager for the various pathfinding states.
 *
 * $LicenseInfo:firstyear=2002&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2010, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include <string>

#include "llviewerprecompiledheaders.h"
#include "llpathfindingmanager.h"
#include "llsingleton.h"
#include "llhttpclient.h"
#include "llagent.h"
#include "llviewerregion.h"

#include <boost/function.hpp>
#include <boost/signals2.hpp>

#define CAP_SERVICE_RETRIEVE_NAVMESH  "RetrieveNavMeshSrc"

#define CAP_SERVICE_AGENT_STATE       "AgentPreferences"
#define ALTER_PERMANENT_OBJECTS_FIELD "alter_permanent_objects"

//---------------------------------------------------------------------------
// AgentStateResponder
//---------------------------------------------------------------------------

class AgentStateResponder : public LLHTTPClient::Responder
{
public:
	AgentStateResponder(const std::string &pCapabilityURL, LLPathfindingManager::EAgentState pRequestedAgentState = LLPathfindingManager::kAgentStateUnknown);
	virtual ~AgentStateResponder();

	virtual void result(const LLSD &pContent);
	virtual void error(U32 pStatus, const std::string& pReason);

protected:

private:
	std::string                       mCapabilityURL;
	LLPathfindingManager::EAgentState mRequestedAgentState;
};

//---------------------------------------------------------------------------
// LLPathfindingManager
//---------------------------------------------------------------------------

LLPathfindingManager::LLPathfindingManager()
	: LLSingleton<LLPathfindingManager>(),
	mAgentStateSignal(),
	mAgentState(kAgentStateUnknown),
	mLastKnownNonErrorAgentState(kAgentStateUnknown)
{
}

LLPathfindingManager::~LLPathfindingManager()
{
}

bool LLPathfindingManager::isPathfindingEnabledForCurrentRegion() const
{
	std::string retrieveNavMeshURL = getRetrieveNavMeshURLForCurrentRegion();
	return !retrieveNavMeshURL.empty();
}

LLPathfindingManager::agent_state_slot_t LLPathfindingManager::registerAgentStateSignal(agent_state_callback_t pAgentStateCallback)
{
	return mAgentStateSignal.connect(pAgentStateCallback);
}

LLPathfindingManager::EAgentState LLPathfindingManager::getAgentState()
{
	if (!isPathfindingEnabledForCurrentRegion())
	{
		setAgentState(kAgentStateNotEnabled);
	}
	else
	{
		if (!isValidAgentState(mAgentState))
		{
			requestGetAgentState();
		}
	}

	return mAgentState;
}

LLPathfindingManager::EAgentState LLPathfindingManager::getLastKnownNonErrorAgentState() const
{
	return mLastKnownNonErrorAgentState;
}

void LLPathfindingManager::requestSetAgentState(EAgentState pRequestedAgentState)
{
	llassert(isValidAgentState(pRequestedAgentState));
	std::string agentStateURL = getAgentStateURLForCurrentRegion();

	if (agentStateURL.empty())
	{
		setAgentState(kAgentStateNotEnabled);
	}
	else
	{
		LLSD request;
		request[ALTER_PERMANENT_OBJECTS_FIELD] = static_cast<LLSD::Boolean>(pRequestedAgentState == kAgentStateUnfrozen);

		LLHTTPClient::ResponderPtr responder = new AgentStateResponder(agentStateURL, pRequestedAgentState);
		LLHTTPClient::post(agentStateURL, request, responder);
	}
}

bool LLPathfindingManager::isValidAgentState(EAgentState pAgentState)
{
	return ((pAgentState == kAgentStateFrozen) || (pAgentState == kAgentStateUnfrozen));
}

void LLPathfindingManager::requestGetAgentState()
{
	std::string agentStateURL = getAgentStateURLForCurrentRegion();

	if (agentStateURL.empty())
	{
		setAgentState(kAgentStateNotEnabled);
	}
	else
	{
		LLHTTPClient::ResponderPtr responder = new AgentStateResponder(agentStateURL);
		LLHTTPClient::get(agentStateURL, responder);
	}
}

void LLPathfindingManager::setAgentState(EAgentState pAgentState)
{
	mAgentState = pAgentState;

	if (mAgentState != kAgentStateError)
	{
		mLastKnownNonErrorAgentState = mAgentState;
	}

	mAgentStateSignal(mAgentState);
}

void LLPathfindingManager::handleAgentStateResult(const LLSD &pContent, EAgentState pRequestedAgentState)
{
	llassert(pContent.has(ALTER_PERMANENT_OBJECTS_FIELD));
	llassert(pContent.get(ALTER_PERMANENT_OBJECTS_FIELD).isBoolean());
	EAgentState agentState = (pContent.get(ALTER_PERMANENT_OBJECTS_FIELD).asBoolean() ? kAgentStateUnfrozen : kAgentStateFrozen);

	if (isValidAgentState(pRequestedAgentState) && (agentState != pRequestedAgentState))
	{
		agentState = kAgentStateError;
		llassert(0);
	}

	setAgentState(agentState);
}

void LLPathfindingManager::handleAgentStateError(U32 pStatus, const std::string &pReason, const std::string &pURL)
{
	llwarns << "error with request to URL '" << pURL << "' because " << pReason << " (statusCode:" << pStatus << ")" << llendl;
	setAgentState(kAgentStateError);
}

std::string LLPathfindingManager::getRetrieveNavMeshURLForCurrentRegion() const
{
	return getCapabilityURLForCurrentRegion(CAP_SERVICE_RETRIEVE_NAVMESH);
}

std::string LLPathfindingManager::getAgentStateURLForCurrentRegion() const
{
	return getCapabilityURLForCurrentRegion(CAP_SERVICE_AGENT_STATE);
}

std::string LLPathfindingManager::getCapabilityURLForCurrentRegion(const std::string &pCapabilityName) const
{
	std::string capabilityURL("");

	LLViewerRegion* region = gAgent.getRegion();
	if (region != NULL)
	{
		capabilityURL = region->getCapability(pCapabilityName);
	}

	if (capabilityURL.empty())
	{
		llwarns << "cannot find capability '" << pCapabilityName << "' for current region '"
			<< ((region != NULL) ? region->getName() : "<null>") << "'" << llendl;
	}

	return capabilityURL;
}

//---------------------------------------------------------------------------
// AgentStateResponder
//---------------------------------------------------------------------------

AgentStateResponder::AgentStateResponder(const std::string &pCapabilityURL, LLPathfindingManager::EAgentState pRequestedAgentState)
	: mCapabilityURL(pCapabilityURL),
	mRequestedAgentState(pRequestedAgentState)
{
}

AgentStateResponder::~AgentStateResponder()
{
}

void AgentStateResponder::result(const LLSD &pContent)
{
	LLPathfindingManager::getInstance()->handleAgentStateResult(pContent, mRequestedAgentState);
}

void AgentStateResponder::error(U32 pStatus, const std::string &pReason)
{
	LLPathfindingManager::getInstance()->handleAgentStateError(pStatus, pReason, mCapabilityURL);
}
<commit_msg>Adding a missing base constructor to the list.<commit_after>/**
 * @file llpathfindingmanager.cpp
 * @author William Todd Stinson
 * @brief A state manager for the various pathfinding states.
 *
 * $LicenseInfo:firstyear=2002&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2010, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include <string>

#include "llviewerprecompiledheaders.h"
#include "llpathfindingmanager.h"
#include "llsingleton.h"
#include "llhttpclient.h"
#include "llagent.h"
#include "llviewerregion.h"

#include <boost/function.hpp>
#include <boost/signals2.hpp>

#define CAP_SERVICE_RETRIEVE_NAVMESH  "RetrieveNavMeshSrc"

#define CAP_SERVICE_AGENT_STATE       "AgentPreferences"
#define ALTER_PERMANENT_OBJECTS_FIELD "alter_permanent_objects"

//---------------------------------------------------------------------------
// AgentStateResponder
//---------------------------------------------------------------------------

class AgentStateResponder : public LLHTTPClient::Responder
{
public:
	AgentStateResponder(const std::string &pCapabilityURL, LLPathfindingManager::EAgentState pRequestedAgentState = LLPathfindingManager::kAgentStateUnknown);
	virtual ~AgentStateResponder();

	virtual void result(const LLSD &pContent);
	virtual void error(U32 pStatus, const std::string& pReason);

protected:

private:
	std::string                       mCapabilityURL;
	LLPathfindingManager::EAgentState mRequestedAgentState;
};

//---------------------------------------------------------------------------
// LLPathfindingManager
//---------------------------------------------------------------------------

LLPathfindingManager::LLPathfindingManager()
	: LLSingleton<LLPathfindingManager>(),
	mAgentStateSignal(),
	mAgentState(kAgentStateUnknown),
	mLastKnownNonErrorAgentState(kAgentStateUnknown)
{
}

LLPathfindingManager::~LLPathfindingManager()
{
}

bool LLPathfindingManager::isPathfindingEnabledForCurrentRegion() const
{
	std::string retrieveNavMeshURL = getRetrieveNavMeshURLForCurrentRegion();
	return !retrieveNavMeshURL.empty();
}

LLPathfindingManager::agent_state_slot_t LLPathfindingManager::registerAgentStateSignal(agent_state_callback_t pAgentStateCallback)
{
	return mAgentStateSignal.connect(pAgentStateCallback);
}

LLPathfindingManager::EAgentState LLPathfindingManager::getAgentState()
{
	if (!isPathfindingEnabledForCurrentRegion())
	{
		setAgentState(kAgentStateNotEnabled);
	}
	else
	{
		if (!isValidAgentState(mAgentState))
		{
			requestGetAgentState();
		}
	}

	return mAgentState;
}

LLPathfindingManager::EAgentState LLPathfindingManager::getLastKnownNonErrorAgentState() const
{
	return mLastKnownNonErrorAgentState;
}

void LLPathfindingManager::requestSetAgentState(EAgentState pRequestedAgentState)
{
	llassert(isValidAgentState(pRequestedAgentState));
	std::string agentStateURL = getAgentStateURLForCurrentRegion();

	if (agentStateURL.empty())
	{
		setAgentState(kAgentStateNotEnabled);
	}
	else
	{
		LLSD request;
		request[ALTER_PERMANENT_OBJECTS_FIELD] = static_cast<LLSD::Boolean>(pRequestedAgentState == kAgentStateUnfrozen);

		LLHTTPClient::ResponderPtr responder = new AgentStateResponder(agentStateURL, pRequestedAgentState);
		LLHTTPClient::post(agentStateURL, request, responder);
	}
}

bool LLPathfindingManager::isValidAgentState(EAgentState pAgentState)
{
	return ((pAgentState == kAgentStateFrozen) || (pAgentState == kAgentStateUnfrozen));
}

void LLPathfindingManager::requestGetAgentState()
{
	std::string agentStateURL = getAgentStateURLForCurrentRegion();

	if (agentStateURL.empty())
	{
		setAgentState(kAgentStateNotEnabled);
	}
	else
	{
		LLHTTPClient::ResponderPtr responder = new AgentStateResponder(agentStateURL);
		LLHTTPClient::get(agentStateURL, responder);
	}
}

void LLPathfindingManager::setAgentState(EAgentState pAgentState)
{
	mAgentState = pAgentState;

	if (mAgentState != kAgentStateError)
	{
		mLastKnownNonErrorAgentState = mAgentState;
	}

	mAgentStateSignal(mAgentState);
}

void LLPathfindingManager::handleAgentStateResult(const LLSD &pContent, EAgentState pRequestedAgentState)
{
	llassert(pContent.has(ALTER_PERMANENT_OBJECTS_FIELD));
	llassert(pContent.get(ALTER_PERMANENT_OBJECTS_FIELD).isBoolean());
	EAgentState agentState = (pContent.get(ALTER_PERMANENT_OBJECTS_FIELD).asBoolean() ? kAgentStateUnfrozen : kAgentStateFrozen);

	if (isValidAgentState(pRequestedAgentState) && (agentState != pRequestedAgentState))
	{
		agentState = kAgentStateError;
		llassert(0);
	}

	setAgentState(agentState);
}

void LLPathfindingManager::handleAgentStateError(U32 pStatus, const std::string &pReason, const std::string &pURL)
{
	llwarns << "error with request to URL '" << pURL << "' because " << pReason << " (statusCode:" << pStatus << ")" << llendl;
	setAgentState(kAgentStateError);
}

std::string LLPathfindingManager::getRetrieveNavMeshURLForCurrentRegion() const
{
	return getCapabilityURLForCurrentRegion(CAP_SERVICE_RETRIEVE_NAVMESH);
}

std::string LLPathfindingManager::getAgentStateURLForCurrentRegion() const
{
	return getCapabilityURLForCurrentRegion(CAP_SERVICE_AGENT_STATE);
}

std::string LLPathfindingManager::getCapabilityURLForCurrentRegion(const std::string &pCapabilityName) const
{
	std::string capabilityURL("");

	LLViewerRegion* region = gAgent.getRegion();
	if (region != NULL)
	{
		capabilityURL = region->getCapability(pCapabilityName);
	}

	if (capabilityURL.empty())
	{
		llwarns << "cannot find capability '" << pCapabilityName << "' for current region '"
			<< ((region != NULL) ? region->getName() : "<null>") << "'" << llendl;
	}

	return capabilityURL;
}

//---------------------------------------------------------------------------
// AgentStateResponder
//---------------------------------------------------------------------------

AgentStateResponder::AgentStateResponder(const std::string &pCapabilityURL, LLPathfindingManager::EAgentState pRequestedAgentState)
	: LLHTTPClient::Responder(),
	mCapabilityURL(pCapabilityURL),
	mRequestedAgentState(pRequestedAgentState)
{
}

AgentStateResponder::~AgentStateResponder()
{
}

void AgentStateResponder::result(const LLSD &pContent)
{
	LLPathfindingManager::getInstance()->handleAgentStateResult(pContent, mRequestedAgentState);
}

void AgentStateResponder::error(U32 pStatus, const std::string &pReason)
{
	LLPathfindingManager::getInstance()->handleAgentStateError(pStatus, pReason, mCapabilityURL);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: directsql.hxx,v $
 *
 *  $Revision: 1.1 $
 *
 *  last change: $Author: fs $ $Date: 2001-06-19 10:54:55 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _DBACCESS_UI_DIRECTSQL_HXX_
#define _DBACCESS_UI_DIRECTSQL_HXX_

#ifndef _SV_DIALOG_HXX
#include <vcl/dialog.hxx>
#endif
#ifndef _SVEDIT_HXX
#include <svtools/svmedit.hxx>
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _SV_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#include <stl/deque>

#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _UNOTOOLS_EVENTLISTENERADAPTER_HXX_
#include <unotools/eventlisteneradapter.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif

//........................................................................
namespace dbaui
{
//........................................................................

    //====================================================================
    //= DirectSQLDialog
    //====================================================================
    class DirectSQLDialog
            :public ModalDialog
            ,public ::utl::OEventListenerAdapter
    {
    protected:
        ::osl::Mutex    m_aMutex;

        FixedLine       m_aFrame;
        FixedText       m_aSQLLabel;
        MultiLineEdit   m_aSQL;
        PushButton      m_aExecute;
        FixedText       m_aHistoryLabel;
        ListBox*        m_pSQLHistory;
        FixedLine       m_aStatusFrame;
        MultiLineEdit   m_aStatus;
        FixedLine       m_aButtonSeparator;
        HelpButton      m_aHelp;
        PushButton      m_aClose;

        typedef ::std::deque< String >  StringQueue;
        StringQueue     m_aStatementHistory;    // previous statements
        StringQueue     m_aNormalizedHistory;   // previous statements, normalized to be used in the list box

        sal_Int32       m_nHistoryLimit;
        sal_Int32       m_nStatusCount;

        ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >
                        m_xConnection;

    public:
        DirectSQLDialog(
            Window* _pParent,
            const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn);
        ~DirectSQLDialog();

        /// add an history entry
        void addHistoryEntry(const String& _rStatement);

        /// set the limit for the history size
        void setHistoryLimit(sal_Int32 _nMaxEntries);

        /// number of history entries
        sal_Int32 getHistorySize() const;

    protected:
        void executeCurrent();
        void switchToHistory(sal_Int32 _nHistoryPos, sal_Bool _bUpdateListBox = sal_True);

        // OEventListenerAdapter
        virtual void _disposing( const ::com::sun::star::lang::EventObject& _rSource );

    protected:
        DECL_LINK( OnExecute, void* );
        DECL_LINK( OnClose, void* );
        DECL_LINK( OnListEntrySelected, void* );
        DECL_LINK( OnStatementModified, void* );

    private:
        /// adds a statement to the statement history
        void implAddToStatementHistory(const String& _rStatement);

        /// ensures that our history has at most m_nHistoryLimit entries
        void implEnsureHistoryLimit();

        /// executes the statement given, adds the status to the status list
        void implExecuteStatement(const String& _rStatement);

        /// adds a status text to the status list
        void addStatusText(const String& _rMessage);

#ifdef DBG_UTIL
        const sal_Char* impl_CheckInvariants() const;
#endif
    };

    //====================================================================
#ifdef DBG_UTIL
#define CHECK_INVARIANTS(methodname)    \
    {   \
        const sal_Char* pError = impl_CheckInvariants();    \
        if (pError) \
            OSL_ENSURE(sal_False, (ByteString(methodname) += ByteString(": ") += ByteString(pError)).GetBuffer());  \
    }
#else
#define CHECK_INVARIANTS(methodname)
#endif

//........................................................................
}   // namespace dbaui
//........................................................................

#endif // _DBACCESS_UI_DIRECTSQL_HXX_

/*************************************************************************
 * history:
 *  $Log: not supported by cvs2svn $
 *
 *  Revision 1.0 18.06.01 15:46:43  fs
 ************************************************************************/

<commit_msg>chg: Syntax #87576#<commit_after>/*************************************************************************
 *
 *  $RCSfile: directsql.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: mh $ $Date: 2001-06-22 14:17:03 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _DBACCESS_UI_DIRECTSQL_HXX_
#define _DBACCESS_UI_DIRECTSQL_HXX_

#ifndef _SV_DIALOG_HXX
#include <vcl/dialog.hxx>
#endif
#ifndef _SVEDIT_HXX
#include <svtools/svmedit.hxx>
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _SV_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#include <deque>

#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _UNOTOOLS_EVENTLISTENERADAPTER_HXX_
#include <unotools/eventlisteneradapter.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif

//........................................................................
namespace dbaui
{
//........................................................................

    //====================================================================
    //= DirectSQLDialog
    //====================================================================
    class DirectSQLDialog
            :public ModalDialog
            ,public ::utl::OEventListenerAdapter
    {
    protected:
        ::osl::Mutex    m_aMutex;

        FixedLine       m_aFrame;
        FixedText       m_aSQLLabel;
        MultiLineEdit   m_aSQL;
        PushButton      m_aExecute;
        FixedText       m_aHistoryLabel;
        ListBox*        m_pSQLHistory;
        FixedLine       m_aStatusFrame;
        MultiLineEdit   m_aStatus;
        FixedLine       m_aButtonSeparator;
        HelpButton      m_aHelp;
        PushButton      m_aClose;

        typedef ::std::deque< String >  StringQueue;
        StringQueue     m_aStatementHistory;    // previous statements
        StringQueue     m_aNormalizedHistory;   // previous statements, normalized to be used in the list box

        sal_Int32       m_nHistoryLimit;
        sal_Int32       m_nStatusCount;

        ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >
                        m_xConnection;

    public:
        DirectSQLDialog(
            Window* _pParent,
            const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn);
        ~DirectSQLDialog();

        /// add an history entry
        void addHistoryEntry(const String& _rStatement);

        /// set the limit for the history size
        void setHistoryLimit(sal_Int32 _nMaxEntries);

        /// number of history entries
        sal_Int32 getHistorySize() const;

    protected:
        void executeCurrent();
        void switchToHistory(sal_Int32 _nHistoryPos, sal_Bool _bUpdateListBox = sal_True);

        // OEventListenerAdapter
        virtual void _disposing( const ::com::sun::star::lang::EventObject& _rSource );

    protected:
        DECL_LINK( OnExecute, void* );
        DECL_LINK( OnClose, void* );
        DECL_LINK( OnListEntrySelected, void* );
        DECL_LINK( OnStatementModified, void* );

    private:
        /// adds a statement to the statement history
        void implAddToStatementHistory(const String& _rStatement);

        /// ensures that our history has at most m_nHistoryLimit entries
        void implEnsureHistoryLimit();

        /// executes the statement given, adds the status to the status list
        void implExecuteStatement(const String& _rStatement);

        /// adds a status text to the status list
        void addStatusText(const String& _rMessage);

#ifdef DBG_UTIL
        const sal_Char* impl_CheckInvariants() const;
#endif
    };

    //====================================================================
#ifdef DBG_UTIL
#define CHECK_INVARIANTS(methodname)    \
    {   \
        const sal_Char* pError = impl_CheckInvariants();    \
        if (pError) \
            OSL_ENSURE(sal_False, (ByteString(methodname) += ByteString(": ") += ByteString(pError)).GetBuffer());  \
    }
#else
#define CHECK_INVARIANTS(methodname)
#endif

//........................................................................
}   // namespace dbaui
//........................................................................

#endif // _DBACCESS_UI_DIRECTSQL_HXX_

/*************************************************************************
 * history:
 *  $Log: not supported by cvs2svn $
 *  Revision 1.1  2001/06/19 10:54:55  fs
 *  initial checkin - dialog for executing SQL statements
 *
 *
 *  Revision 1.0 18.06.01 15:46:43  fs
 ************************************************************************/

<|endoftext|>


<commit_before>#ifndef HMLIB_ITERATORS_INDEXATACCESSITERATOR_INC
#define HMLIB_ITERATORS_INDEXATACCESSITERATOR_INC 100
#
#include<iterator>
#include"../utility.hpp"
#include"../type_traits.hpp"
namespace hmLib {
	namespace iterators {
		namespace detail {
			template<typename this_type, typename range_type_, typename index_iterator_, typename index_iterator_category>
			struct index_at_access_iterator_mixin{
			protected:
				template<typename this_type_ref>
				static auto& container(this_type_ref& This) { return static_cast<this_type&>(This).pContainer; }
				template<typename this_type_ref>
				static const auto& container(const this_type_ref& This) { return static_cast<const this_type&>(This).pContainer; }
				template<typename this_type_ref>
				static auto& iitr(this_type_ref& This) { return static_cast<this_type&>(This).IItr; }
				template<typename this_type_ref>
				static const auto& iitr(const this_type_ref& This) { return static_cast<const this_type&>(This).IItr; }
			public:
				using value_type = decltype(std::declval<range_type_>().at(*std::declval<index_iterator_>()));
				using difference_type = int;
				using reference = decltype((std::declval<range_type_>().at(*std::declval<index_iterator_>())));
				using pointer = void;
			};
			template<typename this_type, typename range_type_, typename index_iterator_>
			struct index_at_access_iterator_mixin<this_type, range_type_, index_iterator_, std::input_iterator_tag>
				:public index_at_access_iterator_mixin<this_type, range_type_, index_iterator_, void> {
			public:
				reference operator*()const { return container(*this)->at(*iitr(*this)); }
				this_type& operator++() {
					this_type& This = static_cast<this_type&>(*this);
					++iitr(This);
					return This;
				}
				this_type operator++(int) {
					this_type Prev = static_cast<this_type&>(*this);
					operator++();
					return Prev;
				}
				friend bool operator==(const this_type& v1, const this_type& v2) {
					return iitr(v1) == iitr(v2);
				}
				friend bool operator!=(const this_type& v1, const this_type& v2) {
					return iitr(v1) != iitr(v2);
				}
			};
			template<typename this_type, typename range_type_, typename index_iterator_>
			struct index_at_access_iterator_mixin<this_type, range_type_, index_iterator_, std::forward_iterator_tag>
				:public index_at_access_iterator_mixin<this_type, range_type_, index_iterator_, std::input_iterator_tag> {
			};
			template<typename this_type, typename range_type_, typename index_iterator_>
			struct index_at_access_iterator_mixin<this_type, range_type_, index_iterator_, std::bidirectional_iterator_tag>
				:public index_at_access_iterator_mixin<this_type, range_type_, index_iterator_, std::forward_iterator_tag> {
			public:
				this_type& operator++() {
					this_type& This = static_cast<this_type&>(*this);
					--iitr(This);
					return This;
				}
				this_type operator++(int) {
					this_type Prev = static_cast<this_type&>(*this);
					operator--();
					return Prev;
				}
			};
			template<typename this_type, typename range_type_, typename index_iterator_>
			struct index_at_access_iterator_mixin<this_type, range_type_, index_iterator_, std::random_access_iterator_tag>
				:public index_at_access_iterator_mixin<this_type, range_type_, index_iterator_, std::bidirectional_iterator_tag> {
			public:
				reference operator[](difference_type d) { return container(*this)->at(IItr[d]); }
				this_type& operator+=(difference_type d) {
					iitr(*this) = +d;
					return *this;
				}
				this_type& operator-=(difference_type d) {
					iitr(*this) = -d;
					return *this;
				}
				friend this_type operator+(const this_type& itr, difference_type d) {
					this_type ans = itr;
					ans += d;
					return ans;
				}
				friend this_type operator+(difference_type d, const this_type& itr) {
					return operator+(itr, d);
				}
				friend this_type operator-(const this_type& itr, difference_type d) {
					this_type ans = itr;
					ans -= d;
					return ans;
				}
				friend difference_type operator-(const this_type& itr1, const this_type& itr2) {
					return iitr(itr1) - iitr(itr2);
				}
				friend bool operator>(const this_type& v1, const this_type& v2) {
					return iitr(v1) > iitr(v2);
				}
				friend bool operator<(const this_type& v1, const this_type& v2) {
					return iitr(v1) < iitr(v2);
				}
				friend bool operator>=(const this_type& v1, const this_type& v2) {
					return iitr(v1) >= iitr(v2);
				}
				friend bool operator<=(const this_type& v1, const this_type& v2) {
					return iitr(v1) <= iitr(v2);
				}
			};
		}
	}
	template<typename range_type_, typename index_iterator_, typename index_iterator_category_ = typename std::iterator_traits<index_iterator_>::iterator_category>
	struct index_at_access_iterator
		: public iterators::detail::index_at_access_iterator_mixin<
			index_at_access_iterator<range_type_, index_iterator_, index_iterator_category_>,
			range_type_, index_iterator_, index_iterator_category_
		>{
		friend struct iterators::detail::index_at_access_iterator_mixin<
			index_at_access_iterator<range_type_, index_iterator_, index_iterator_category_>,
			range_type_, index_iterator_, void
		>;
	private:
		using this_type = index_at_access_iterator<range_type_, index_iterator_, index_iterator_category_>;
		using range_type = range_type_;
		using index_iterator = index_iterator_;
	public:
		using iterator_category = index_iterator_category_;
	private:
		range_type* pContainer;
		index_iterator IItr;
	public://constructer
		index_at_access_iterator()noexcept : pContainer(nullptr), IItr() {}
		index_at_access_iterator(range_type& Container_, index_iterator_ IItr_):pContainer(&Container_), IItr(IItr_) {}
	public:
		auto index()const { return *(static_cast<this_type&>(*this).IItr); }
	};

	template<typename range_type, typename index_iterator>
	auto make_index_at_access_iterator(range_type& Container, index_iterator iitr) {
		return index_at_access_iterator<range_type, index_iterator>(Container, iitr);
	}

	template<typename range_type_, typename index_iterator_>
	struct index_at_access_range {
		using range_type = range_type_;
		using index_iterator = index_iterator_;
	public:
		using iterator = index_at_access_iterator<range_type, index_iterator>;
		using reference = typename std::iterator_traits<iterator>::reference;
	private:
		range_type* pContainer;
		index_iterator IBeg;
		index_iterator IEnd;
	public:
		index_at_access_range() = default;
		index_at_access_range(range_type& Container_, index_iterator IBeg_, index_iterator IEnd_):pContainer(&Container_), IBeg(IBeg_), IEnd(IEnd_) {}
		iterator begin()const { return iterator(*pContainer, IBeg); }
		iterator end()const { return iterator(*pContainer, IEnd); }
		reference at(std::size_t Index)const { return pContainer->at(*std::next(IBeg, Index)); }
		std::size_t size()const { return std::distance(IBeg, IEnd); }
	};
	template<typename range_type, typename index_iterator>
	auto make_index_at_access_range(range_type& Container, index_iterator IndexBegin, index_iterator IndexEnd) {
		return index_at_access_range<range_type, index_iterator>(Container, IndexBegin, IndexEnd);
	}
}
#
#endif
<commit_msg>Add inex_op_access <commit_after>#ifndef HMLIB_ITERATORS_INDEXATACCESSITERATOR_INC
#define HMLIB_ITERATORS_INDEXATACCESSITERATOR_INC 100
#
#include<iterator>
#include"../utility.hpp"
#include"../type_traits.hpp"
namespace hmLib {
	namespace iterators {
		namespace detail {
			template<typename this_type, typename range_type_, typename index_iterator_, typename index_iterator_category>
			struct index_at_access_iterator_mixin{
			protected:
				template<typename this_type_ref>
				static auto& container(this_type_ref& This) { return static_cast<this_type&>(This).pContainer; }
				template<typename this_type_ref>
				static const auto& container(const this_type_ref& This) { return static_cast<const this_type&>(This).pContainer; }
				template<typename this_type_ref>
				static auto& iitr(this_type_ref& This) { return static_cast<this_type&>(This).IItr; }
				template<typename this_type_ref>
				static const auto& iitr(const this_type_ref& This) { return static_cast<const this_type&>(This).IItr; }
			public:
				using value_type = decltype(std::declval<range_type_>().at(*std::declval<index_iterator_>()));
				using difference_type = int;
				using reference = decltype((std::declval<range_type_>().at(*std::declval<index_iterator_>())));
				using pointer = void;
			};
			template<typename this_type, typename range_type_, typename index_iterator_>
			struct index_at_access_iterator_mixin<this_type, range_type_, index_iterator_, std::input_iterator_tag>
				:public index_at_access_iterator_mixin<this_type, range_type_, index_iterator_, void> {
			public:
				reference operator*()const { return container(*this)->at(*iitr(*this)); }
				this_type& operator++() {
					this_type& This = static_cast<this_type&>(*this);
					++iitr(This);
					return This;
				}
				this_type operator++(int) {
					this_type Prev = static_cast<this_type&>(*this);
					operator++();
					return Prev;
				}
				friend bool operator==(const this_type& v1, const this_type& v2) {
					return iitr(v1) == iitr(v2);
				}
				friend bool operator!=(const this_type& v1, const this_type& v2) {
					return iitr(v1) != iitr(v2);
				}
			};
			template<typename this_type, typename range_type_, typename index_iterator_>
			struct index_at_access_iterator_mixin<this_type, range_type_, index_iterator_, std::forward_iterator_tag>
				:public index_at_access_iterator_mixin<this_type, range_type_, index_iterator_, std::input_iterator_tag> {
			};
			template<typename this_type, typename range_type_, typename index_iterator_>
			struct index_at_access_iterator_mixin<this_type, range_type_, index_iterator_, std::bidirectional_iterator_tag>
				:public index_at_access_iterator_mixin<this_type, range_type_, index_iterator_, std::forward_iterator_tag> {
			public:
				this_type& operator++() {
					this_type& This = static_cast<this_type&>(*this);
					--iitr(This);
					return This;
				}
				this_type operator++(int) {
					this_type Prev = static_cast<this_type&>(*this);
					operator--();
					return Prev;
				}
			};
			template<typename this_type, typename range_type_, typename index_iterator_>
			struct index_at_access_iterator_mixin<this_type, range_type_, index_iterator_, std::random_access_iterator_tag>
				:public index_at_access_iterator_mixin<this_type, range_type_, index_iterator_, std::bidirectional_iterator_tag> {
			public:
				reference operator[](difference_type d) { return container(*this)->at(IItr[d]); }
				this_type& operator+=(difference_type d) {
					iitr(*this) = +d;
					return *this;
				}
				this_type& operator-=(difference_type d) {
					iitr(*this) = -d;
					return *this;
				}
				friend this_type operator+(const this_type& itr, difference_type d) {
					this_type ans = itr;
					ans += d;
					return ans;
				}
				friend this_type operator+(difference_type d, const this_type& itr) {
					return operator+(itr, d);
				}
				friend this_type operator-(const this_type& itr, difference_type d) {
					this_type ans = itr;
					ans -= d;
					return ans;
				}
				friend difference_type operator-(const this_type& itr1, const this_type& itr2) {
					return iitr(itr1) - iitr(itr2);
				}
				friend bool operator>(const this_type& v1, const this_type& v2) {
					return iitr(v1) > iitr(v2);
				}
				friend bool operator<(const this_type& v1, const this_type& v2) {
					return iitr(v1) < iitr(v2);
				}
				friend bool operator>=(const this_type& v1, const this_type& v2) {
					return iitr(v1) >= iitr(v2);
				}
				friend bool operator<=(const this_type& v1, const this_type& v2) {
					return iitr(v1) <= iitr(v2);
				}
			};

			template<typename this_type, typename range_type_, typename index_iterator_, typename index_iterator_category>
			struct index_op_access_iterator_mixin {
			protected:
				template<typename this_type_ref>
				static auto& container(this_type_ref& This) { return static_cast<this_type&>(This).pContainer; }
				template<typename this_type_ref>
				static const auto& container(const this_type_ref& This) { return static_cast<const this_type&>(This).pContainer; }
				template<typename this_type_ref>
				static auto& iitr(this_type_ref& This) { return static_cast<this_type&>(This).IItr; }
				template<typename this_type_ref>
				static const auto& iitr(const this_type_ref& This) { return static_cast<const this_type&>(This).IItr; }
			public:
				using value_type = decltype(std::declval<range_type_>().operator[](*std::declval<index_iterator_>()));
				using difference_type = int;
				using reference = decltype((std::declval<range_type_>().operator[](*std::declval<index_iterator_>())));
				using pointer = void;
			};
			template<typename this_type, typename range_type_, typename index_iterator_>
			struct index_op_access_iterator_mixin<this_type, range_type_, index_iterator_, std::input_iterator_tag>
				:public index_op_access_iterator_mixin<this_type, range_type_, index_iterator_, void> {
			public:
				reference operator*()const { return container(*this)->operator[](*iitr(*this)); }
				this_type& operator++() {
					this_type& This = static_cast<this_type&>(*this);
					++iitr(This);
					return This;
				}
				this_type operator++(int) {
					this_type Prev = static_cast<this_type&>(*this);
					operator++();
					return Prev;
				}
				friend bool operator==(const this_type& v1, const this_type& v2) {
					return iitr(v1) == iitr(v2);
				}
				friend bool operator!=(const this_type& v1, const this_type& v2) {
					return iitr(v1) != iitr(v2);
				}
			};
			template<typename this_type, typename range_type_, typename index_iterator_>
			struct index_op_access_iterator_mixin<this_type, range_type_, index_iterator_, std::forward_iterator_tag>
				:public index_op_access_iterator_mixin<this_type, range_type_, index_iterator_, std::input_iterator_tag> {
			};
			template<typename this_type, typename range_type_, typename index_iterator_>
			struct index_op_access_iterator_mixin<this_type, range_type_, index_iterator_, std::bidirectional_iterator_tag>
				:public index_op_access_iterator_mixin<this_type, range_type_, index_iterator_, std::forward_iterator_tag> {
			public:
				this_type& operator++() {
					this_type& This = static_cast<this_type&>(*this);
					--iitr(This);
					return This;
				}
				this_type operator++(int) {
					this_type Prev = static_cast<this_type&>(*this);
					operator--();
					return Prev;
				}
			};
			template<typename this_type, typename range_type_, typename index_iterator_>
			struct index_op_access_iterator_mixin<this_type, range_type_, index_iterator_, std::random_access_iterator_tag>
				:public index_op_access_iterator_mixin<this_type, range_type_, index_iterator_, std::bidirectional_iterator_tag> {
			public:
				reference operator[](difference_type d) { return container(*this)->operator[](IItr[d]); }
				this_type& operator+=(difference_type d) {
					iitr(*this) = +d;
					return *this;
				}
				this_type& operator-=(difference_type d) {
					iitr(*this) = -d;
					return *this;
				}
				friend this_type operator+(const this_type& itr, difference_type d) {
					this_type ans = itr;
					ans += d;
					return ans;
				}
				friend this_type operator+(difference_type d, const this_type& itr) {
					return operator+(itr, d);
				}
				friend this_type operator-(const this_type& itr, difference_type d) {
					this_type ans = itr;
					ans -= d;
					return ans;
				}
				friend difference_type operator-(const this_type& itr1, const this_type& itr2) {
					return iitr(itr1) - iitr(itr2);
				}
				friend bool operator>(const this_type& v1, const this_type& v2) {
					return iitr(v1) > iitr(v2);
				}
				friend bool operator<(const this_type& v1, const this_type& v2) {
					return iitr(v1) < iitr(v2);
				}
				friend bool operator>=(const this_type& v1, const this_type& v2) {
					return iitr(v1) >= iitr(v2);
				}
				friend bool operator<=(const this_type& v1, const this_type& v2) {
					return iitr(v1) <= iitr(v2);
				}
			};
		}
	}
	template<typename range_type_, typename index_iterator_, typename index_iterator_category_ = typename std::iterator_traits<index_iterator_>::iterator_category>
	struct index_at_access_iterator
		: public iterators::detail::index_at_access_iterator_mixin<
			index_at_access_iterator<range_type_, index_iterator_, index_iterator_category_>,
			range_type_, index_iterator_, index_iterator_category_
		>{
		friend struct iterators::detail::index_at_access_iterator_mixin<
			index_at_access_iterator<range_type_, index_iterator_, index_iterator_category_>,
			range_type_, index_iterator_, void
		>;
	private:
		using this_type = index_at_access_iterator<range_type_, index_iterator_, index_iterator_category_>;
		using range_type = range_type_;
		using index_iterator = index_iterator_;
	public:
		using iterator_category = index_iterator_category_;
	private:
		range_type* pContainer;
		index_iterator IItr;
	public://constructer
		index_at_access_iterator()noexcept : pContainer(nullptr), IItr() {}
		index_at_access_iterator(range_type& Container_, index_iterator_ IItr_):pContainer(&Container_), IItr(IItr_) {}
	public:
		auto index()const { return *(static_cast<this_type&>(*this).IItr); }
	};

	template<typename range_type, typename index_iterator>
	auto make_index_at_access_iterator(range_type& Container, index_iterator iitr) {
		return index_at_access_iterator<range_type, index_iterator>(Container, iitr);
	}

	template<typename range_type_, typename index_iterator_>
	struct index_at_access_range {
		using range_type = range_type_;
		using index_iterator = index_iterator_;
	public:
		using iterator = index_at_access_iterator<range_type, index_iterator>;
		using reference = typename std::iterator_traits<iterator>::reference;
	private:
		range_type* pContainer;
		index_iterator IBeg;
		index_iterator IEnd;
	public:
		index_at_access_range() = default;
		index_at_access_range(range_type& Container_, index_iterator IBeg_, index_iterator IEnd_):pContainer(&Container_), IBeg(IBeg_), IEnd(IEnd_) {}
		iterator begin()const { return iterator(*pContainer, IBeg); }
		iterator end()const { return iterator(*pContainer, IEnd); }
		reference at(std::size_t Index)const { return pContainer->at(*std::next(IBeg, Index)); }
		std::size_t size()const { return std::distance(IBeg, IEnd); }
	};
	template<typename range_type, typename index_iterator>
	auto make_index_at_access_range(range_type& Container, index_iterator IndexBegin, index_iterator IndexEnd) {
		return index_at_access_range<range_type, index_iterator>(Container, IndexBegin, IndexEnd);
	}

	template<typename range_type_, typename index_iterator_, typename index_iterator_category_ = typename std::iterator_traits<index_iterator_>::iterator_category>
	struct index_op_access_iterator
		: public iterators::detail::index_op_access_iterator_mixin<
		index_op_access_iterator<range_type_, index_iterator_, index_iterator_category_>,
		range_type_, index_iterator_, index_iterator_category_
		> {
		friend struct iterators::detail::index_op_access_iterator_mixin<
			index_op_access_iterator<range_type_, index_iterator_, index_iterator_category_>,
			range_type_, index_iterator_, void
		>;
	private:
		using this_type = index_op_access_iterator<range_type_, index_iterator_, index_iterator_category_>;
		using range_type = range_type_;
		using index_iterator = index_iterator_;
	public:
		using iterator_category = index_iterator_category_;
	private:
		range_type* pContainer;
		index_iterator IItr;
	public://constructer
		index_op_access_iterator()noexcept : pContainer(nullptr), IItr() {}
		index_op_access_iterator(range_type& Container_, index_iterator_ IItr_):pContainer(&Container_), IItr(IItr_) {}
	public:
		auto index()const { return *(static_cast<this_type&>(*this).IItr); }
	};

	template<typename range_type, typename index_iterator>
	auto make_index_op_access_iterator(range_type& Container, index_iterator iitr) {
		return index_op_access_iterator<range_type, index_iterator>(Container, iitr);
	}

	template<typename range_type_, typename index_iterator_>
	struct index_op_access_range {
		using range_type = range_type_;
		using index_iterator = index_iterator_;
	public:
		using iterator = index_op_access_iterator<range_type, index_iterator>;
		using reference = typename std::iterator_traits<iterator>::reference;
	private:
		range_type* pContainer;
		index_iterator IBeg;
		index_iterator IEnd;
	public:
		index_op_access_range() = default;
		index_op_access_range(range_type& Container_, index_iterator IBeg_, index_iterator IEnd_):pContainer(&Container_), IBeg(IBeg_), IEnd(IEnd_) {}
		iterator begin()const { return iterator(*pContainer, IBeg); }
		iterator end()const { return iterator(*pContainer, IEnd); }
		reference at(std::size_t Index)const { return pContainer->at(*std::next(IBeg, Index)); }
		std::size_t size()const { return std::distance(IBeg, IEnd); }
	};
	template<typename range_type, typename index_iterator>
	auto make_index_op_access_range(range_type& Container, index_iterator IndexBegin, index_iterator IndexEnd) {
		return index_op_access_range<range_type, index_iterator>(Container, IndexBegin, IndexEnd);
	}
}
#
#endif
<|endoftext|>