EventListener.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * Author: Patrick-Christopher Mattulat
  3. * Company: Lynar Studios
  4. * E-Mail: webmaster@lynarstudios.com
  5. * Created: 2024-05-16
  6. * Changed: 2024-05-17
  7. *
  8. * */
  9. #include <ls-std/core/evaluator/NullPointerEvaluator.hpp>
  10. #include <ls-std/event/EventListener.hpp>
  11. #include <ls-std/event/EventManager.hpp>
  12. using ls::std::core::Class;
  13. using ls::std::core::NullPointerEvaluator;
  14. using ls::std::event::Event;
  15. using ls::std::event::EventListener;
  16. using ls::std::event::EventManager;
  17. using ls::std::event::type::event_action;
  18. using ls::std::event::type::listener_id;
  19. using ::std::dynamic_pointer_cast;
  20. using ::std::shared_ptr;
  21. EventListener::EventListener() : Class("EventListener")
  22. {}
  23. EventListener::~EventListener() noexcept = default;
  24. listener_id EventListener::getId() const
  25. {
  26. return this->id;
  27. }
  28. void EventListener::setId(listener_id _id)
  29. {
  30. this->id = _id;
  31. }
  32. bool EventListener::subscribe(const Event &_event, const event_action &_action)
  33. {
  34. NullPointerEvaluator(_event.getManager(), "no event manager is provided for " + _event.getClassName()).evaluate();
  35. this->_requestListenerId(_event.getManager());
  36. return this->_subscribe(_event, _action);
  37. }
  38. void EventListener::_requestListenerId(const shared_ptr<Class> &_manager)
  39. {
  40. shared_ptr<EventManager> manager = dynamic_pointer_cast<EventManager>(_manager);
  41. if (this->id == 0)
  42. {
  43. this->setId(manager->requestListenerId());
  44. }
  45. }
  46. bool EventListener::_subscribe(const Event &_event, const event_action &_action)
  47. {
  48. bool subscribed{};
  49. if (shared_ptr<EventManager> manager = dynamic_pointer_cast<EventManager>(_event.getManager()); !manager->holdsListenerForEvent(this->id, _event))
  50. {
  51. manager->subscribeListenerForEvent(shared_from_this(), _event, _action);
  52. subscribed = manager->holdsListenerForEvent(this->id, _event);
  53. }
  54. return subscribed;
  55. }