From fd43b8917cdc74f168cd773129dbc198a5a2c87a Mon Sep 17 00:00:00 2001
From: Robert <Robert-Altner@t-online.de>
Date: Mon, 15 Jun 2020 21:49:10 +0200
Subject: [PATCH] Added events

---
 src/example/main.cpp | 9 ++++++++-
 src/sdlf/Window.cpp  | 7 +++++++
 src/sdlf/Window.hpp  | 6 ++++++
 3 files changed, 21 insertions(+), 1 deletion(-)

diff --git a/src/example/main.cpp b/src/example/main.cpp
index 72f510f..9bcf5a4 100644
--- a/src/example/main.cpp
+++ b/src/example/main.cpp
@@ -4,6 +4,12 @@
 
 using namespace sf;
 
+int Callback(void* userdata, SDL_Event* event)
+{
+	std::cout << event->type << std::endl;
+	return 0;
+}
+
 class MyWindow : public IWindow
 {
 public:
@@ -27,7 +33,7 @@ private:
 
 	virtual bool OnUpdate(double frametime) override
 	{
-		printf("Frame took %f seconds\n", frametime);
+		SDL_SetWindowTitle(m_pWindow, std::to_string(frametime).c_str());
 		return true;
 	}
 };
@@ -37,6 +43,7 @@ int main(int argc, char* argv[])
 	SDL_Init(SDL_INIT_VIDEO);
 
 	MyWindow window;
+	window.AddEventCallback(Callback, nullptr);
 
 	try
 	{
diff --git a/src/sdlf/Window.cpp b/src/sdlf/Window.cpp
index b016681..dd7feeb 100644
--- a/src/sdlf/Window.cpp
+++ b/src/sdlf/Window.cpp
@@ -62,6 +62,11 @@ namespace sf
 
 	}
 
+	void IWindow::AddEventCallback(EventCallback callback, void* userdata)
+	{
+		SDL_AddEventWatch(*(callback.target<SDL_EventFilter>()), userdata);
+	}
+
 	IWindow::IWindow(Vector2u size, Vector2i position, std::string title,
 		Uint32 flags /*= SDL_WINDOW_RESIZABLE*/) :
 		m_pWindow(nullptr), m_pRenderer(nullptr), m_oEvent(),
@@ -83,6 +88,8 @@ namespace sf
 		{
 			while (SDL_PollEvent(&m_oEvent))
 			{
+				OnEvent(m_oEvent);
+
 				if (m_oEvent.type == SDL_QUIT)
 				{
 					m_atomWindowOpen = false;
diff --git a/src/sdlf/Window.hpp b/src/sdlf/Window.hpp
index f7ad161..ea98a73 100644
--- a/src/sdlf/Window.hpp
+++ b/src/sdlf/Window.hpp
@@ -3,6 +3,7 @@
 #include <string>
 #include <thread>
 #include <atomic>
+#include <functional>
 
 #include "SDL.h"
 #include "util/Vector2.hpp"
@@ -11,6 +12,8 @@
 
 namespace sf
 {
+	typedef std::function<int(void*, SDL_Event*)> EventCallback;
+
 	class IWindow
 	{
 	public:
@@ -21,11 +24,14 @@ namespace sf
 
 		bool IsOpen() { return m_atomWindowOpen; }
 
+		void AddEventCallback(EventCallback callback, void* userdata);
+
 	protected:
 		IWindow(Vector2u size, Vector2i position, std::string title, Uint32 flags = SDL_WINDOW_RESIZABLE);
 
 		virtual bool OnCreate() { return true; }
 		virtual void OnClose() { }
+		virtual void OnEvent(const SDL_Event& event) { }
 		virtual bool OnUpdate(double frametime) { return true; }
 
 	protected: