EventListener.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. bool EventListener::unsubscribe(const Event &_event)
  39. {
  40. NullPointerEvaluator(_event.getManager(), "no event manager is provided for " + _event.getClassName()).evaluate();
  41. return this->_unsubscribe(_event);
  42. }
  43. void EventListener::_requestListenerId(const shared_ptr<Class> &_manager)
  44. {
  45. shared_ptr<EventManager> manager = dynamic_pointer_cast<EventManager>(_manager);
  46. if (this->id == 0)
  47. {
  48. this->setId(manager->requestListenerId());
  49. }
  50. }
  51. bool EventListener::_subscribe(const Event &_event, const event_action &_action)
  52. {
  53. bool subscribed{};
  54. if (shared_ptr<EventManager> manager = dynamic_pointer_cast<EventManager>(_event.getManager()); !manager->holdsListenerForEvent(this->id, _event))
  55. {
  56. manager->subscribeListenerForEvent(shared_from_this(), _event, _action);
  57. subscribed = manager->holdsListenerForEvent(this->id, _event);
  58. }
  59. return subscribed;
  60. }
  61. bool EventListener::_unsubscribe(const Event &_event)
  62. {
  63. bool unsubscribed{};
  64. if (shared_ptr<EventManager> manager = dynamic_pointer_cast<EventManager>(_event.getManager()); manager->holdsListenerForEvent(this->id, _event))
  65. {
  66. manager->unsubscribeListenerForEvent(shared_from_this(), _event);
  67. unsubscribed = !manager->holdsListenerForEvent(this->id, _event);
  68. }
  69. return unsubscribed;
  70. }