<commit_before>#include "Layers.h"
#include "components/Exceptions.h"
#include "layers/Layer.h"
#include "renderers/MapRenderer.h"
#include "utils/Log.h"

namespace carto {

    Layers::Layers(const std::shared_ptr<CancelableThreadPool>& envelopeThreadPool,
                   const std::shared_ptr<CancelableThreadPool>& tileThreadPool,
                   const std::weak_ptr<Options>& options) :
        _layers(),
        _envelopeThreadPool(envelopeThreadPool),
        _tileThreadPool(tileThreadPool),
        _options(options),
        _mapRenderer(),
        _touchHandler(),
        _mutex()
    {
    }

    Layers::~Layers() {
    }

    int Layers::count() const {
        std::lock_guard<std::mutex> lock(_mutex);
        return static_cast<int>(_layers.size());
    }

    void Layers::clear() {
        setAll(std::vector<std::shared_ptr<Layer> >());
    }

    std::shared_ptr<Layer> Layers::get(int index) const {
        std::lock_guard<std::mutex> lock(_mutex);
        if (index < 0 || static_cast<std::size_t>(index) >= _layers.size()) {
            throw OutOfRangeException("Layer index out of range");
        }
        return _layers[index];
    }

    std::vector<std::shared_ptr<Layer> > Layers::getAll() const {
        std::lock_guard<std::mutex> lock(_mutex);
        return _layers;
    }

    void Layers::set(int index, const std::shared_ptr<Layer>& layer) {
        if (!layer) {
            throw NullArgumentException("Null layer");
        }

        std::shared_ptr<MapRenderer> mapRenderer;
        {
            std::lock_guard<std::mutex> lock(_mutex);
            if (index < 0 || static_cast<std::size_t>(index) >= _layers.size()) {
                throw OutOfRangeException("Layer index out of range");
            }

            std::shared_ptr<Layer> oldLayer = _layers[index];
            if (std::find(_layers.begin(), _layers.end(), layer) == _layers.end()) {
                layer->setComponents(_envelopeThreadPool, _tileThreadPool, _options, _mapRenderer, _touchHandler);
            }
            _layers[index] = layer;
            if (std::find(_layers.begin(), _layers.end(), oldLayer) == _layers.end()) {
                oldLayer->setComponents(std::shared_ptr<CancelableThreadPool>(), std::shared_ptr<CancelableThreadPool>(), std::shared_ptr<Options>(), std::weak_ptr<MapRenderer>(), std::weak_ptr<TouchHandler>());
            }

            mapRenderer = _mapRenderer.lock();
        }

        if (mapRenderer) {
            mapRenderer->layerChanged(layer, false);
        }
    }

    void Layers::setAll(const std::vector<std::shared_ptr<Layer> >& layers) {
        if (!std::all_of(layers.begin(), layers.end(), [](const std::shared_ptr<Layer>& layer) -> bool {
            return layer.get();
        })) {
            throw NullArgumentException("Null layer");
        }

        std::shared_ptr<MapRenderer> mapRenderer;
        {
            std::lock_guard<std::mutex> lock(_mutex);
            std::vector<std::shared_ptr<Layer> > oldLayers = _layers;
            for (const std::shared_ptr<Layer>& layer : layers) {
                if (std::find(_layers.begin(), _layers.end(), layer) == _layers.end()) {
                    layer->setComponents(_envelopeThreadPool, _tileThreadPool, _options, _mapRenderer, _touchHandler);
                }
            }
            _layers = layers;
            for (const std::shared_ptr<Layer>& oldLayer : oldLayers) {
                if (std::find(_layers.begin(), _layers.end(), oldLayer) == _layers.end()) {
                    oldLayer->setComponents(std::shared_ptr<CancelableThreadPool>(), std::shared_ptr<CancelableThreadPool>(), std::shared_ptr<Options>(), std::weak_ptr<MapRenderer>(), std::weak_ptr<TouchHandler>());
                }
            }

            mapRenderer = _mapRenderer.lock();
        }

        if (mapRenderer) {
            for (const std::shared_ptr<Layer>& layer : layers) {
                mapRenderer->layerChanged(layer, false);
            }
        }
    }

    void Layers::insert(int index, const std::shared_ptr<Layer>& layer) {
        if (!layer) {
            throw NullArgumentException("Null layer");
        }

        std::shared_ptr<MapRenderer> mapRenderer;
        {
            std::lock_guard<std::mutex> lock(_mutex);
            if (index < 0 || static_cast<std::size_t>(index) > _layers.size()) {
                throw OutOfRangeException("Layer index out of range");
            }

            if (std::find(_layers.begin(), _layers.end(), layer) == _layers.end()) {
                layer->setComponents(_envelopeThreadPool, _tileThreadPool, _options, _mapRenderer, _touchHandler);
            }
            _layers.insert(_layers.begin() + index, layer);

            mapRenderer = _mapRenderer.lock();
        }

        if (mapRenderer) {
            mapRenderer->layerChanged(layer, false);
        }
    }

    void Layers::add(const std::shared_ptr<Layer>& layer) {
        std::vector<std::shared_ptr<Layer> > layers;
        layers.push_back(layer);
        addAll(layers);
    }

    void Layers::addAll(const std::vector<std::shared_ptr<Layer> >& layers) {
        if (!std::all_of(layers.begin(), layers.end(), [](const std::shared_ptr<Layer>& layer) -> bool {
            return layer.get();
        })) {
            throw NullArgumentException("Null layer");
        }

        std::shared_ptr<MapRenderer> mapRenderer;
        {
            std::lock_guard<std::mutex> lock(_mutex);
            for (const std::shared_ptr<Layer>& layer : layers) {
                if (std::find(_layers.begin(), _layers.end(), layer) == _layers.end()) {
                    layer->setComponents(_envelopeThreadPool, _tileThreadPool, _options, _mapRenderer, _touchHandler);
                }
                _layers.push_back(layer);
            }

            mapRenderer = _mapRenderer.lock();
        }

        if (mapRenderer) {
            for (const std::shared_ptr<Layer>& layer : layers) {
                mapRenderer->layerChanged(layer, false);
            }
        }
    }

    bool Layers::remove(const std::shared_ptr<Layer>& layer) {
        std::vector<std::shared_ptr<Layer> > layers;
        layers.push_back(layer);
        return removeAll(layers);
    }

    bool Layers::removeAll(const std::vector<std::shared_ptr<Layer> >& layers) {
        if (!std::all_of(layers.begin(), layers.end(), [](const std::shared_ptr<Layer>& layer) -> bool {
            return layer.get();
        })) {
            throw NullArgumentException("Null layer");
        }

        bool removedAll = true;
        std::shared_ptr<MapRenderer> mapRenderer;
        {
            std::lock_guard<std::mutex> lock(_mutex);
            for (const std::shared_ptr<Layer>& layer : layers) {
                auto it = std::remove(_layers.begin(), _layers.end(), layer);
                if (it == _layers.end()) {
                    removedAll = false;
                    continue;
                }
                _layers.erase(it, _layers.end());
                if (std::find(_layers.begin(), _layers.end(), layer) == _layers.end()) {
                    layer->setComponents(std::shared_ptr<CancelableThreadPool>(), std::shared_ptr<CancelableThreadPool>(), std::shared_ptr<Options>(), std::weak_ptr<MapRenderer>(), std::weak_ptr<TouchHandler>());
                }
            }

            mapRenderer = _mapRenderer.lock();
        }

        if (mapRenderer) {
            mapRenderer->requestRedraw();
        }
        return removedAll;
    }

    void Layers::setComponents(const std::weak_ptr<MapRenderer>& mapRenderer, const std::weak_ptr<TouchHandler>& touchHandler) {
        _mapRenderer = mapRenderer;
        _touchHandler = touchHandler;
    }

}
<commit_msg>Fixed an issue in layer removal code that could cause removing more layers than intended<commit_after>#include "Layers.h"
#include "components/Exceptions.h"
#include "layers/Layer.h"
#include "renderers/MapRenderer.h"
#include "utils/Log.h"

namespace carto {

    Layers::Layers(const std::shared_ptr<CancelableThreadPool>& envelopeThreadPool,
                   const std::shared_ptr<CancelableThreadPool>& tileThreadPool,
                   const std::weak_ptr<Options>& options) :
        _layers(),
        _envelopeThreadPool(envelopeThreadPool),
        _tileThreadPool(tileThreadPool),
        _options(options),
        _mapRenderer(),
        _touchHandler(),
        _mutex()
    {
    }

    Layers::~Layers() {
    }

    int Layers::count() const {
        std::lock_guard<std::mutex> lock(_mutex);
        return static_cast<int>(_layers.size());
    }

    void Layers::clear() {
        setAll(std::vector<std::shared_ptr<Layer> >());
    }

    std::shared_ptr<Layer> Layers::get(int index) const {
        std::lock_guard<std::mutex> lock(_mutex);
        if (index < 0 || static_cast<std::size_t>(index) >= _layers.size()) {
            throw OutOfRangeException("Layer index out of range");
        }
        return _layers[index];
    }

    std::vector<std::shared_ptr<Layer> > Layers::getAll() const {
        std::lock_guard<std::mutex> lock(_mutex);
        return _layers;
    }

    void Layers::set(int index, const std::shared_ptr<Layer>& layer) {
        if (!layer) {
            throw NullArgumentException("Null layer");
        }

        std::shared_ptr<MapRenderer> mapRenderer;
        {
            std::lock_guard<std::mutex> lock(_mutex);
            if (index < 0 || static_cast<std::size_t>(index) >= _layers.size()) {
                throw OutOfRangeException("Layer index out of range");
            }

            std::shared_ptr<Layer> oldLayer = _layers[index];
            if (std::find(_layers.begin(), _layers.end(), layer) == _layers.end()) {
                layer->setComponents(_envelopeThreadPool, _tileThreadPool, _options, _mapRenderer, _touchHandler);
            }
            _layers[index] = layer;
            if (std::find(_layers.begin(), _layers.end(), oldLayer) == _layers.end()) {
                oldLayer->setComponents(std::shared_ptr<CancelableThreadPool>(), std::shared_ptr<CancelableThreadPool>(), std::shared_ptr<Options>(), std::weak_ptr<MapRenderer>(), std::weak_ptr<TouchHandler>());
            }

            mapRenderer = _mapRenderer.lock();
        }

        if (mapRenderer) {
            mapRenderer->layerChanged(layer, false);
        }
    }

    void Layers::setAll(const std::vector<std::shared_ptr<Layer> >& layers) {
        if (!std::all_of(layers.begin(), layers.end(), [](const std::shared_ptr<Layer>& layer) -> bool {
            return layer.get();
        })) {
            throw NullArgumentException("Null layer");
        }

        std::shared_ptr<MapRenderer> mapRenderer;
        {
            std::lock_guard<std::mutex> lock(_mutex);
            std::vector<std::shared_ptr<Layer> > oldLayers = _layers;
            for (const std::shared_ptr<Layer>& layer : layers) {
                if (std::find(_layers.begin(), _layers.end(), layer) == _layers.end()) {
                    layer->setComponents(_envelopeThreadPool, _tileThreadPool, _options, _mapRenderer, _touchHandler);
                }
            }
            _layers = layers;
            for (const std::shared_ptr<Layer>& oldLayer : oldLayers) {
                if (std::find(_layers.begin(), _layers.end(), oldLayer) == _layers.end()) {
                    oldLayer->setComponents(std::shared_ptr<CancelableThreadPool>(), std::shared_ptr<CancelableThreadPool>(), std::shared_ptr<Options>(), std::weak_ptr<MapRenderer>(), std::weak_ptr<TouchHandler>());
                }
            }

            mapRenderer = _mapRenderer.lock();
        }

        if (mapRenderer) {
            for (const std::shared_ptr<Layer>& layer : layers) {
                mapRenderer->layerChanged(layer, false);
            }
        }
    }

    void Layers::insert(int index, const std::shared_ptr<Layer>& layer) {
        if (!layer) {
            throw NullArgumentException("Null layer");
        }

        std::shared_ptr<MapRenderer> mapRenderer;
        {
            std::lock_guard<std::mutex> lock(_mutex);
            if (index < 0 || static_cast<std::size_t>(index) > _layers.size()) {
                throw OutOfRangeException("Layer index out of range");
            }

            if (std::find(_layers.begin(), _layers.end(), layer) == _layers.end()) {
                layer->setComponents(_envelopeThreadPool, _tileThreadPool, _options, _mapRenderer, _touchHandler);
            }
            _layers.insert(_layers.begin() + index, layer);

            mapRenderer = _mapRenderer.lock();
        }

        if (mapRenderer) {
            mapRenderer->layerChanged(layer, false);
        }
    }

    void Layers::add(const std::shared_ptr<Layer>& layer) {
        addAll(std::vector<std::shared_ptr<Layer> > { layer });
    }

    void Layers::addAll(const std::vector<std::shared_ptr<Layer> >& layers) {
        if (!std::all_of(layers.begin(), layers.end(), [](const std::shared_ptr<Layer>& layer) -> bool {
            return layer.get();
        })) {
            throw NullArgumentException("Null layer");
        }

        std::shared_ptr<MapRenderer> mapRenderer;
        {
            std::lock_guard<std::mutex> lock(_mutex);
            for (const std::shared_ptr<Layer>& layer : layers) {
                if (std::find(_layers.begin(), _layers.end(), layer) == _layers.end()) {
                    layer->setComponents(_envelopeThreadPool, _tileThreadPool, _options, _mapRenderer, _touchHandler);
                }
                _layers.push_back(layer);
            }

            mapRenderer = _mapRenderer.lock();
        }

        if (mapRenderer) {
            for (const std::shared_ptr<Layer>& layer : layers) {
                mapRenderer->layerChanged(layer, false);
            }
        }
    }

    bool Layers::remove(const std::shared_ptr<Layer>& layer) {
        return removeAll(std::vector<std::shared_ptr<Layer> > { layer });
    }

    bool Layers::removeAll(const std::vector<std::shared_ptr<Layer> >& layers) {
        if (!std::all_of(layers.begin(), layers.end(), [](const std::shared_ptr<Layer>& layer) -> bool {
            return layer.get();
        })) {
            throw NullArgumentException("Null layer");
        }

        bool removedAll = true;
        std::shared_ptr<MapRenderer> mapRenderer;
        {
            std::lock_guard<std::mutex> lock(_mutex);
            for (const std::shared_ptr<Layer>& layer : layers) {
                auto it = std::remove(_layers.begin(), _layers.end(), layer);
                if (it == _layers.end()) {
                    removedAll = false;
                    continue;
                }
                _layers.erase(it);
                if (std::find(_layers.begin(), _layers.end(), layer) == _layers.end()) {
                    layer->setComponents(std::shared_ptr<CancelableThreadPool>(), std::shared_ptr<CancelableThreadPool>(), std::shared_ptr<Options>(), std::weak_ptr<MapRenderer>(), std::weak_ptr<TouchHandler>());
                }
            }

            mapRenderer = _mapRenderer.lock();
        }

        if (mapRenderer) {
            mapRenderer->requestRedraw();
        }
        return removedAll;
    }

    void Layers::setComponents(const std::weak_ptr<MapRenderer>& mapRenderer, const std::weak_ptr<TouchHandler>& touchHandler) {
        _mapRenderer = mapRenderer;
        _touchHandler = touchHandler;
    }

}
<|endoftext|>


<commit_before>#ifndef WINDOW_HPP
#define WINDOW_HPP

#include <string>
#include <vector>

#include <VBE/math.hpp>
#include <VBE/system/ContextSettings.hpp>
#include <VBE/utils/NonCopyable.hpp>
#include <VBE/system/Log.hpp>

class WindowImpl;
///
/// \brief The Window class represents the application's display
///
class Window : public NonCopyable {
	public:

		///
		/// \brief The DisplayMode class represents a display mode that can be used.
		/// There are two types of DisplayModes: Fullscreen and Windowed. You can
		/// create a Windowed mode with the size you want, but you're restricted to
		/// use the Fullscreen modes from Window::getFullscreenModes(), which
		/// are the modes supported by the hardware.
		///
		class DisplayMode {
			public:

				///
				/// \brief Types of DisplayModes
				///
				enum Type {
					Fullscreen,
					Windowed
				};

				///
				/// \brief getWidth returns the width of the DisplayMode.
				/// \return the width of the DisplayMode.
				///
				unsigned int getWidth() const {
					return width;
				}

				///
				/// \brief getHeight returns the height of the DisplayMode.
				/// \return the height of the DisplayMode.
				///
				unsigned int getHeight() const {
					return height;
				}

				///
				/// \brief getSize returns the size of the DisplayMode.
				/// \return the size of the DisplayMode.
				///
				vec2ui getSize() const  {
					return vec2ui(width, height);
				}

				///
				/// \brief getRefreshRate returns the refresh rate of the DisplayMode.
				/// You may only call this function on Fullscreen modes, since Windowed
				/// modes use the desktop's refresh rate.
				/// \return the refresh rate of the DisplayMode.
				///
				unsigned int getRefreshRate() const {
					VBE_ASSERT(getType() == Windowed, "You may not query the refresh rate of a Windowed mode");
					return refreshRate;
				}

				///
				/// \brief getType Returns the type of the DisplayMode: Fullscreen or Windowed.
				/// \return the type of the DisplayMode.
				///
				Type getType() const {
					return type;
				}

				///
				/// \brief createWindowedMode Creates a Windowed DisplayMode you can use to
				/// create a Window with the size of your choice.
				/// \param width the width of the window.
				/// \param height the height of the window.
				/// \return the created windowed mode.
				///
				static DisplayMode createWindowedMode(int width, int height) {
					return DisplayMode(width, height, 0, Windowed);
				}
			private:
				DisplayMode(int w, int h, int r, Type t) : width(w), height(h), refreshRate(r), type(t) {}
				unsigned int width;
				unsigned int height;
				unsigned int refreshRate;
				Type type;

				// Implementation defined, do not use.
				int implementationData;

				friend class Window;
				friend class WindowImpl;
		};

		///
		/// \brief The VsyncMode enum
		///
		enum VsyncMode {
			DisabledVsync = 0, ///< The framerate won't be capped
			EnabledVsync, ///< The framerate will be capped to the screen's refresh rate
			LateTearingVsync
		};

		///
		/// \brief getFullscreenModes returns all the Fullscreen display modes supported by
		/// the hardware. You must use one of these modes to create a Fullscreen Window.
		/// The modes are sorted decreasingly by width, then by height. Therefore,
		/// the first Fullscreen mode is most likely the one you want to use.
		/// \return the supported Fullscreen modes.
		///
		static std::vector<DisplayMode> getFullscreenModes();

		///
		/// \brief Window Creates a Window with the specified DisplayMode and ContextSettings.
		/// This will create an OpenGL context on the Window so you can draw to it.
		///
		/// It's not guaranteed that the final size of the Window will be the one specified
		/// in the DisplayMode, you should always call getSize to get the real size of the Window.
		/// For example, on Android mode is ignored entirely, and the Window is always
		/// created the size of the Window.
		///
		/// There can be only one Window created at a given time. If there's another Window
		/// already created, this constructor will error.
		///
		/// \param mode DisplayMode to use in the Window
		/// \param contextSettings OpenGL context settings. Optional, if you leave it out it will use
		/// the default settings, which are OpenGL 4.2 on desktop or OpenGL ES 2 on mobile.
		///
		Window(DisplayMode mode, ContextSettings contextSettings = ContextSettings());

		///
		/// \brief Destructor
		///
		~Window();

		///
		/// \brief update runs the event loop, updating the input devices and other events. You
		/// should call it once per frame. Calling it less often will cause the input devices to not update,
		/// and calling it more often will make justPressed/justReleased in the inputs behave wrong.
		///
		/// This method may block on some platforms, such as Android, if the app goes to the background,
		/// to avoid crashes and/or wasting CPU. For this reason, you should call this every frame
		/// even if you're not reading any inputs.
		///
		void update();

		///
		/// \brief getSize gets the Window size. This may be different to the size specified in the
		/// DisplayMode, see Window's constructor for details.
		/// \return the Window size.
		///
		vec2ui getSize() const;

		///
		/// \brief setDisplayMode changes the display mode of the Window. The final Window size may be
		/// different to the one specified in the display mode, see Window's constructor for details.
		/// \param mode the new display mode.
		///
		void setDisplayMode(DisplayMode mode);

		///
		/// \brief setVsync changes the Vsync mode of the Window.
		/// \param mode the new vsync mode.
		///
		void setVsync(VsyncMode mode);

		///
		/// \brief getTitle gets the title of the Window.
		/// \return the title.
		///
		std::string getTitle() const;

		///
		/// \brief setTitle sets the title of the Window.
		/// \param newTitle the new title.
		///
		void setTitle(std::string newTitle);

		///
		/// \brief isFocused returns whether the Window is focused, that is, the Window is in
		/// foreground and is receiving keyboard and mouse input. It's useful to pause the game
		/// when the user minimizes it, for example.
		/// \return whether the Window is focused.
		///
		bool isFocused() const;

		///
		/// \brief returns wether the window has been requested to close. This can happen through a quit event
		/// (alt+F4, system call or similar), a window close or a call to setClosing().
		/// \return whether the Window is closing.
		///
		bool isClosing() const;

		///
		/// \brief set the closing status of the window. Setting it won't have any direct effect on the application,
		/// but you can use it to discard user-mode quits. For example, to implement a warning before closing.
		///	Remember that system-mode quits may kill your application anyway.
		/// \param newClosing the new state for the window.
		///
		void setClosing(bool newClosing);

		///
		/// \brief setPosition Sets the Window position in pixe.s, relative the the computer Window.
		/// \param x the X coordinate of the position.
		/// \param y the Y coordinate of the position.
		///
		void setPosition(unsigned int x, unsigned int y);

		///
		/// \brief swapBuffers Swaps OpenGL buffers. This will cause everything you have
		/// drawn using OpenGL to become visible on the Window. You should call this once every
		/// frame after drawing everything.
		///
		void swapBuffers() const;

		///
		/// \brief getInstance returns a pointer to the current Window instance.
		/// \return a pointer to the current created Window, or nullptr if none.
		///
		static Window* getInstance();

	private:
		WindowImpl* impl;
		std::string title;

		static Window* instance;
};

#endif // WINDOW_HPP
<commit_msg>Window docs were messy<commit_after>#ifndef WINDOW_HPP
#define WINDOW_HPP

#include <string>
#include <vector>

#include <VBE/math.hpp>
#include <VBE/system/ContextSettings.hpp>
#include <VBE/utils/NonCopyable.hpp>
#include <VBE/system/Log.hpp>

class WindowImpl;
///
/// \brief The Window class represents the application's display
///
class Window : public NonCopyable {
	public:

		///
		/// \brief The DisplayMode class represents a display mode that can be used.
		///
		/// There are two types of DisplayModes: Fullscreen and Windowed. You can
		/// create a Windowed mode with the size you want, but you're restricted to
		/// use the Fullscreen modes from Window::getFullscreenModes(), which
		/// are the modes supported by the hardware.
		///
		class DisplayMode {
			public:

				///
				/// \brief Types of DisplayModes
				///
				enum Type {
					Fullscreen,
					Windowed
				};

				///
				/// \brief Returns the width of the DisplayMode.
				/// \return the width of the DisplayMode.
				///
				unsigned int getWidth() const {
					return width;
				}

				///
				/// \brief Returns the height of the DisplayMode.
				/// \return the height of the DisplayMode.
				///
				unsigned int getHeight() const {
					return height;
				}

				///
				/// \brief Returns the size of the DisplayMode.
				/// \return the size of the DisplayMode.
				///
				vec2ui getSize() const  {
					return vec2ui(width, height);
				}

				///
				/// \brief Returns the refresh rate of the DisplayMode.
				///
				/// You may only call this function on Fullscreen modes, since Windowed
				/// modes use the desktop's refresh rate.
				/// \return the refresh rate of the DisplayMode.
				///
				unsigned int getRefreshRate() const {
					VBE_ASSERT(getType() == Windowed, "You may not query the refresh rate of a Windowed mode");
					return refreshRate;
				}

				///
				/// \brief Returns the type of the DisplayMode \see DisplayMode::Type
				/// \return the type of the DisplayMode.
				///
				Type getType() const {
					return type;
				}

				///
				/// \brief Creates a Windowed DisplayMode you can use to create a Window with the size of your choice.
				/// \param width the width of the window.
				/// \param height the height of the window.
				/// \return the created windowed mode.
				///
				static DisplayMode createWindowedMode(int width, int height) {
					return DisplayMode(width, height, 0, Windowed);
				}
			private:
				DisplayMode(int w, int h, int r, Type t) : width(w), height(h), refreshRate(r), type(t) {}
				unsigned int width;
				unsigned int height;
				unsigned int refreshRate;
				Type type;

				// Implementation defined, do not use.
				int implementationData;

				friend class Window;
				friend class WindowImpl;
		};

		///
		/// \brief The VsyncMode enum
		///
		enum VsyncMode {
			DisabledVsync = 0, ///< The framerate won't be capped
			EnabledVsync, ///< The framerate will be capped to the screen's refresh rate
			LateTearingVsync
		};

		///
		/// \brief Returns all the Fullscreen display modes supported by the hardware.
		///
		/// You must use one of these modes to create a Fullscreen Window.
		/// The modes are sorted decreasingly by width, then by height. Therefore,
		/// the first Fullscreen mode is most likely the one you want to use.
		///
		/// \return the supported Fullscreen modes.
		///
		static std::vector<DisplayMode> getFullscreenModes();

		///
		/// \brief Creates a Window with the specified DisplayMode and ContextSettings.
		///
		/// This will create an OpenGL context on the Window so you can draw to it.
		///
		/// It's not guaranteed that the final size of the Window will be the one specified
		/// in the DisplayMode, you should always call getSize to get the real size of the Window.
		/// For example, on Android mode is ignored entirely, and the Window is always
		/// created the size of the Window.
		///
		/// There can be only one Window created at a given time. If there's another Window
		/// already created, this constructor will error.
		///
		/// \param mode DisplayMode to use in the Window
		/// \param contextSettings OpenGL context settings. Optional, if you leave it out it will use
		/// the default settings, which are OpenGL 4.2 on desktop or OpenGL ES 2 on mobile.
		///
		Window(DisplayMode mode, ContextSettings contextSettings = ContextSettings());

		///
		/// \brief Destructor
		///
		~Window();

		///
		/// \brief Runs the event loop, updating the input devices and other events.
		///
		/// You should call it once per frame. Calling it less often will cause the input devices to not update,
		/// and calling it more often will make justPressed/justReleased in the inputs behave wrong.
		///
		/// This method may block on some platforms, such as Android, if the app goes to the background,
		/// to avoid crashes and/or wasting CPU. For this reason, you should call this every frame
		/// even if you're not reading any inputs.
		///
		void update();

		///
		/// \brief Gets the Window size.
		///
		/// This may be different to the size specified in the
		/// DisplayMode, see Window's constructor for details.
		/// \return the Window size.
		///
		vec2ui getSize() const;

		///
		/// \brief Changes the display mode of the Window.
		///
		/// The final Window size may be
		/// different to the one specified in the display mode, see Window constructor for details.
		///
		/// \param mode the new display mode.
		///
		void setDisplayMode(DisplayMode mode);

		///
		/// \brief Changes the Vsync mode of the Window.
		/// \param mode the new vsync mode.
		///
		void setVsync(VsyncMode mode);

		///
		/// \brief Gets the title of the Window.
		/// \return the title.
		///
		std::string getTitle() const;

		///
		/// \brief Sets the title of the Window.
		/// \param newTitle the new title.
		///
		void setTitle(std::string newTitle);

		///
		/// \brief Returns whether the Window is focused.
		///
		/// That is, the Window is in the
		/// foreground and is receiving keyboard and mouse input. It's useful to pause the game
		/// when the user minimizes it, for example.
		///
		/// \return whether the Window is focused.
		///
		bool isFocused() const;

		///
		/// \brief Returns wether the window has been requested to close.
		///
		/// This can happen through a quit event
		/// (alt+F4, system call or similar), a window close or a call to setClosing().
		///
		/// \return whether the Window is closing.
		///
		bool isClosing() const;

		///
		/// \brief Set the closing status of the window.
		///
		/// Setting it won't have any direct effect on the application,
		/// but you can use it to discard user-mode quits. For example, to implement a warning before closing.
		///	Remember that system-mode quits may kill your application anyway.
		///
		/// \param newClosing the new state for the window.
		///
		void setClosing(bool newClosing);

		///
		/// \brief Sets the Window position in pixe.s, relative the the computer Window.
		/// \param x the X coordinate of the position.
		/// \param y the Y coordinate of the position.
		///
		void setPosition(unsigned int x, unsigned int y);

		///
		/// \brief Swaps OpenGL buffers.
		///
		/// This will cause everything you have
		/// drawn using OpenGL to become visible on the Window. You should call this once every
		/// frame after drawing everything.
		///
		void swapBuffers() const;

		///
		/// \brief Returns a pointer to the current Window instance.
		/// \return a pointer to the current created Window, or nullptr if none.
		///
		static Window* getInstance();

	private:
		WindowImpl* impl;
		std::string title;

		static Window* instance;
};

#endif // WINDOW_HPP
<|endoftext|>


<commit_before>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/net/atom_network_delegate.h"

#include <string>

#include "atom/common/native_mate_converters/net_converter.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/resource_request_info.h"
#include "net/url_request/url_request.h"

using content::BrowserThread;

namespace atom {

namespace {

const char* ResourceTypeToString(content::ResourceType type) {
  switch (type) {
    case content::RESOURCE_TYPE_MAIN_FRAME:
      return "mainFrame";
    case content::RESOURCE_TYPE_SUB_FRAME:
      return "subFrame";
    case content::RESOURCE_TYPE_STYLESHEET:
      return "stylesheet";
    case content::RESOURCE_TYPE_SCRIPT:
      return "script";
    case content::RESOURCE_TYPE_IMAGE:
      return "image";
    case content::RESOURCE_TYPE_OBJECT:
      return "object";
    case content::RESOURCE_TYPE_XHR:
      return "xhr";
    default:
      return "other";
  }
}

void RunSimpleListener(const AtomNetworkDelegate::SimpleListener& listener,
                       scoped_ptr<base::DictionaryValue> details) {
  return listener.Run(*(details.get()));
}

void RunResponseListener(
    const AtomNetworkDelegate::ResponseListener& listener,
    scoped_ptr<base::DictionaryValue> details,
    const AtomNetworkDelegate::ResponseCallback& callback) {
  return listener.Run(*(details.get()), callback);
}

// Test whether the URL of |request| matches |patterns|.
bool MatchesFilterCondition(net::URLRequest* request,
                            const URLPatterns& patterns) {
  if (patterns.empty())
    return true;

  for (const auto& pattern : patterns) {
    if (pattern.MatchesURL(request->url()))
      return true;
  }
  return false;
}

// Overloaded by multiple types to fill the |details| object.
void ToDictionary(base::DictionaryValue* details, net::URLRequest* request) {
  details->SetInteger("id", request->identifier());
  details->SetString("url", request->url().spec());
  details->SetString("method", request->method());
  details->SetDouble("timestamp", base::Time::Now().ToDoubleT() * 1000);
  auto info = content::ResourceRequestInfo::ForRequest(request);
  details->SetString("resourceType",
                     info ? ResourceTypeToString(info->GetResourceType())
                          : "other");
}

void ToDictionary(base::DictionaryValue* details,
                  const net::HttpRequestHeaders& headers) {
  scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue);
  net::HttpRequestHeaders::Iterator it(headers);
  while (it.GetNext())
    dict->SetString(it.name(), it.value());
  details->Set("requestHeaders", dict.Pass());
}

void ToDictionary(base::DictionaryValue* details,
                  const net::HttpResponseHeaders* headers) {
  if (!headers)
    return;

  scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue);
  void* iter = nullptr;
  std::string key;
  std::string value;
  while (headers->EnumerateHeaderLines(&iter, &key, &value)) {
    if (dict->HasKey(key)) {
      base::ListValue* values = nullptr;
      if (dict->GetList(key, &values))
        values->AppendString(value);
    } else {
      scoped_ptr<base::ListValue> values(new base::ListValue);
      values->AppendString(value);
      dict->Set(key, values.Pass());
    }
  }
  details->Set("responseHeaders", dict.Pass());
  details->SetString("statusLine", headers->GetStatusLine());
  details->SetInteger("statusCode", headers->response_code());
}

void ToDictionary(base::DictionaryValue* details, const GURL& location) {
  details->SetString("redirectURL", location.spec());
}

void ToDictionary(base::DictionaryValue* details,
                  const net::HostPortPair& host_port) {
  if (host_port.host().empty())
    details->SetString("ip", host_port.host());
}

void ToDictionary(base::DictionaryValue* details, bool from_cache) {
  details->SetBoolean("fromCache", from_cache);
}

void ToDictionary(base::DictionaryValue* details,
                  const net::URLRequestStatus& status) {
  details->SetString("error", net::ErrorToString(status.error()));
}

// Helper function to fill |details| with arbitrary |args|.
template<typename Arg>
void FillDetailsObject(base::DictionaryValue* details, Arg arg) {
  ToDictionary(details, arg);
}

template<typename Arg, typename... Args>
void FillDetailsObject(base::DictionaryValue* details, Arg arg, Args... args) {
  ToDictionary(details, arg);
  FillDetailsObject(details, args...);
}

// Fill the native types with the result from the response object.
void ReadFromResponseObject(const base::DictionaryValue& response,
                            GURL* new_location) {
  std::string url;
  if (response.GetString("redirectURL", &url))
    *new_location = GURL(url);
}

void ReadFromResponseObject(const base::DictionaryValue& response,
                            net::HttpRequestHeaders* headers) {
  const base::DictionaryValue* dict;
  if (response.GetDictionary("requestHeaders", &dict)) {
    for (base::DictionaryValue::Iterator it(*dict);
         !it.IsAtEnd();
         it.Advance()) {
      std::string value;
      if (it.value().GetAsString(&value))
        headers->SetHeader(it.key(), value);
    }
  }
}

void ReadFromResponseObject(const base::DictionaryValue& response,
                            scoped_refptr<net::HttpResponseHeaders>* headers) {
  const base::DictionaryValue* dict;
  if (response.GetDictionary("responseHeaders", &dict)) {
    *headers = new net::HttpResponseHeaders("");
    for (base::DictionaryValue::Iterator it(*dict);
         !it.IsAtEnd();
         it.Advance()) {
      const base::ListValue* list;
      if (it.value().GetAsList(&list)) {
        (*headers)->RemoveHeader(it.key());
        for (size_t i = 0; i < list->GetSize(); ++i) {
          std::string value;
          if (list->GetString(i, &value))
            (*headers)->AddHeader(it.key() + " : " + value);
        }
      }
    }
  }
}

}  // namespace

AtomNetworkDelegate::AtomNetworkDelegate() {
}

AtomNetworkDelegate::~AtomNetworkDelegate() {
}

void AtomNetworkDelegate::SetSimpleListenerInIO(
    SimpleEvent type,
    const URLPatterns& patterns,
    const SimpleListener& callback) {
  if (callback.is_null())
    simple_listeners_.erase(type);
  else
    simple_listeners_[type] = { patterns, callback };
}

void AtomNetworkDelegate::SetResponseListenerInIO(
    ResponseEvent type,
    const URLPatterns& patterns,
    const ResponseListener& callback) {
  if (callback.is_null())
    response_listeners_.erase(type);
  else
    response_listeners_[type] = { patterns, callback };
}

int AtomNetworkDelegate::OnBeforeURLRequest(
    net::URLRequest* request,
    const net::CompletionCallback& callback,
    GURL* new_url) {
  if (!ContainsKey(response_listeners_, kOnBeforeRequest))
    return brightray::NetworkDelegate::OnBeforeURLRequest(
        request, callback, new_url);

  return HandleResponseEvent(kOnBeforeRequest, request, callback, new_url);
}

int AtomNetworkDelegate::OnBeforeSendHeaders(
    net::URLRequest* request,
    const net::CompletionCallback& callback,
    net::HttpRequestHeaders* headers) {
  if (!ContainsKey(response_listeners_, kOnBeforeSendHeaders))
    return brightray::NetworkDelegate::OnBeforeSendHeaders(
        request, callback, headers);

  return HandleResponseEvent(
      kOnBeforeSendHeaders, request, callback, headers, *headers);
}

void AtomNetworkDelegate::OnSendHeaders(
    net::URLRequest* request,
    const net::HttpRequestHeaders& headers) {
  if (!ContainsKey(simple_listeners_, kOnSendHeaders)) {
    brightray::NetworkDelegate::OnSendHeaders(request, headers);
    return;
  }

  HandleSimpleEvent(kOnSendHeaders, request, headers);
}

int AtomNetworkDelegate::OnHeadersReceived(
    net::URLRequest* request,
    const net::CompletionCallback& callback,
    const net::HttpResponseHeaders* original,
    scoped_refptr<net::HttpResponseHeaders>* override,
    GURL* allowed) {
  if (!ContainsKey(response_listeners_, kOnHeadersReceived))
    return brightray::NetworkDelegate::OnHeadersReceived(
        request, callback, original, override, allowed);

  return HandleResponseEvent(
      kOnHeadersReceived, request, callback, override, original);
}

void AtomNetworkDelegate::OnBeforeRedirect(net::URLRequest* request,
                                           const GURL& new_location) {
  if (!ContainsKey(simple_listeners_, kOnBeforeRedirect)) {
    brightray::NetworkDelegate::OnBeforeRedirect(request, new_location);
    return;
  }

  HandleSimpleEvent(kOnBeforeRedirect, request, new_location,
                    request->response_headers(), request->GetSocketAddress(),
                    request->was_cached());
}

void AtomNetworkDelegate::OnResponseStarted(net::URLRequest* request) {
  if (!ContainsKey(simple_listeners_, kOnResponseStarted)) {
    brightray::NetworkDelegate::OnResponseStarted(request);
    return;
  }

  if (request->status().status() != net::URLRequestStatus::SUCCESS)
    return;

  HandleSimpleEvent(kOnResponseStarted, request, request->response_headers(),
                    request->was_cached());
}

void AtomNetworkDelegate::OnCompleted(net::URLRequest* request, bool started) {
  // OnCompleted may happen before other events.
  callbacks_.erase(request->identifier());

  if (request->status().status() == net::URLRequestStatus::FAILED ||
      request->status().status() == net::URLRequestStatus::CANCELED) {
    // Error event.
    OnErrorOccurred(request, started);
    return;
  } else if (request->response_headers() &&
             net::HttpResponseHeaders::IsRedirectResponseCode(
                 request->response_headers()->response_code())) {
    // Redirect event.
    brightray::NetworkDelegate::OnCompleted(request, started);
    return;
  }

  if (!ContainsKey(simple_listeners_, kOnCompleted)) {
    brightray::NetworkDelegate::OnCompleted(request, started);
    return;
  }

  HandleSimpleEvent(kOnCompleted, request, request->response_headers(),
                    request->was_cached());
}

void AtomNetworkDelegate::OnURLRequestDestroyed(net::URLRequest* request) {
  callbacks_.erase(request->identifier());
}

void AtomNetworkDelegate::OnErrorOccurred(
    net::URLRequest* request, bool started) {
  if (!ContainsKey(simple_listeners_, kOnErrorOccurred)) {
    brightray::NetworkDelegate::OnCompleted(request, started);
    return;
  }

  HandleSimpleEvent(kOnErrorOccurred, request, request->was_cached(),
                    request->status());
}

template<typename Out, typename... Args>
int AtomNetworkDelegate::HandleResponseEvent(
    ResponseEvent type,
    net::URLRequest* request,
    const net::CompletionCallback& callback,
    Out out,
    Args... args) {
  const auto& info = response_listeners_[type];
  if (!MatchesFilterCondition(request, info.url_patterns))
    return net::OK;

  scoped_ptr<base::DictionaryValue> details(new base::DictionaryValue);
  FillDetailsObject(details.get(), request, args...);

  // The |request| could be destroyed before the |callback| is called.
  callbacks_[request->identifier()] = callback;

  ResponseCallback response =
      base::Bind(&AtomNetworkDelegate::OnListenerResultInUI<Out>,
                 base::Unretained(this), request->identifier(), out);
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(RunResponseListener, info.listener, base::Passed(&details),
                 response));
  return net::ERR_IO_PENDING;
}

template<typename...Args>
void AtomNetworkDelegate::HandleSimpleEvent(
    SimpleEvent type, net::URLRequest* request, Args... args) {
  const auto& info = simple_listeners_[type];
  if (!MatchesFilterCondition(request, info.url_patterns))
    return;

  scoped_ptr<base::DictionaryValue> details(new base::DictionaryValue);
  FillDetailsObject(details.get(), request, args...);

  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(RunSimpleListener, info.listener, base::Passed(&details)));
}

template<typename T>
void AtomNetworkDelegate::OnListenerResultInIO(
    uint64_t id, T out, scoped_ptr<base::DictionaryValue> response) {
  // The request has been destroyed.
  if (!ContainsKey(callbacks_, id))
    return;

  ReadFromResponseObject(*response.get(), out);

  bool cancel = false;
  response->GetBoolean("cancel", &cancel);
  callbacks_[id].Run(cancel ? net::ERR_BLOCKED_BY_CLIENT : net::OK);
}

template<typename T>
void AtomNetworkDelegate::OnListenerResultInUI(
    uint64_t id, T out, const base::DictionaryValue& response) {
  scoped_ptr<base::DictionaryValue> copy = response.CreateDeepCopy();
  BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      base::Bind(&AtomNetworkDelegate::OnListenerResultInIO<T>,
                 base::Unretained(this),  id, out, base::Passed(&copy)));
}

}  // namespace atom
<commit_msg>Reset whole headers when requestHeaders is set<commit_after>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/net/atom_network_delegate.h"

#include <string>

#include "atom/common/native_mate_converters/net_converter.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/resource_request_info.h"
#include "net/url_request/url_request.h"

using content::BrowserThread;

namespace atom {

namespace {

const char* ResourceTypeToString(content::ResourceType type) {
  switch (type) {
    case content::RESOURCE_TYPE_MAIN_FRAME:
      return "mainFrame";
    case content::RESOURCE_TYPE_SUB_FRAME:
      return "subFrame";
    case content::RESOURCE_TYPE_STYLESHEET:
      return "stylesheet";
    case content::RESOURCE_TYPE_SCRIPT:
      return "script";
    case content::RESOURCE_TYPE_IMAGE:
      return "image";
    case content::RESOURCE_TYPE_OBJECT:
      return "object";
    case content::RESOURCE_TYPE_XHR:
      return "xhr";
    default:
      return "other";
  }
}

void RunSimpleListener(const AtomNetworkDelegate::SimpleListener& listener,
                       scoped_ptr<base::DictionaryValue> details) {
  return listener.Run(*(details.get()));
}

void RunResponseListener(
    const AtomNetworkDelegate::ResponseListener& listener,
    scoped_ptr<base::DictionaryValue> details,
    const AtomNetworkDelegate::ResponseCallback& callback) {
  return listener.Run(*(details.get()), callback);
}

// Test whether the URL of |request| matches |patterns|.
bool MatchesFilterCondition(net::URLRequest* request,
                            const URLPatterns& patterns) {
  if (patterns.empty())
    return true;

  for (const auto& pattern : patterns) {
    if (pattern.MatchesURL(request->url()))
      return true;
  }
  return false;
}

// Overloaded by multiple types to fill the |details| object.
void ToDictionary(base::DictionaryValue* details, net::URLRequest* request) {
  details->SetInteger("id", request->identifier());
  details->SetString("url", request->url().spec());
  details->SetString("method", request->method());
  details->SetDouble("timestamp", base::Time::Now().ToDoubleT() * 1000);
  auto info = content::ResourceRequestInfo::ForRequest(request);
  details->SetString("resourceType",
                     info ? ResourceTypeToString(info->GetResourceType())
                          : "other");
}

void ToDictionary(base::DictionaryValue* details,
                  const net::HttpRequestHeaders& headers) {
  scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue);
  net::HttpRequestHeaders::Iterator it(headers);
  while (it.GetNext())
    dict->SetString(it.name(), it.value());
  details->Set("requestHeaders", dict.Pass());
}

void ToDictionary(base::DictionaryValue* details,
                  const net::HttpResponseHeaders* headers) {
  if (!headers)
    return;

  scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue);
  void* iter = nullptr;
  std::string key;
  std::string value;
  while (headers->EnumerateHeaderLines(&iter, &key, &value)) {
    if (dict->HasKey(key)) {
      base::ListValue* values = nullptr;
      if (dict->GetList(key, &values))
        values->AppendString(value);
    } else {
      scoped_ptr<base::ListValue> values(new base::ListValue);
      values->AppendString(value);
      dict->Set(key, values.Pass());
    }
  }
  details->Set("responseHeaders", dict.Pass());
  details->SetString("statusLine", headers->GetStatusLine());
  details->SetInteger("statusCode", headers->response_code());
}

void ToDictionary(base::DictionaryValue* details, const GURL& location) {
  details->SetString("redirectURL", location.spec());
}

void ToDictionary(base::DictionaryValue* details,
                  const net::HostPortPair& host_port) {
  if (host_port.host().empty())
    details->SetString("ip", host_port.host());
}

void ToDictionary(base::DictionaryValue* details, bool from_cache) {
  details->SetBoolean("fromCache", from_cache);
}

void ToDictionary(base::DictionaryValue* details,
                  const net::URLRequestStatus& status) {
  details->SetString("error", net::ErrorToString(status.error()));
}

// Helper function to fill |details| with arbitrary |args|.
template<typename Arg>
void FillDetailsObject(base::DictionaryValue* details, Arg arg) {
  ToDictionary(details, arg);
}

template<typename Arg, typename... Args>
void FillDetailsObject(base::DictionaryValue* details, Arg arg, Args... args) {
  ToDictionary(details, arg);
  FillDetailsObject(details, args...);
}

// Fill the native types with the result from the response object.
void ReadFromResponseObject(const base::DictionaryValue& response,
                            GURL* new_location) {
  std::string url;
  if (response.GetString("redirectURL", &url))
    *new_location = GURL(url);
}

void ReadFromResponseObject(const base::DictionaryValue& response,
                            net::HttpRequestHeaders* headers) {
  const base::DictionaryValue* dict;
  if (response.GetDictionary("requestHeaders", &dict)) {
    headers->Clear();
    for (base::DictionaryValue::Iterator it(*dict);
         !it.IsAtEnd();
         it.Advance()) {
      std::string value;
      if (it.value().GetAsString(&value))
        headers->SetHeader(it.key(), value);
    }
  }
}

void ReadFromResponseObject(const base::DictionaryValue& response,
                            scoped_refptr<net::HttpResponseHeaders>* headers) {
  const base::DictionaryValue* dict;
  if (response.GetDictionary("responseHeaders", &dict)) {
    *headers = new net::HttpResponseHeaders("");
    for (base::DictionaryValue::Iterator it(*dict);
         !it.IsAtEnd();
         it.Advance()) {
      const base::ListValue* list;
      if (it.value().GetAsList(&list)) {
        (*headers)->RemoveHeader(it.key());
        for (size_t i = 0; i < list->GetSize(); ++i) {
          std::string value;
          if (list->GetString(i, &value))
            (*headers)->AddHeader(it.key() + " : " + value);
        }
      }
    }
  }
}

}  // namespace

AtomNetworkDelegate::AtomNetworkDelegate() {
}

AtomNetworkDelegate::~AtomNetworkDelegate() {
}

void AtomNetworkDelegate::SetSimpleListenerInIO(
    SimpleEvent type,
    const URLPatterns& patterns,
    const SimpleListener& callback) {
  if (callback.is_null())
    simple_listeners_.erase(type);
  else
    simple_listeners_[type] = { patterns, callback };
}

void AtomNetworkDelegate::SetResponseListenerInIO(
    ResponseEvent type,
    const URLPatterns& patterns,
    const ResponseListener& callback) {
  if (callback.is_null())
    response_listeners_.erase(type);
  else
    response_listeners_[type] = { patterns, callback };
}

int AtomNetworkDelegate::OnBeforeURLRequest(
    net::URLRequest* request,
    const net::CompletionCallback& callback,
    GURL* new_url) {
  if (!ContainsKey(response_listeners_, kOnBeforeRequest))
    return brightray::NetworkDelegate::OnBeforeURLRequest(
        request, callback, new_url);

  return HandleResponseEvent(kOnBeforeRequest, request, callback, new_url);
}

int AtomNetworkDelegate::OnBeforeSendHeaders(
    net::URLRequest* request,
    const net::CompletionCallback& callback,
    net::HttpRequestHeaders* headers) {
  if (!ContainsKey(response_listeners_, kOnBeforeSendHeaders))
    return brightray::NetworkDelegate::OnBeforeSendHeaders(
        request, callback, headers);

  return HandleResponseEvent(
      kOnBeforeSendHeaders, request, callback, headers, *headers);
}

void AtomNetworkDelegate::OnSendHeaders(
    net::URLRequest* request,
    const net::HttpRequestHeaders& headers) {
  if (!ContainsKey(simple_listeners_, kOnSendHeaders)) {
    brightray::NetworkDelegate::OnSendHeaders(request, headers);
    return;
  }

  HandleSimpleEvent(kOnSendHeaders, request, headers);
}

int AtomNetworkDelegate::OnHeadersReceived(
    net::URLRequest* request,
    const net::CompletionCallback& callback,
    const net::HttpResponseHeaders* original,
    scoped_refptr<net::HttpResponseHeaders>* override,
    GURL* allowed) {
  if (!ContainsKey(response_listeners_, kOnHeadersReceived))
    return brightray::NetworkDelegate::OnHeadersReceived(
        request, callback, original, override, allowed);

  return HandleResponseEvent(
      kOnHeadersReceived, request, callback, override, original);
}

void AtomNetworkDelegate::OnBeforeRedirect(net::URLRequest* request,
                                           const GURL& new_location) {
  if (!ContainsKey(simple_listeners_, kOnBeforeRedirect)) {
    brightray::NetworkDelegate::OnBeforeRedirect(request, new_location);
    return;
  }

  HandleSimpleEvent(kOnBeforeRedirect, request, new_location,
                    request->response_headers(), request->GetSocketAddress(),
                    request->was_cached());
}

void AtomNetworkDelegate::OnResponseStarted(net::URLRequest* request) {
  if (!ContainsKey(simple_listeners_, kOnResponseStarted)) {
    brightray::NetworkDelegate::OnResponseStarted(request);
    return;
  }

  if (request->status().status() != net::URLRequestStatus::SUCCESS)
    return;

  HandleSimpleEvent(kOnResponseStarted, request, request->response_headers(),
                    request->was_cached());
}

void AtomNetworkDelegate::OnCompleted(net::URLRequest* request, bool started) {
  // OnCompleted may happen before other events.
  callbacks_.erase(request->identifier());

  if (request->status().status() == net::URLRequestStatus::FAILED ||
      request->status().status() == net::URLRequestStatus::CANCELED) {
    // Error event.
    OnErrorOccurred(request, started);
    return;
  } else if (request->response_headers() &&
             net::HttpResponseHeaders::IsRedirectResponseCode(
                 request->response_headers()->response_code())) {
    // Redirect event.
    brightray::NetworkDelegate::OnCompleted(request, started);
    return;
  }

  if (!ContainsKey(simple_listeners_, kOnCompleted)) {
    brightray::NetworkDelegate::OnCompleted(request, started);
    return;
  }

  HandleSimpleEvent(kOnCompleted, request, request->response_headers(),
                    request->was_cached());
}

void AtomNetworkDelegate::OnURLRequestDestroyed(net::URLRequest* request) {
  callbacks_.erase(request->identifier());
}

void AtomNetworkDelegate::OnErrorOccurred(
    net::URLRequest* request, bool started) {
  if (!ContainsKey(simple_listeners_, kOnErrorOccurred)) {
    brightray::NetworkDelegate::OnCompleted(request, started);
    return;
  }

  HandleSimpleEvent(kOnErrorOccurred, request, request->was_cached(),
                    request->status());
}

template<typename Out, typename... Args>
int AtomNetworkDelegate::HandleResponseEvent(
    ResponseEvent type,
    net::URLRequest* request,
    const net::CompletionCallback& callback,
    Out out,
    Args... args) {
  const auto& info = response_listeners_[type];
  if (!MatchesFilterCondition(request, info.url_patterns))
    return net::OK;

  scoped_ptr<base::DictionaryValue> details(new base::DictionaryValue);
  FillDetailsObject(details.get(), request, args...);

  // The |request| could be destroyed before the |callback| is called.
  callbacks_[request->identifier()] = callback;

  ResponseCallback response =
      base::Bind(&AtomNetworkDelegate::OnListenerResultInUI<Out>,
                 base::Unretained(this), request->identifier(), out);
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(RunResponseListener, info.listener, base::Passed(&details),
                 response));
  return net::ERR_IO_PENDING;
}

template<typename...Args>
void AtomNetworkDelegate::HandleSimpleEvent(
    SimpleEvent type, net::URLRequest* request, Args... args) {
  const auto& info = simple_listeners_[type];
  if (!MatchesFilterCondition(request, info.url_patterns))
    return;

  scoped_ptr<base::DictionaryValue> details(new base::DictionaryValue);
  FillDetailsObject(details.get(), request, args...);

  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE,
      base::Bind(RunSimpleListener, info.listener, base::Passed(&details)));
}

template<typename T>
void AtomNetworkDelegate::OnListenerResultInIO(
    uint64_t id, T out, scoped_ptr<base::DictionaryValue> response) {
  // The request has been destroyed.
  if (!ContainsKey(callbacks_, id))
    return;

  ReadFromResponseObject(*response.get(), out);

  bool cancel = false;
  response->GetBoolean("cancel", &cancel);
  callbacks_[id].Run(cancel ? net::ERR_BLOCKED_BY_CLIENT : net::OK);
}

template<typename T>
void AtomNetworkDelegate::OnListenerResultInUI(
    uint64_t id, T out, const base::DictionaryValue& response) {
  scoped_ptr<base::DictionaryValue> copy = response.CreateDeepCopy();
  BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      base::Bind(&AtomNetworkDelegate::OnListenerResultInIO<T>,
                 base::Unretained(this),  id, out, base::Passed(&copy)));
}

}  // namespace atom
<|endoftext|>


<commit_before>#include "ovasCDriverGenericOscilator.h"
#include "../ovasCConfigurationBuilder.h"

#include <openvibe-toolkit/ovtk_all.h>

#include <system/Time.h>

#include <cmath>

using namespace OpenViBEAcquisitionServer;
using namespace OpenViBE;
using namespace OpenViBE::Kernel;

//___________________________________________________________________//
//                                                                   //

CDriverGenericOscillator::CDriverGenericOscillator(IDriverContext& rDriverContext)
	:IDriver(rDriverContext)
	,m_pCallback(NULL)
	,m_ui32SampleCountPerSentBlock(0)
	,m_pSample(NULL)
	,m_ui32TotalSampleCount(0)
	,m_ui32StartTime(0)
{
	m_rDriverContext.getLogManager() << LogLevel_Trace << "CDriverGenericOscillator::CDriverGenericOscillator\n";

	m_oHeader.setSamplingFrequency(512);
	m_oHeader.setChannelCount(4);
}

void CDriverGenericOscillator::release(void)
{
	m_rDriverContext.getLogManager() << LogLevel_Trace << "CDriverGenericOscillator::release\n";

	delete this;
}

const char* CDriverGenericOscillator::getName(void)
{
	m_rDriverContext.getLogManager() << LogLevel_Trace << "CDriverGenericOscillator::getName\n";

	return "Generic Oscillator";
}

//___________________________________________________________________//
//                                                                   //

boolean CDriverGenericOscillator::initialize(
	const uint32 ui32SampleCountPerSentBlock,
	IDriverCallback& rCallback)
{
	m_rDriverContext.getLogManager() << LogLevel_Trace << "CDriverGenericOscillator::initialize\n";

	if(m_rDriverContext.isConnected()) { return false; }

	if(!m_oHeader.isChannelCountSet()
	 ||!m_oHeader.isSamplingFrequencySet())
	{
		return false;
	}

	m_pSample=new float32[m_oHeader.getChannelCount()*ui32SampleCountPerSentBlock];
	if(!m_pSample)
	{
		delete [] m_pSample;
		m_pSample=NULL;
		return false;
	}

	m_pCallback=&rCallback;
	m_ui32SampleCountPerSentBlock=ui32SampleCountPerSentBlock;

	return true;
}

boolean CDriverGenericOscillator::start(void)
{
	m_rDriverContext.getLogManager() << LogLevel_Trace << "CDriverGenericOscillator::start\n";

	if(!m_rDriverContext.isConnected()) { return false; }
	if(m_rDriverContext.isStarted()) { return false; }

	m_ui32TotalSampleCount=0;
	m_ui32StartTime=System::Time::getTime();

	return true;
}

boolean CDriverGenericOscillator::loop(void)
{
	m_rDriverContext.getLogManager() << LogLevel_Debug << "CDriverGenericOscillator::loop\n";

	if(!m_rDriverContext.isConnected()) { return false; }
	if(!m_rDriverContext.isStarted()) { return true; }

	uint32 l_ui32CurrentTime=System::Time::getTime();

	if(l_ui32CurrentTime-m_ui32StartTime > (1002*(m_ui32TotalSampleCount+m_ui32SampleCountPerSentBlock))/m_oHeader.getSamplingFrequency())
	{
		CStimulationSet l_oStimulationSet;
		l_oStimulationSet.setStimulationCount(1);
		l_oStimulationSet.setStimulationIdentifier(0, 0);
		l_oStimulationSet.setStimulationDate(0, 0);
		l_oStimulationSet.setStimulationDuration(0, 0);

		for(uint32 j=0; j<m_oHeader.getChannelCount(); j++)
		{
			for(uint32 i=0; i<m_ui32SampleCountPerSentBlock; i++)
			{
#if 1
				float64 l_f64Value=
					::sin(((i+m_ui32TotalSampleCount)*(j+1)*12.3)/m_oHeader.getSamplingFrequency())+
					::sin(((i+m_ui32TotalSampleCount)*(j+1)* 4.5)/m_oHeader.getSamplingFrequency())+
					::sin(((i+m_ui32TotalSampleCount)*(j+1)*67.8)/m_oHeader.getSamplingFrequency());
				m_pSample[j*m_ui32SampleCountPerSentBlock+i]=(float32)l_f64Value;
#else
				m_pSample[j*m_ui32SampleCountPerSentBlock+i]=j;
#endif
			}
		}

		m_ui32TotalSampleCount+=m_ui32SampleCountPerSentBlock;
		m_pCallback->setSamples(m_pSample);
		m_pCallback->setStimulationSet(l_oStimulationSet);
	}

	return true;
}

boolean CDriverGenericOscillator::stop(void)
{
	m_rDriverContext.getLogManager() << LogLevel_Trace << "CDriverGenericOscillator::stop\n";

	if(!m_rDriverContext.isConnected()) { return false; }
	if(!m_rDriverContext.isStarted()) { return false; }
	return true;
}

boolean CDriverGenericOscillator::uninitialize(void)
{
	m_rDriverContext.getLogManager() << LogLevel_Trace << "CDriverGenericOscillator::uninitialize\n";

	if(!m_rDriverContext.isConnected()) { return false; }
	if(m_rDriverContext.isStarted()) { return false; }

	delete [] m_pSample;
	m_pSample=NULL;
	m_pCallback=NULL;

	return true;
}

//___________________________________________________________________//
//                                                                   //

boolean CDriverGenericOscillator::isConfigurable(void)
{
	m_rDriverContext.getLogManager() << LogLevel_Trace << "CDriverGenericOscillator::isConfigurable\n";

	return true;
}

boolean CDriverGenericOscillator::configure(void)
{
	m_rDriverContext.getLogManager() << LogLevel_Trace << "CDriverGenericOscillator::configure\n";

	CConfigurationBuilder m_oConfiguration("../share/openvibe-applications/acquisition-server/interface-Generic-Oscillator.ui");
	return m_oConfiguration.configure(m_oHeader);
}
<commit_msg><commit_after>#include "ovasCDriverGenericOscilator.h"
#include "../ovasCConfigurationBuilder.h"

#include <openvibe-toolkit/ovtk_all.h>

#include <system/Time.h>

#include <cmath>

using namespace OpenViBEAcquisitionServer;
using namespace OpenViBE;
using namespace OpenViBE::Kernel;

//___________________________________________________________________//
//                                                                   //

CDriverGenericOscillator::CDriverGenericOscillator(IDriverContext& rDriverContext)
	:IDriver(rDriverContext)
	,m_pCallback(NULL)
	,m_ui32SampleCountPerSentBlock(0)
	,m_pSample(NULL)
	,m_ui32TotalSampleCount(0)
	,m_ui32StartTime(0)
{
	m_rDriverContext.getLogManager() << LogLevel_Trace << "CDriverGenericOscillator::CDriverGenericOscillator\n";

	m_oHeader.setSamplingFrequency(512);
	m_oHeader.setChannelCount(4);
}

void CDriverGenericOscillator::release(void)
{
	m_rDriverContext.getLogManager() << LogLevel_Trace << "CDriverGenericOscillator::release\n";

	delete this;
}

const char* CDriverGenericOscillator::getName(void)
{
	m_rDriverContext.getLogManager() << LogLevel_Trace << "CDriverGenericOscillator::getName\n";

	return "Generic Oscillator";
}

//___________________________________________________________________//
//                                                                   //

boolean CDriverGenericOscillator::initialize(
	const uint32 ui32SampleCountPerSentBlock,
	IDriverCallback& rCallback)
{
	m_rDriverContext.getLogManager() << LogLevel_Trace << "CDriverGenericOscillator::initialize\n";

	if(m_rDriverContext.isConnected()) { return false; }

	if(!m_oHeader.isChannelCountSet()
	 ||!m_oHeader.isSamplingFrequencySet())
	{
		return false;
	}

	m_pSample=new float32[m_oHeader.getChannelCount()*ui32SampleCountPerSentBlock];
	if(!m_pSample)
	{
		delete [] m_pSample;
		m_pSample=NULL;
		return false;
	}

	m_pCallback=&rCallback;
	m_ui32SampleCountPerSentBlock=ui32SampleCountPerSentBlock;

	return true;
}

boolean CDriverGenericOscillator::start(void)
{
	m_rDriverContext.getLogManager() << LogLevel_Trace << "CDriverGenericOscillator::start\n";

	if(!m_rDriverContext.isConnected()) { return false; }
	if(m_rDriverContext.isStarted()) { return false; }

	m_ui32TotalSampleCount=0;
	m_ui32StartTime=System::Time::getTime();

	return true;
}

boolean CDriverGenericOscillator::loop(void)
{
	m_rDriverContext.getLogManager() << LogLevel_Debug << "CDriverGenericOscillator::loop\n";

	if(!m_rDriverContext.isConnected()) { return false; }
	if(!m_rDriverContext.isStarted()) { return true; }

	uint32 l_ui32CurrentTime=System::Time::getTime();

	if(l_ui32CurrentTime-m_ui32StartTime > (1000*(m_ui32TotalSampleCount+m_ui32SampleCountPerSentBlock))/m_oHeader.getSamplingFrequency())
	{
		CStimulationSet l_oStimulationSet;
		l_oStimulationSet.setStimulationCount(1);
		l_oStimulationSet.setStimulationIdentifier(0, 0);
		l_oStimulationSet.setStimulationDate(0, 0);
		l_oStimulationSet.setStimulationDuration(0, 0);

		for(uint32 j=0; j<m_oHeader.getChannelCount(); j++)
		{
			for(uint32 i=0; i<m_ui32SampleCountPerSentBlock; i++)
			{
#if 1
				float64 l_f64Value=
					::sin(((i+m_ui32TotalSampleCount)*(j+1)*12.3)/m_oHeader.getSamplingFrequency())+
					::sin(((i+m_ui32TotalSampleCount)*(j+1)* 4.5)/m_oHeader.getSamplingFrequency())+
					::sin(((i+m_ui32TotalSampleCount)*(j+1)*67.8)/m_oHeader.getSamplingFrequency());
				m_pSample[j*m_ui32SampleCountPerSentBlock+i]=(float32)l_f64Value;
#else
				m_pSample[j*m_ui32SampleCountPerSentBlock+i]=j;
#endif
			}
		}

		m_ui32TotalSampleCount+=m_ui32SampleCountPerSentBlock;
		m_pCallback->setSamples(m_pSample);
		m_pCallback->setStimulationSet(l_oStimulationSet);
	}

	return true;
}

boolean CDriverGenericOscillator::stop(void)
{
	m_rDriverContext.getLogManager() << LogLevel_Trace << "CDriverGenericOscillator::stop\n";

	if(!m_rDriverContext.isConnected()) { return false; }
	if(!m_rDriverContext.isStarted()) { return false; }
	return true;
}

boolean CDriverGenericOscillator::uninitialize(void)
{
	m_rDriverContext.getLogManager() << LogLevel_Trace << "CDriverGenericOscillator::uninitialize\n";

	if(!m_rDriverContext.isConnected()) { return false; }
	if(m_rDriverContext.isStarted()) { return false; }

	delete [] m_pSample;
	m_pSample=NULL;
	m_pCallback=NULL;

	return true;
}

//___________________________________________________________________//
//                                                                   //

boolean CDriverGenericOscillator::isConfigurable(void)
{
	m_rDriverContext.getLogManager() << LogLevel_Trace << "CDriverGenericOscillator::isConfigurable\n";

	return true;
}

boolean CDriverGenericOscillator::configure(void)
{
	m_rDriverContext.getLogManager() << LogLevel_Trace << "CDriverGenericOscillator::configure\n";

	CConfigurationBuilder m_oConfiguration("../share/openvibe-applications/acquisition-server/interface-Generic-Oscillator.ui");
	return m_oConfiguration.configure(m_oHeader);
}
<|endoftext|>


<commit_before>#include "render/RenderTarget.h"

#include  <GL/glew.h>

using fei::RenderTarget;

RenderTarget::RenderTarget()
: _renderbuffer(0),
  _framebuffer(0),
  _width(0),
  _height(0),
  _isBind(false)
{
}

RenderTarget::~RenderTarget()
{
	deleteBuffers();
}

RenderTarget::RenderTarget(const fei::Vec2& size)
{
	setSize(size);
}

RenderTarget::RenderTarget(GLsizei width, GLsizei height)
{
	setSize(width, height);
}

fei::Texture* RenderTarget::getTexture()
{
	return &_texture;
}

void RenderTarget::setSize(const fei::Vec2& size, Texture::Format format)
{
	setSize(static_cast<GLsizei>(size.x), static_cast<GLsizei>(size.y), format);
}

void RenderTarget::setSize(GLsizei width, GLsizei height, fei::Texture::Format format)
{
	if (width == 0 || height == 0) {
		return;
	}
	if (width != _width || height != _height) {
		_width = width;
		_height = height;
		_texture.load(nullptr, width, height, format);

		genBuffers();

		glBindRenderbuffer(GL_RENDERBUFFER, _renderbuffer);
		bind();
		bindColorAttachment(getTexture(), 0);
		glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, width, height);

		glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _renderbuffer);
		unbind();
		glBindRenderbuffer(GL_RENDERBUFFER, 0);
	}
}

void RenderTarget::bindColorAttachment(fei::Texture* texture, int attachIndex)
{
	GLuint texId = 0;
	if (texture != nullptr) {
		texId = texture->getId();
	}
	if (isBind()) {
		glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + attachIndex, GL_TEXTURE_2D, texId, 0);
	} else {
		bind();
		glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + attachIndex, GL_TEXTURE_2D, texId, 0);
		unbind();
	}
}

void RenderTarget::bind()
{
	glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _framebuffer);
	_isBind = true;
}

void RenderTarget::unbind()
{
	glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
	_isBind = false;
}

bool RenderTarget::isBind()
{
	return _isBind;
}

void RenderTarget::genBuffers()
{
	if (_renderbuffer == 0) {
		glGenRenderbuffers(1, &_renderbuffer);
	}
	if (_framebuffer == 0) {
		glGenFramebuffers(1, &_framebuffer);
	}
}

void RenderTarget::deleteBuffers()
{
	if (isBind()) {
		unbind();
	}
	if (_framebuffer != 0) {
		glDeleteFramebuffers(1, &_framebuffer);
		_framebuffer = 0;
	}
	if (_renderbuffer != 0) {
		glDeleteRenderbuffers(1, &_renderbuffer);
		_renderbuffer = 0;
	}
}
<commit_msg>fix namespace<commit_after>#include "render/RenderTarget.h"

#include  <GL/glew.h>

using fei::RenderTarget;

RenderTarget::RenderTarget()
: _renderbuffer(0),
  _framebuffer(0),
  _width(0),
  _height(0),
  _isBind(false)
{
}

RenderTarget::~RenderTarget()
{
	deleteBuffers();
}

RenderTarget::RenderTarget(const fei::Vec2& size)
{
	setSize(size);
}

RenderTarget::RenderTarget(GLsizei width, GLsizei height)
{
	setSize(width, height);
}

fei::Texture* RenderTarget::getTexture()
{
	return &_texture;
}

void RenderTarget::setSize(const fei::Vec2& size, fei::Texture::Format format)
{
	setSize(static_cast<GLsizei>(size.x), static_cast<GLsizei>(size.y), format);
}

void RenderTarget::setSize(GLsizei width, GLsizei height, fei::Texture::Format format)
{
	if (width == 0 || height == 0) {
		return;
	}
	if (width != _width || height != _height) {
		_width = width;
		_height = height;
		_texture.load(nullptr, width, height, format);

		genBuffers();

		glBindRenderbuffer(GL_RENDERBUFFER, _renderbuffer);
		bind();
		bindColorAttachment(getTexture(), 0);
		glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, width, height);

		glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _renderbuffer);
		unbind();
		glBindRenderbuffer(GL_RENDERBUFFER, 0);
	}
}

void RenderTarget::bindColorAttachment(fei::Texture* texture, int attachIndex)
{
	GLuint texId = 0;
	if (texture != nullptr) {
		texId = texture->getId();
	}
	if (isBind()) {
		glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + attachIndex, GL_TEXTURE_2D, texId, 0);
	} else {
		bind();
		glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + attachIndex, GL_TEXTURE_2D, texId, 0);
		unbind();
	}
}

void RenderTarget::bind()
{
	glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _framebuffer);
	_isBind = true;
}

void RenderTarget::unbind()
{
	glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
	_isBind = false;
}

bool RenderTarget::isBind()
{
	return _isBind;
}

void RenderTarget::genBuffers()
{
	if (_renderbuffer == 0) {
		glGenRenderbuffers(1, &_renderbuffer);
	}
	if (_framebuffer == 0) {
		glGenFramebuffers(1, &_framebuffer);
	}
}

void RenderTarget::deleteBuffers()
{
	if (isBind()) {
		unbind();
	}
	if (_framebuffer != 0) {
		glDeleteFramebuffers(1, &_framebuffer);
		_framebuffer = 0;
	}
	if (_renderbuffer != 0) {
		glDeleteRenderbuffers(1, &_renderbuffer);
		_renderbuffer = 0;
	}
}
<|endoftext|>


<commit_before>/* individual.hpp - CS 472 Project #2: Genetic Programming
 * Copyright 2014 Andrew Schwartzmeyer
 *
 * Header file for interface of an individual representing a
 * gentically generated solution function
 */

#ifndef _INDIVIDUAL_H_
#define _INDIVIDUAL_H_

#include <string>
#include <vector>
#include "../options/options.hpp"

namespace individual
{
  // Represents a tree's size in terms of internal and leaf nodes.
  struct Size
  {
    unsigned int internals;
    unsigned int leaves;
    unsigned int depth;
    Size();
  };

  // Available methods for tree creation.
  enum class Method {grow, full};

  // List of valid functions for an expression.
  enum class Function {nil, prog2, prog3, iffoodahead, left, right, forward};

  // Implements a recursive parse tree representing an expression.
  class Node
  {
  public:
    Node();
    Node(const Method&, const unsigned int&);
    std::string print() const;
    std::string represent() const;
    void evaluate(options::Map&) const;
    const Size size() const;
    Node& visit(const Size&, Size&);
    void mutate_tree(const float&);

  private:
    Function function;
    unsigned int arity;
    std::vector<Node> children;

    void mutate_self();
  };

  class Individual
  {
  public:
    Individual();
    Individual(const unsigned int, const float&, options::Map map);

    std::string print() const;
    std::string print_formula() const;

    unsigned int get_internals() const;
    unsigned int get_leaves() const;
    unsigned int get_total() const;
    unsigned int get_depth() const;
    unsigned int get_score() const;
    float get_fitness() const;
    float get_adjusted() const;

    Node& operator[](const Size&);
    void mutate(const float&);
    std::string evaluate(options::Map, const float& penalty = 0,
			 const bool& print = false);
    friend void crossover(const float&, Individual&, Individual&);

  private:
    Node root;
    Size size;
    unsigned int score;
    float fitness;
    float adjusted;

    enum class Type {leaf, internal};
    Size get_node(const Type&);
  };
}

#endif /* _INDIVIDUAL_H_ */
<commit_msg>Making Individual friend of Node<commit_after>/* individual.hpp - CS 472 Project #2: Genetic Programming
 * Copyright 2014 Andrew Schwartzmeyer
 *
 * Header file for interface of an individual representing a
 * gentically generated solution function
 */

#ifndef _INDIVIDUAL_H_
#define _INDIVIDUAL_H_

#include <string>
#include <vector>
#include "../options/options.hpp"

namespace individual
{
  // Represents a tree's size in terms of internal and leaf nodes.
  struct Size
  {
    unsigned int internals;
    unsigned int leaves;
    unsigned int depth;
    Size();
  };

  // Available methods for tree creation.
  enum class Method {grow, full};

  // List of valid functions for an expression.
  enum class Function {nil, prog2, prog3, iffoodahead, left, right, forward};

  // Implements a recursive parse tree representing an expression.
  class Node
  {
    friend class Individual;

  public:
    Node();
    Node(const Method&, const unsigned int&);

  protected:
    std::string print() const;
    std::string represent() const;
    void evaluate(options::Map&) const;
    const Size size() const;
    Node& visit(const Size&, Size&);
    void mutate();
    std::vector<Node> children;
    Function function;
    unsigned int arity;
  };

  class Individual
  {
  public:
    Individual();
    Individual(const unsigned int, const float&, options::Map map);

    std::string print() const;
    std::string print_formula() const;

    unsigned int get_internals() const;
    unsigned int get_leaves() const;
    unsigned int get_total() const;
    unsigned int get_depth() const;
    unsigned int get_score() const;
    float get_fitness() const;
    float get_adjusted() const;

    Node& operator[](const Size&);
    void mutate(const float&);
    std::string evaluate(options::Map, const float& penalty = 0,
			 const bool& print = false);
    friend void crossover(const float&, Individual&, Individual&);

  private:
    Node root;
    Size size;
    unsigned int score;
    float fitness;
    float adjusted;

    enum class Type {leaf, internal};
    Size get_node(const Type&);
  };
}

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


<commit_before>#include <ccspec/matcher.h>
#include <iostream>
using namespace std;

namespace ccspec {

// Public methods.

template <typename U>
template <typename V>
void Eq<U>::match(V expected_value) {
    if (expected_value != this->value())
        throw 1;
}

// Private methods.

template<typename U>
Eq<U>::Eq(U value) : Matcher<Eq<U>, U>(value) {}

// Friend methods.

template<typename U>
Eq<U> eq(U value) {
    return Eq<U>(value);
}

} // namespace ccspec
<commit_msg>Remove debug code<commit_after>#include <ccspec/matcher.h>

namespace ccspec {

// Public methods.

template <typename U>
template <typename V>
void Eq<U>::match(V expected_value) {
    if (expected_value != this->value())
        throw 1;
}

// Private methods.

template<typename U>
Eq<U>::Eq(U value) : Matcher<Eq<U>, U>(value) {}

// Friend methods.

template<typename U>
Eq<U> eq(U value) {
    return Eq<U>(value);
}

} // namespace ccspec
<|endoftext|>


<commit_before>// ----------------------------------------------------
//
// AIMP DotNet SDK
//
// Copyright (c) 2014 - 2017 Evgeniy Bogdan
// https://github.com/martin211/aimp_dotnet
//
// Mail: mail4evgeniy@gmail.com
//
// ----------------------------------------------------

#include "Stdafx.h"
#include "AimpMenuItem.h"
#include "../Action/AimpActionEvent.h"
#include "../Action/AimpAction.h"

using namespace AIMP::SDK;
using namespace System;
using namespace System::Runtime::InteropServices;

AimpMenuItem::AimpMenuItem(IAIMPMenuItem *menuItem) : AimpObject(menuItem)
{}

AimpMenuItem::~AimpMenuItem()
{
    _onExecuteHandler = nullptr;
    _onExecuteHandler = nullptr;
    _showHandler.Free();
    _executeHandler.Free();
}

String ^AimpMenuItem::Custom::get()
{
    return String::Empty;
}

void AimpMenuItem::Custom::set(String ^value)
{}

IAimpAction ^AimpMenuItem::Action::get()
{
    IAIMPAction *action;
    if (PropertyListExtension::GetObject(InternalAimpObject, AIMP_MENUITEM_PROPID_ACTION, IID_IAIMPAction, (void**)&action) == AimpActionResult::Ok)
    {
        return gcnew AimpAction(action);
    }

    return nullptr;
}

void AimpMenuItem::Action::set(IAimpAction ^value)
{
    PropertyListExtension::SetObject(InternalAimpObject, AIMP_MENUITEM_PROPID_ACTION, ((AimpAction^)value)->InternalAimpObject);
}

String ^AimpMenuItem::Id::get()
{
    String^ str = nullptr;
    PropertyListExtension::GetString(InternalAimpObject, AIMP_MENUITEM_PROPID_ID, *&str);
    return str;
}

void AimpMenuItem::Id::set(String ^value)
{
    _id = value;
    PropertyListExtension::SetString(InternalAimpObject, AIMP_MENUITEM_PROPID_ID, value);
}

String ^AimpMenuItem::Name::get()
{
    String^ str = nullptr;
    PropertyListExtension::GetString(InternalAimpObject, AIMP_MENUITEM_PROPID_NAME, *&str);
    return str;
}

void AimpMenuItem::Name::set(String ^value)
{
    PropertyListExtension::SetString(InternalAimpObject, AIMP_MENUITEM_PROPID_NAME, value);
}

bool AimpMenuItem::Checked::get()
{
    bool val = false;
    PropertyListExtension::GetBool(InternalAimpObject, AIMP_MENUITEM_PROPID_CHECKED, val);
    return val;
}

void AimpMenuItem::Checked::set(bool value)
{
    PropertyListExtension::SetBool(InternalAimpObject, AIMP_MENUITEM_PROPID_CHECKED, value);
}

bool AimpMenuItem::Enabled::get()
{
    bool val = false;
    PropertyListExtension::GetBool(InternalAimpObject, AIMP_MENUITEM_PROPID_ENABLED, val);
    return val;
}

void AimpMenuItem::Enabled::set(bool value)
{
    PropertyListExtension::SetBool(InternalAimpObject, AIMP_MENUITEM_PROPID_ENABLED, value);
}

bool AimpMenuItem::Visible::get()
{
    bool val = false;
    PropertyListExtension::GetBool(InternalAimpObject, AIMP_MENUITEM_PROPID_VISIBLE, val);
    return val;
}

void AimpMenuItem::Visible::set(bool value)
{
    PropertyListExtension::SetBool(InternalAimpObject, AIMP_MENUITEM_PROPID_VISIBLE, value);
}

Bitmap ^AimpMenuItem::Glyph::get()
{
    return nullptr;
}

void AimpMenuItem::Glyph::set(Bitmap ^value)
{
    if (value != nullptr)
    {
        IAIMPImage *image = AimpConverter::ToAimpImage(value);
        InternalAimpObject->SetValueAsObject(AIMP_MENUITEM_PROPID_GLYPH, image);
        image->Release();
    }
}

IAimpMenuItem ^AimpMenuItem::Parent::get()
{
    IAIMPMenuItem *item;
    InternalAimpObject->GetValueAsObject(AIMP_MENUITEM_PROPID_PARENT, IID_IAIMPMenuItem, (void**)&item);
    AimpMenuItem ^parentIttem = gcnew AimpMenuItem(item);
    item->Release();

    return parentIttem;
}

void AimpMenuItem::Parent::set(IAimpMenuItem ^value)
{
    InternalAimpObject->SetValueAsObject(AIMP_MENUITEM_PROPID_PARENT, ((AimpMenuItem^)value)->InternalAimpObject);
}

AimpMenuItemStyle AimpMenuItem::Style::get()
{
    int val = 0;
    PropertyListExtension::GetInt32(InternalAimpObject, AIMP_MENUITEM_PROPID_STYLE, val);
    return (AimpMenuItemStyle)val;
}

void AimpMenuItem::Style::set(AimpMenuItemStyle value)
{
    PropertyListExtension::SetInt32(InternalAimpObject, AIMP_MENUITEM_PROPID_STYLE, (int)value);
}

bool AimpMenuItem::IsDefault::get()
{
    bool val = false;
    PropertyListExtension::GetBool(InternalAimpObject, AIMP_MENUITEM_PROPID_DEFAULT, val);
    return val;
}

void AimpMenuItem::IsDefault::set(bool value)
{
    PropertyListExtension::SetBool(InternalAimpObject, AIMP_MENUITEM_PROPID_DEFAULT, value);
}

int AimpMenuItem::Shortcut::get()
{
    int val = 0;
    PropertyListExtension:: GetInt32(InternalAimpObject, AIMP_MENUITEM_PROPID_SHORTCUT, val);
    return val;
}

void AimpMenuItem::Shortcut::set(int val)
{
    PropertyListExtension::SetInt32(InternalAimpObject, AIMP_MENUITEM_PROPID_SHORTCUT, val);
}

void AimpMenuItem::OnExecute::add(EventHandler ^onEvent)
{
    if (_onExecuteHandler == nullptr)
    {
        AIMP::SDK::AimpActionEventDelegate ^fp = gcnew AIMP::SDK::AimpActionEventDelegate(this->Execute);
        _executeHandler = GCHandle::Alloc(fp);
        IntPtr ip = Marshal::GetFunctionPointerForDelegate(fp);
        AIMP::SDK::AimpActionEventCallback callback = static_cast<AIMP::SDK::AimpActionEventCallback>(ip.ToPointer());
        _onExecuteEvent = new AimpActionEvent(this, callback);
        GC::Collect();
        _onExecuteHandler = (EventHandler^)Delegate::Combine(_onExecuteHandler, onEvent);
        InternalAimpObject->SetValueAsObject(AIMP_MENUITEM_PROPID_EVENT, _onExecuteEvent);
    }
}

void AimpMenuItem::OnExecute::remove(EventHandler ^onEvent)
{
    if (_onExecuteHandler != nullptr)
    {
        _onExecuteHandler = (EventHandler^)Delegate::Remove(_onExecuteHandler, onEvent);
        _onExecuteEvent->Release();
        _onExecuteEvent = NULL;
        delete _onExecuteEvent;
        _executeHandler.Free();
    }
}

void AimpMenuItem::OnExecute::raise(Object ^sender, EventArgs ^args)
{
    if (_onExecuteHandler != nullptr)
    {
        _onExecuteHandler(sender, args);
    }
}

void AimpMenuItem::OnShow::add(EventHandler ^onEvent)
{
    if (_onShowHandler == nullptr)
    {
        AIMP::SDK::AimpActionEventDelegate ^fp = gcnew AIMP::SDK::AimpActionEventDelegate(this->Show);
        _showHandler = GCHandle::Alloc(fp);
        IntPtr ip = Marshal::GetFunctionPointerForDelegate(fp);
        AIMP::SDK::AimpActionEventCallback callback = static_cast<AIMP::SDK::AimpActionEventCallback>(ip.ToPointer());
        _onShowEvent = new AimpActionEvent(this, callback);
        GC::Collect();
        _onShowHandler = (EventHandler^)Delegate::Combine(_onShowHandler, onEvent);
        InternalAimpObject->SetValueAsObject(AIMP_MENUITEM_PROPID_EVENT_ONSHOW, _onShowEvent);
    }
}

void AimpMenuItem::OnShow::remove(EventHandler ^onEvent)
{
    if (_onShowHandler != nullptr)
    {
        _onShowHandler = (EventHandler^)Delegate::Remove(_onShowHandler, onEvent);
        _onShowEvent->Release();
        _onShowEvent = NULL;
        delete _onShowEvent;
        _showHandler.Free();
    }
}

void AimpMenuItem::OnShow::raise(Object ^sender, EventArgs ^args)
{
    if (_onShowHandler != nullptr)
    {
        _onShowHandler(sender, args);
    }
}
<commit_msg>Fix MenuItem destructor<commit_after>// ----------------------------------------------------
//
// AIMP DotNet SDK
//
// Copyright (c) 2014 - 2017 Evgeniy Bogdan
// https://github.com/martin211/aimp_dotnet
//
// Mail: mail4evgeniy@gmail.com
//
// ----------------------------------------------------

#include "Stdafx.h"
#include "AimpMenuItem.h"
#include "../Action/AimpActionEvent.h"
#include "../Action/AimpAction.h"

using namespace AIMP::SDK;
using namespace System;
using namespace System::Runtime::InteropServices;

AimpMenuItem::AimpMenuItem(IAIMPMenuItem *menuItem) : AimpObject(menuItem)
{}

AimpMenuItem::~AimpMenuItem()
{
    _onExecuteHandler = nullptr;
    _onExecuteEvent = nullptr;
    _showHandler.Free();
    _executeHandler.Free();
}

String ^AimpMenuItem::Custom::get()
{
    return String::Empty;
}

void AimpMenuItem::Custom::set(String ^value)
{}

IAimpAction ^AimpMenuItem::Action::get()
{
    IAIMPAction *action;
    if (PropertyListExtension::GetObject(InternalAimpObject, AIMP_MENUITEM_PROPID_ACTION, IID_IAIMPAction, (void**)&action) == AimpActionResult::Ok)
    {
        return gcnew AimpAction(action);
    }

    return nullptr;
}

void AimpMenuItem::Action::set(IAimpAction ^value)
{
    PropertyListExtension::SetObject(InternalAimpObject, AIMP_MENUITEM_PROPID_ACTION, ((AimpAction^)value)->InternalAimpObject);
}

String ^AimpMenuItem::Id::get()
{
    String^ str = nullptr;
    PropertyListExtension::GetString(InternalAimpObject, AIMP_MENUITEM_PROPID_ID, *&str);
    return str;
}

void AimpMenuItem::Id::set(String ^value)
{
    _id = value;
    PropertyListExtension::SetString(InternalAimpObject, AIMP_MENUITEM_PROPID_ID, value);
}

String ^AimpMenuItem::Name::get()
{
    String^ str = nullptr;
    PropertyListExtension::GetString(InternalAimpObject, AIMP_MENUITEM_PROPID_NAME, *&str);
    return str;
}

void AimpMenuItem::Name::set(String ^value)
{
    PropertyListExtension::SetString(InternalAimpObject, AIMP_MENUITEM_PROPID_NAME, value);
}

bool AimpMenuItem::Checked::get()
{
    bool val = false;
    PropertyListExtension::GetBool(InternalAimpObject, AIMP_MENUITEM_PROPID_CHECKED, val);
    return val;
}

void AimpMenuItem::Checked::set(bool value)
{
    PropertyListExtension::SetBool(InternalAimpObject, AIMP_MENUITEM_PROPID_CHECKED, value);
}

bool AimpMenuItem::Enabled::get()
{
    bool val = false;
    PropertyListExtension::GetBool(InternalAimpObject, AIMP_MENUITEM_PROPID_ENABLED, val);
    return val;
}

void AimpMenuItem::Enabled::set(bool value)
{
    PropertyListExtension::SetBool(InternalAimpObject, AIMP_MENUITEM_PROPID_ENABLED, value);
}

bool AimpMenuItem::Visible::get()
{
    bool val = false;
    PropertyListExtension::GetBool(InternalAimpObject, AIMP_MENUITEM_PROPID_VISIBLE, val);
    return val;
}

void AimpMenuItem::Visible::set(bool value)
{
    PropertyListExtension::SetBool(InternalAimpObject, AIMP_MENUITEM_PROPID_VISIBLE, value);
}

Bitmap ^AimpMenuItem::Glyph::get()
{
    return nullptr;
}

void AimpMenuItem::Glyph::set(Bitmap ^value)
{
    if (value != nullptr)
    {
        IAIMPImage *image = AimpConverter::ToAimpImage(value);
        InternalAimpObject->SetValueAsObject(AIMP_MENUITEM_PROPID_GLYPH, image);
        image->Release();
    }
}

IAimpMenuItem ^AimpMenuItem::Parent::get()
{
    IAIMPMenuItem *item;
    InternalAimpObject->GetValueAsObject(AIMP_MENUITEM_PROPID_PARENT, IID_IAIMPMenuItem, (void**)&item);
    AimpMenuItem ^parentIttem = gcnew AimpMenuItem(item);
    item->Release();

    return parentIttem;
}

void AimpMenuItem::Parent::set(IAimpMenuItem ^value)
{
    InternalAimpObject->SetValueAsObject(AIMP_MENUITEM_PROPID_PARENT, ((AimpMenuItem^)value)->InternalAimpObject);
}

AimpMenuItemStyle AimpMenuItem::Style::get()
{
    int val = 0;
    PropertyListExtension::GetInt32(InternalAimpObject, AIMP_MENUITEM_PROPID_STYLE, val);
    return (AimpMenuItemStyle)val;
}

void AimpMenuItem::Style::set(AimpMenuItemStyle value)
{
    PropertyListExtension::SetInt32(InternalAimpObject, AIMP_MENUITEM_PROPID_STYLE, (int)value);
}

bool AimpMenuItem::IsDefault::get()
{
    bool val = false;
    PropertyListExtension::GetBool(InternalAimpObject, AIMP_MENUITEM_PROPID_DEFAULT, val);
    return val;
}

void AimpMenuItem::IsDefault::set(bool value)
{
    PropertyListExtension::SetBool(InternalAimpObject, AIMP_MENUITEM_PROPID_DEFAULT, value);
}

int AimpMenuItem::Shortcut::get()
{
    int val = 0;
    PropertyListExtension:: GetInt32(InternalAimpObject, AIMP_MENUITEM_PROPID_SHORTCUT, val);
    return val;
}

void AimpMenuItem::Shortcut::set(int val)
{
    PropertyListExtension::SetInt32(InternalAimpObject, AIMP_MENUITEM_PROPID_SHORTCUT, val);
}

void AimpMenuItem::OnExecute::add(EventHandler ^onEvent)
{
    if (_onExecuteHandler == nullptr)
    {
        AIMP::SDK::AimpActionEventDelegate ^fp = gcnew AIMP::SDK::AimpActionEventDelegate(this->Execute);
        _executeHandler = GCHandle::Alloc(fp);
        IntPtr ip = Marshal::GetFunctionPointerForDelegate(fp);
        AIMP::SDK::AimpActionEventCallback callback = static_cast<AIMP::SDK::AimpActionEventCallback>(ip.ToPointer());
        _onExecuteEvent = new AimpActionEvent(this, callback);
        GC::Collect();
        _onExecuteHandler = (EventHandler^)Delegate::Combine(_onExecuteHandler, onEvent);
        InternalAimpObject->SetValueAsObject(AIMP_MENUITEM_PROPID_EVENT, _onExecuteEvent);
    }
}

void AimpMenuItem::OnExecute::remove(EventHandler ^onEvent)
{
    if (_onExecuteHandler != nullptr)
    {
        _onExecuteHandler = (EventHandler^)Delegate::Remove(_onExecuteHandler, onEvent);
        _onExecuteEvent->Release();
        _onExecuteEvent = NULL;
        delete _onExecuteEvent;
        _executeHandler.Free();
    }
}

void AimpMenuItem::OnExecute::raise(Object ^sender, EventArgs ^args)
{
    if (_onExecuteHandler != nullptr)
    {
        _onExecuteHandler(sender, args);
    }
}

void AimpMenuItem::OnShow::add(EventHandler ^onEvent)
{
    if (_onShowHandler == nullptr)
    {
        AIMP::SDK::AimpActionEventDelegate ^fp = gcnew AIMP::SDK::AimpActionEventDelegate(this->Show);
        _showHandler = GCHandle::Alloc(fp);
        IntPtr ip = Marshal::GetFunctionPointerForDelegate(fp);
        AIMP::SDK::AimpActionEventCallback callback = static_cast<AIMP::SDK::AimpActionEventCallback>(ip.ToPointer());
        _onShowEvent = new AimpActionEvent(this, callback);
        GC::Collect();
        _onShowHandler = (EventHandler^)Delegate::Combine(_onShowHandler, onEvent);
        InternalAimpObject->SetValueAsObject(AIMP_MENUITEM_PROPID_EVENT_ONSHOW, _onShowEvent);
    }
}

void AimpMenuItem::OnShow::remove(EventHandler ^onEvent)
{
    if (_onShowHandler != nullptr)
    {
        _onShowHandler = (EventHandler^)Delegate::Remove(_onShowHandler, onEvent);
        _onShowEvent->Release();
        _onShowEvent = NULL;
        delete _onShowEvent;
        _showHandler.Free();
    }
}

void AimpMenuItem::OnShow::raise(Object ^sender, EventArgs ^args)
{
    if (_onShowHandler != nullptr)
    {
        _onShowHandler(sender, args);
    }
}
<|endoftext|>


<commit_before>#ifndef CORE8_IOCONNECTOR_HPP
#define CORE8_IOCONNECTOR_HPP

#include <array>

#include "Chip8.hpp"

namespace Core8 {

class IOConnector {
  public:
    virtual void drawScreen(const std::array<Chip8::BYTE, Chip8::SCREEN_SIZE>& frame) = 0;

    virtual bool isKeyPressed(const Chip8::BYTE key) const = 0;
};

} // namespace Core8

#endif
<commit_msg>Fix typo in class name<commit_after>#ifndef CORE8_IOCONNECTOR_HPP
#define CORE8_IOCONNECTOR_HPP

#include <array>

#include "Chip8.hpp"

namespace Core8 {

class IoConnector {
  public:
    virtual void drawScreen(const std::array<Chip8::BYTE, Chip8::DISPLAY_SIZE>& frame) = 0;

    virtual bool isKeyPressed(const Chip8::BYTE key) const = 0;
};

} // namespace Core8

#endif
<|endoftext|>