Audacity 3.2.0
AppEvents.cpp
Go to the documentation of this file.
1/*
2 * SPDX-License-Identifier: GPL-2.0-or-later
3 * SPDX-FileName: AppEvents.cpp
4 * SPDX-FileContributor: Dmitry Vedenko
5 */
6
7#include "AppEvents.h"
8
9#include <cassert>
10#include <vector>
11
12
13
14namespace AppEvents
15{
16namespace
17{
19{
20};
21
22struct EventHandlers final : public Observer::Publisher<IdleEvent>
23{
24 std::vector<std::function<void()>> appInitialized;
25 std::vector<std::function<void()>> appClosing;
26
27 bool AppInitializedCalled {};
28 bool AppClosingCalled {};
29
32};
33
35{
36 static EventHandlers handlers;
37 return handlers;
38}
39
40} // namespace
41
42void OnAppInitialized(std::function<void()> callback)
43{
44 assert(callback);
45
46 if (!callback)
47 return;
48
49 auto& handlers = GetEventHandlers();
50
51 if (handlers.AppInitializedCalled)
52 callback();
53 else
54 handlers.appInitialized.push_back(std::move(callback));
55}
56
57void OnAppClosing(std::function<void()> callback)
58{
59 assert(callback);
60
61 if (!callback)
62 return;
63
64 auto& handlers = GetEventHandlers();
65
66 if (handlers.AppClosingCalled)
67 callback();
68 else
69 handlers.appClosing.push_back(std::move(callback));
70}
71
72Observer::Subscription OnAppIdle(std::function<void()> callback)
73{
74 return GetEventHandlers().Subscribe([callback = std::move(callback)](auto&)
75 { callback(); });
76}
77
79{
80 auto& handlers = GetEventHandlers();
81
82 handlers.AppInitializedCalled = true;
83
84 std::vector<std::function<void()>> callbacks;
85 std::swap(callbacks, handlers.appInitialized);
86
87 for (auto& callback : callbacks)
88 callback();
89}
90
92{
93 GetEventHandlers().Publish(IdleEvent{});
94}
95
97{
98 auto& handlers = GetEventHandlers();
99
100 handlers.AppClosingCalled = true;
101
102 std::vector<std::function<void()>> callbacks;
103 std::swap(callbacks, handlers.appClosing);
104
105 for (auto& callback : callbacks)
106 callback();
107}
108
109} // namespace AppEvents
An object that sends messages to an open-ended list of subscribed callbacks.
Definition: Observer.h:108
Subscription Subscribe(Callback callback)
Connect a callback to the Publisher; later-connected are called earlier.
Definition: Observer.h:199
CallbackReturn Publish(const Message &message)
Send a message to connected callbacks.
Definition: Observer.h:207
A move-only handle representing a connection to a Publisher.
Definition: Observer.h:70
void OnAppClosing(std::function< void()> callback)
Definition: AppEvents.cpp:57
Observer::Subscription OnAppIdle(std::function< void()> callback)
Definition: AppEvents.cpp:72
void OnAppInitialized(std::function< void()> callback)
Definition: AppEvents.cpp:42
void swap(std::unique_ptr< Alg_seq > &a, std::unique_ptr< Alg_seq > &b)
Definition: NoteTrack.cpp:628
std::vector< std::function< void()> > appInitialized
Definition: AppEvents.cpp:24
std::vector< std::function< void()> > appClosing
Definition: AppEvents.cpp:25