From 414fbf6404e9ea137fe17df9a171d78bf552796c Mon Sep 17 00:00:00 2001 From: xdrm-brackets Date: Tue, 4 Feb 2020 21:08:17 +0100 Subject: [PATCH] create proper handler interface for xController : xEventHandler --- xSDL/xController.cpp | 19 +++++++------------ xSDL/xController.h | 13 ++++++------- xSDL/xEventHandler.cpp | 1 + xSDL/xEventHandler.h | 16 ++++++++++++++++ 4 files changed, 30 insertions(+), 19 deletions(-) create mode 100644 xSDL/xEventHandler.cpp create mode 100644 xSDL/xEventHandler.h diff --git a/xSDL/xController.cpp b/xSDL/xController.cpp index 1f83cd0..c2c5e07 100644 --- a/xSDL/xController.cpp +++ b/xSDL/xController.cpp @@ -12,29 +12,24 @@ xController::~xController(){ void xController::handleEvent(SDL_Event* event){ _mutex.lock(); - map::iterator found = _handlers.find( (SDL_EventType) event->type ); - - // ignore no handler found - if( found == _handlers.end() ){ - _mutex.unlock(); - return; + for( set::iterator it = _handlers.begin() ; it != _handlers.end() ; it++ ){ + xEventHandler* handler = (*it); + handler->handle(event); } - (*found->second)(event); - _mutex.unlock(); } // bind a new handler -void xController::attachEvent(SDL_EventType t, EventHandlerArg){ +void xController::attachEvent(xEventHandler* handler){ _mutex.lock(); - _handlers[ t ] = handler; + _handlers.insert(handler); _mutex.unlock(); } // removes an existing handler -void xController::detachEvent(SDL_EventType t){ +void xController::detachEvent(xEventHandler* handler){ _mutex.lock(); - _handlers.erase(t); + _handlers.erase(handler); _mutex.unlock(); } \ No newline at end of file diff --git a/xSDL/xController.h b/xSDL/xController.h index 56d8fbd..3431f92 100644 --- a/xSDL/xController.h +++ b/xSDL/xController.h @@ -3,11 +3,10 @@ #include "SDL.h" #include - #include - using namespace std; + #include + #include "xEventHandler.h" - #define EventHandlerArg void(* handler)(SDL_Event*) - #define EventHandler void(*)(SDL_Event*) + using namespace std; class xController{ @@ -19,12 +18,12 @@ void handleEvent(SDL_Event* event); // manage handlers - void attachEvent(SDL_EventType t, EventHandlerArg); - void detachEvent(SDL_EventType t); + void attachEvent(xEventHandler* handler); + void detachEvent(xEventHandler* handler); private: // event handlers - map _handlers; + set _handlers; // thread safety mutex _mutex; diff --git a/xSDL/xEventHandler.cpp b/xSDL/xEventHandler.cpp new file mode 100644 index 0000000..1e8fc26 --- /dev/null +++ b/xSDL/xEventHandler.cpp @@ -0,0 +1 @@ +#include "xEventHandler.h" \ No newline at end of file diff --git a/xSDL/xEventHandler.h b/xSDL/xEventHandler.h new file mode 100644 index 0000000..68dbf56 --- /dev/null +++ b/xSDL/xEventHandler.h @@ -0,0 +1,16 @@ +#ifndef DEF_XEVENT_HANDLER_H + #define DEF_XEVENT_HANDLER_H + + #include "SDL.h" + using namespace std; + + class xEventHandler { + + public: + + // handles the event + virtual void handle(SDL_Event* event) const = 0; + + }; + +#endif \ No newline at end of file