summaryrefslogtreecommitdiffstats
path: root/engine/include/core/signal.hpp
blob: f06a193a8da8b133e6a1efc0fd3a274f256d6863 (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
#pragma once

#include "task.hpp"
#include "types.hpp"
#include "priority.hpp"
#include "labelled.hpp"
#include "debug.hpp"

#include <tuple>
#include <list>
#include <functional>
#include <memory>


namespace flat::core
{
    /* forward decls */
    template<typename ...Args>
    class listener;

    class channel;

    namespace helper
    {
        /* class helper::signal 
         *
         * is a non constructible, but copyable object used only as abstract
         * pointer type. To make anything with it must be first downcasted to a
         * core::signal<Args...>
         */
        class signal : public prioritized
        {
        public:
            /// copyable
            signal(const signal& other) = default;
            /// movable
            signal(signal&& other) = default;

            virtual ~signal() {}

        protected:
            /// not default constructible
            signal() = delete;

            /// normal constructor
            signal(priority_t p = priority_t::none) : prioritized(p) {}
        };
    }

    /* class signal<...Args>
     *
     * is a tuple wrapper that contains function arguments (...Args) 
     * that are later used to call a callback stored in a listener.
     */
    template <typename ...Args> 
    struct signal : public helper::signal
    {
        const std::tuple<Args...> args;

        /// disallow empty constructor
        // TODO: think: should empty signals be allowed?
        //       yes if there is a way to identify them by something that
        //       is not the signature of the listener (so not yet)
        signal() = delete;

        /// copyable
        signal(const signal& other) = default;

        /// movable
        signal(signal&& other) = default;

        /// normal constructor that copies arguments
        constexpr signal(const Args&... _args)
            : helper::signal(priority_t::none), args(_args...) {}

        constexpr signal(priority_t p, const Args&... _args)
            : helper::signal(p), args(_args...) {}

        /// normal constructor that forwards arguments
        /// this optimizes rvalue initializations
        constexpr signal(Args&&... _args)
            : helper::signal(priority_t::none),
              args(std::forward<Args>(_args)...)
        {}

        constexpr signal(priority_t p, Args&&... _args)
            : helper::signal(p),
              args(std::forward<Args>(_args)...)
        {}
    };


    namespace helper
    {
        /* class helper::listener
         *
         * is a non constructible, but copyable object used only as abstract
         * pointer type. To make anything with it must be first downcasted to a
         * core::listener<Args...>
         */
        class listener
        {
        public:
            /// copyable
            listener(const listener& other) = default;

            /// movable
            listener(listener&& other) = default;

            virtual ~listener() {}

            /// pure interface
            virtual bool invoke(std::shared_ptr<const helper::signal> s) const = 0;

        protected:
            /// constructuble only by listener
            listener() = default;
        };
    }
        
    /* class listener<F, ...Args>
     *
     * is an object holding a callback, that can be only called by passing
     * a signal<...Args> object, which contains the arguments for the callback.
     *
     * Note: listener objects can be created only by a channel.
     */
    template <typename ...Args>
    class listener : public helper::listener
    {
    public:
        using callback = typename std::function<void(Args...)>;

        friend class channel;

        /// not default constructible
        listener() = delete;

        /// copyable
        listener(const listener&) = default;

        /// movable
        listener(listener&&) = default;

        /// attempt to call m_callback with s as argument
        /// m_callback is called only if the signature matches
        bool invoke(std::shared_ptr<const helper::signal> s) const override
        {
            auto p = std::dynamic_pointer_cast<const signal<Args...>>(s);

            // if dynamic cast fails
            if (!p) {
                npdebug("invoked listener ", this, " with non-matching signal ", s);
                return false;
            }

            npdebug("invoked listener ", this, " with signal ", p);
            std::apply(m_callback, p->args);

            return true;
        }

    private:
        /// normal constructor only allowed by channel
        listener(callback f) : m_callback(f) {}

        callback m_callback;
    };

    
    /* class channel
     *
     * is an object type through which signals are emitted.
     * and is an object type through which listener get their signals.
     */
    class channel : virtual public labelled
    {
    private:
        // this is a set because sets do not allow identical elements
        std::list<std::weak_ptr<helper::listener>> m_listeners;
        queue<std::shared_ptr<helper::signal>> m_signals;

        /// task to call 
        std::shared_ptr<task> m_broadcast;

        /// connect a std::function (this is a helper), see others below
        template<typename R, typename ...Args>
        std::shared_ptr<listener<Args...>> _connect(std::function<R(Args...)>&& f)
        {
            auto lis_ptr = std::make_shared<listener<Args...>>(
                listener<Args...>(f)
            );

            // insert pointer
            m_listeners.push_front(
                // decay shared_ptr to weak_ptr
                //   btw, here a static_cast is correct
                static_cast<std::weak_ptr<helper::listener>>(
                    // decay listener to helper::listener
                    std::static_pointer_cast<helper::listener>(lis_ptr)
                )
            );

            return lis_ptr;
        }
             
    public:
        using ptr = std::shared_ptr<channel>;
   
        // TODO: channel() that binds to main_job
        channel(job& broadcaster);

        /// not copyable
        // TODO: review: should be copyable?
        channel(const channel&) = delete;

        /// movable
        channel(channel&&) = default;

        /// add a signal to the queue/stack of signals (m_signals)
        template<class ...Args> 
        void emit(const signal<Args...>& sig)
        {   
            // create a shared_ptr
            auto p = std::make_shared<signal<Args...>>(sig)

            npdebug("emitted signal ", p);

            // insert pointer
            m_signals.insert(
                // decay signal to helper::signal
                std::static_pointer_cast<helper::signal>(p)
            );
        }

        /// for each signal accumulated, call each listener
        void broadcast();

        /// connect a closure
        // template<typename ...Args, typename Closure>
        // std::shared_ptr<listener<Args...>> connect(Closure f)
        // {
            // TODO: fix
        // }

        /// connect a function
        template<typename R, typename ...Args>
        std::shared_ptr<listener<Args...>> connect(R (*f)(Args...))
        {
            return _connect(static_cast<std::function<R(Args...)>>(
                [f](Args ...args) constexpr -> R {
                    return f((args)...);
                })
            );
        }

        /// connect a member function
        template<typename R, typename T, typename ...Args>
        std::shared_ptr<listener<Args...>> connect(R (T::*mf)(Args ...args), T* obj)
        {
            return _connect(static_cast<std::function<R(Args...)>>(
                [mf, obj](Args ...args) constexpr -> R {
                    return (obj->*mf)((args)...);
                })
            );
        }
    };
}