aboutsummaryrefslogtreecommitdiff
path: root/include/core/signal.h
blob: be2984b19aaf968379d6ce937589d7ea2d49854a (plain)
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
/*
 * Copyright © 2013 Canonical Ltd.
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Authored by: Thomas Voß <thomas.voss@canonical.com>
 */
#ifndef COM_UBUNTU_SIGNAL_H_
#define COM_UBUNTU_SIGNAL_H_

#include <core/connection.h>

#include <functional>
#include <iostream>
#include <list>
#include <mutex>
#include <set>

namespace core
{
/**
 * @brief A signal class that observers can subscribe to.
 * @tparam Arguments List of argument types passed on to observers when the signal is emitted.
 */
template<typename ...Arguments>
class Signal
{
public:
    /**
     * @brief Slot is the function type that observers have to provide to connect to this signal.
     */
    typedef std::function<void(Arguments...)> Slot;

private:
    struct SlotWrapper
    {
        void operator()(Arguments... args)
        {
            dispatcher(std::bind(slot, args...));
        }

        Slot slot;
        Connection::Dispatcher dispatcher;
        Connection connection;
    };

public:
    /**
     * @brief Signal constructs a new instance. Never throws.
     */
    inline Signal() noexcept(true) : d(new Private())
    {
    }

    inline ~Signal()
    {
        std::lock_guard<std::mutex> lg(d->guard);
        for (auto slot : d->slots)
            slot.connection.reset();
    }

    // Copy construction, assignment and equality comparison are disabled.
    Signal(const Signal&) = delete;
    Signal& operator=(const Signal&) = delete;
    bool operator==(const Signal&) const = delete;

    /**
     * @brief Connects the provided slot to this signal instance.
     *
     * Calling this method is thread-safe and synchronized with any
     * other connect, signal emission or disconnect calls.
     *
     * @param slot The function to be called when the signal is emitted.
     * @return A connection object corresponding to the signal-slot connection.
     */
    inline Connection connect(const Slot& slot) const
    {
        // Helpers to initialize an invalid connection.
        static const Connection::Disconnector empty_disconnector{};
        static const Connection::DispatcherInstaller empty_dispatcher_installer{};

        // The default dispatcher immediately executes the function object
        // provided as argument on whatever thread is currently running.
        static const Connection::Dispatcher default_dispatcher
                = [](const std::function<void()>& handler) { handler(); };

        Connection conn{empty_disconnector, empty_dispatcher_installer};

        std::lock_guard<std::mutex> lg(d->guard);

        auto result = d->slots.insert(
                    d->slots.end(),
                    SlotWrapper{slot, default_dispatcher, conn});

        // We implicitly share our internal state with the connection here
        // by passing in our private bits contained in 'd' to the std::bind call.
        // This admittedly uncommon approach allows us to cleanly manage connection
        // and signal lifetimes without the need to mark everything as mutable.
        conn.d->disconnector = std::bind(
                    &Private::disconnect_slot_for_iterator,
                    d,
                    result);
        conn.d->dispatcher_installer = std::bind(
                    &Private::install_dispatcher_for_iterator,
                    d,
                    std::placeholders::_1,
                    result);

        return conn;
    }

    /**
     * @brief operator () emits the signal with the provided parameters.
     *
     * Please note that signal emissions might not be delivered immediately to
     * registered slots, depending on whether the respective connection is dispatched
     * via a queueing dispatcher. For that reason, the lifetime of the arguments has to
     * exceed the scope of the call to this operator and its surrounding scope.
     *
     * @param args The arguments to be passed on to registered slots.
     */
    inline void operator()(Arguments... args)
    {
        std::lock_guard<std::mutex> lg(d->guard);
        for(auto slot : d->slots)
        {
            slot(args...);
        }
    }

private:
    struct Private
    {
        typedef std::list<SlotWrapper> SlotContainer;

        inline void disconnect_slot_for_iterator(typename SlotContainer::iterator it)
        {
            std::lock_guard<std::mutex> lg(guard);
            slots.erase(it);
        }

        inline void install_dispatcher_for_iterator(const Connection::Dispatcher& dispatcher,
                                                    typename SlotContainer::iterator it)
        {
            std::lock_guard<std::mutex> lg(guard);
            it->dispatcher = dispatcher;
        }

        std::mutex guard;
        SlotContainer slots;
    };
    std::shared_ptr<Private> d;
};

/**
 * @brief A signal class that observers can subscribe to,
 * template specialization for signals without arguments.
 */
template<>
class Signal<void>
{
public:
    /**
     * @brief Slot is the function type that observers have to provide to connect to this signal.
     */
    typedef std::function<void()> Slot;

private:
    struct SlotWrapper
    {
        void operator()()
        {
            dispatcher(slot);
        }

        Slot slot;
        Connection::Dispatcher dispatcher;
        Connection connection;
    };

public:
    /**
     * @brief Signal constructs a new instance. Never throws.
     */
    inline Signal() noexcept(true) : d(new Private())
    {
    }

    inline ~Signal()
    {
        std::lock_guard<std::mutex> lg(d->guard);
        for (auto slot : d->slots)
            slot.connection.reset();
    }

    // Copy construction, assignment and equality comparison are disabled.
    Signal(const Signal&) = delete;
    Signal& operator=(const Signal&) = delete;
    bool operator==(const Signal&) const = delete;

    /**
     * @brief Connects the provided slot to this signal instance.
     *
     * Calling this method is thread-safe and synchronized with any
     * other connect, signal emission or disconnect calls.
     *
     * @param slot The function to be called when the signal is emitted.
     * @return A connection object corresponding to the signal-slot connection.
     */
    inline Connection connect(const Slot& slot) const
    {
        // Helpers to initialize an invalid connection.
        static const Connection::Disconnector empty_disconnector{};
        static const Connection::DispatcherInstaller empty_dispatcher_installer{};

        // The default dispatcher immediately executes the function object
        // provided as argument on whatever thread is currently running.
        static const Connection::Dispatcher default_dispatcher
                = [](const std::function<void()>& handler) { handler(); };

        Connection conn{empty_disconnector, empty_dispatcher_installer};

        std::lock_guard<std::mutex> lg(d->guard);

        auto result = d->slots.insert(
                    d->slots.end(),
                    SlotWrapper{slot, default_dispatcher, conn});

        // We implicitly share our internal state with the connection here
        // by passing in our private bits contained in 'd' to the std::bind call.
        // This admittedly uncommon approach allows us to cleanly manage connection
        // and signal lifetimes without the need to mark everything as mutable.
        conn.d->disconnector = std::bind(
                    &Private::disconnect_slot_for_iterator,
                    d,
                    result);
        conn.d->dispatcher_installer = std::bind(
                    &Private::install_dispatcher_for_iterator,
                    d,
                    std::placeholders::_1,
                    result);

        return conn;
    }

    /**
     * @brief operator () emits the signal.
     *
     * Please note that signal emissions might not be delivered immediately to
     * registered slots, depending on whether the respective connection is dispatched
     * via a queueing dispatcher.
     */
    inline void operator()()
    {
        std::lock_guard<std::mutex> lg(d->guard);
        for(auto slot : d->slots)
        {
            slot();
        }
    }

private:
    struct Private
    {
        typedef std::list<SlotWrapper> SlotContainer;

        inline void disconnect_slot_for_iterator(typename SlotContainer::iterator it)
        {
            std::lock_guard<std::mutex> lg(guard);
            slots.erase(it);
        }

        inline void install_dispatcher_for_iterator(const Connection::Dispatcher& dispatcher,
                                                    typename SlotContainer::iterator it)
        {
            std::lock_guard<std::mutex> lg(guard);
            it->dispatcher = dispatcher;
        }

        std::mutex guard;
        SlotContainer slots;
    };
    std::shared_ptr<Private> d;
};
}

#endif // COM_UBUNTU_SIGNAL_H_