SystemEventDispatcher.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include "CrySystem_precompiled.h"
  9. #include "SystemEventDispatcher.h"
  10. #include <AzCore/Debug/Profiler.h>
  11. AZ_DECLARE_BUDGET(CrySystem);
  12. CSystemEventDispatcher::CSystemEventDispatcher()
  13. : m_listeners(0)
  14. {
  15. }
  16. bool CSystemEventDispatcher::RegisterListener(ISystemEventListener* pListener)
  17. {
  18. m_listenerRegistrationLock.lock();
  19. bool ret = m_listeners.Add(pListener);
  20. m_listenerRegistrationLock.unlock();
  21. return ret;
  22. }
  23. bool CSystemEventDispatcher::RemoveListener(ISystemEventListener* pListener)
  24. {
  25. m_listenerRegistrationLock.lock();
  26. m_listeners.Remove(pListener);
  27. m_listenerRegistrationLock.unlock();
  28. return true;
  29. }
  30. //////////////////////////////////////////////////////////////////////////
  31. void CSystemEventDispatcher::OnSystemEventAnyThread(ESystemEvent event, UINT_PTR wparam, UINT_PTR lparam)
  32. {
  33. m_listenerRegistrationLock.lock();
  34. for (TSystemEventListeners::Notifier notifier(m_listeners); notifier.IsValid(); notifier.Next())
  35. {
  36. notifier->OnSystemEventAnyThread(event, wparam, lparam);
  37. }
  38. m_listenerRegistrationLock.unlock();
  39. }
  40. //////////////////////////////////////////////////////////////////////////
  41. void CSystemEventDispatcher::OnSystemEvent(ESystemEvent event, UINT_PTR wparam, UINT_PTR lparam)
  42. {
  43. if (gEnv && gEnv->mMainThreadId == CryGetCurrentThreadId())
  44. {
  45. for (TSystemEventListeners::Notifier notifier(m_listeners); notifier.IsValid(); notifier.Next())
  46. {
  47. notifier->OnSystemEvent(event, wparam, lparam);
  48. }
  49. }
  50. else
  51. {
  52. SEventParams params;
  53. params.event = event;
  54. params.wparam = wparam;
  55. params.lparam = lparam;
  56. m_systemEventQueue.push(params);
  57. }
  58. // Also dispatch the event on this thread. This technically means the event
  59. // will be sent twice (thru different OnSystemEventXX functions), therefore it is up to listeners which one they react to.
  60. OnSystemEventAnyThread(event, wparam, lparam);
  61. }
  62. //////////////////////////////////////////////////////////////////////////
  63. void CSystemEventDispatcher::Update()
  64. {
  65. AZ_PROFILE_FUNCTION(CrySystem);
  66. assert(gEnv && gEnv->mMainThreadId == CryGetCurrentThreadId());
  67. SEventParams params;
  68. while (m_systemEventQueue.try_pop(params))
  69. {
  70. OnSystemEvent(params.event, params.wparam, params.lparam);
  71. }
  72. }