1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
|
/*
* SPDX-License-Identifier: GPL-2.0-or-later
* SPDX-FileName: AppEvents.cpp
* SPDX-FileContributor: Dmitry Vedenko
*/
#include "AppEvents.h"
#include <cassert>
#include <vector>
namespace AppEvents
{
namespace
{
struct IdleEvent
{
};
struct EventHandlers final : public Observer::Publisher<IdleEvent>
{
std::vector<std::function<void()>> appInitialized;
std::vector<std::function<void()>> appClosing;
bool AppInitializedCalled {};
bool AppClosingCalled {};
using Observer::Publisher<IdleEvent>::Subscribe;
using Observer::Publisher<IdleEvent>::Publish;
};
EventHandlers& GetEventHandlers()
{
static EventHandlers handlers;
return handlers;
}
} // namespace
void OnAppInitialized(std::function<void()> callback)
{
assert(callback);
if (!callback)
return;
auto& handlers = GetEventHandlers();
if (handlers.AppInitializedCalled)
callback();
else
handlers.appInitialized.push_back(std::move(callback));
}
void OnAppClosing(std::function<void()> callback)
{
assert(callback);
if (!callback)
return;
auto& handlers = GetEventHandlers();
if (handlers.AppClosingCalled)
callback();
else
handlers.appClosing.push_back(std::move(callback));
}
Observer::Subscription OnAppIdle(std::function<void()> callback)
{
return GetEventHandlers().Subscribe([callback = std::move(callback)](auto&)
{ callback(); });
}
void ProviderBase::HandleAppInitialized()
{
auto& handlers = GetEventHandlers();
handlers.AppInitializedCalled = true;
std::vector<std::function<void()>> callbacks;
std::swap(callbacks, handlers.appInitialized);
for (auto& callback : callbacks)
callback();
}
void ProviderBase::HandleAppIdle()
{
GetEventHandlers().Publish(IdleEvent{});
}
void ProviderBase::HandleAppClosing()
{
auto& handlers = GetEventHandlers();
handlers.AppClosingCalled = true;
std::vector<std::function<void()>> callbacks;
std::swap(callbacks, handlers.appClosing);
for (auto& callback : callbacks)
callback();
}
} // namespace AppEvents
|