Add Event Looper

This commit is contained in:
Kirigaya Kazuto 2017-05-02 13:37:03 +08:00
parent 65c8b2e6ef
commit 64ec1cfa42
2 changed files with 91 additions and 0 deletions

View File

@ -19,3 +19,67 @@ int PushEvent(const Event& refEvent)
{
return SDL_PushEvent(const_cast<Event*>(&refEvent));
}
Looper::Looper()
{
_update=_running=true;
}
void Looper::add(decltype(Event::type) event_type,const std::function<int(Looper&,Event&)>& event_callback)
{
_evmap[event_type].push_back(event_callback);
}
void Looper::add(decltype(Event::type) event_type,const std::function<int(Event&)>& event_callback)
{
_evmap[event_type].push_back([&](Looper& lp,Event& ev)->int{return event_callback(ev);});
}
void Looper::add(decltype(Event::type) event_type,const std::function<void(Looper&,Event&)>& event_callback)
{
_evmap[event_type].push_back([&](Looper& lp,Event& ev)->int{event_callback(lp,ev); return 0;});
}
void Looper::add(decltype(Event::type) event_type,const std::function<void(Event&)>& event_callback)
{
_evmap[event_type].push_back([&](Looper& lp,Event& ev)->int{event_callback(ev); return 0;});
}
void Looper::dispatch()
{
for(auto callback:_evmap[_e.type])
{
if(callback(*this,_e)) break;
}
}
void Looper::run()
{
while(_running)
{
while(!_update&&WaitEvent(_e))
{
dispatch();
}
_update=false;
}
}
Event Looper::GetLastEvent()
{
return _e;
}
void Looper::needupdate()
{
_update=true;
}
void Looper::needstop()
{
_running=false;
}
void Looper::stop()
{
needstop();
needupdate();
}
void Looper::reset()
{
_running=true;
_update=true;
_evmap.clear();
}

View File

@ -1,5 +1,7 @@
#pragma once
#include "MiniEngine.h"
#include <map>
#include <list>
typedef SDL_Event Event;
@ -7,3 +9,28 @@ int PollEvent(Event& refEvent);
int WaitEvent(Event& refEvent);
int WaitEventTimeout(Event& refEvent,int ms);
int PushEvent(const Event& refEvent);
class Looper
{
public:
Looper();
/// If Callback does not return 0, then stop transferring this event.
void add(decltype(Event::type) event_type,const std::function<int(Looper&,Event&)>& event_callback);
/// If Callback does not return 0, then stop transferring this event. (Discards Looper)
void add(decltype(Event::type) event_type,const std::function<int(Event&)>& event_callback);
/// If Callback has no return (void), then we assume it return 0.
void add(decltype(Event::type) event_type,const std::function<void(Looper&,Event&)>& event_callback);
/// If Callback has no return (void), then we assume it return 0. (Discards Looper)
void add(decltype(Event::type) event_type,const std::function<void(Event&)>& event_callback);
void dispatch();
void run();
Event GetLastEvent();
void needupdate();
void needstop();
void stop();
void reset();
private:
Event _e;
bool _running,_update;
std::map<decltype(Event::type),std::list<std::function<int(Looper&,Event&)>>> _evmap;
};