summaryrefslogtreecommitdiff
path: root/src/QGlib/connectimpl.h
blob: 023da11c4609b6356256df28a7a5454c74e424e8 (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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
/*
    Copyright (C) 2010  George Kiagiadakis <kiagiadakis.george@gmail.com>

    This library is free software; you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published
    by the Free Software Foundation; either version 2.1 of the License, or
    (at your option) any later version.

    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 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/>.
*/
#if !defined(BOOST_PP_IS_ITERATING) || !BOOST_PP_IS_ITERATING

# ifndef IN_QGLIB_SIGNAL_H
#  error "This file must not be included directly"
# endif

# include "value.h"
# include "refpointer.h"
# include <QtCore/QList>
# include <stdexcept>
# include <boost/type_traits.hpp>


namespace QGlib {

//BEGIN ******** Closure ********

/* Wrapper class for GClosure. It contains no public methods, it is
 * only used internally to pass around GClosure pointers in a C++ fashion.
 */
class Closure : public RefCountedObject
{
    QGLIB_WRAPPER(Closure)

    virtual void ref(bool increaseRef);
    virtual void unref();
};

//END ******** Closure ********

namespace Private {

//BEGIN ******** Closure internals ********

class ClosureDataBase
{
public:
    inline virtual ~ClosureDataBase() {}
    virtual void marshaller(Value &, const QList<Value> &) = 0;

    bool passSender; //whether to pass the sender instance as the first slot argument

protected:
    inline ClosureDataBase(bool passSender)
        : passSender(passSender) {}
};


/*! This is the method that glues the c++ closure system with the GObject world.
 * It creates a GClosure, sets its data, marshaller and finalize notifier accordingly
 * and returns a ClosurePtr. This is the only exported symbol from this library that
 * allows you to create a GClosure and it should only be used through the
 * template CppClosure class.
 */
ClosurePtr createCppClosure(ClosureDataBase *data); //implemented in signal.cpp


template <typename Function, typename Signature>
struct CppClosure {};

//END ******** Closure internals ********
//BEGIN ******** invoker ********

template <typename Function, typename R>
struct invoker
{
    static inline void invoke(const Function & f, Value & result) { ValueImpl<R>::set(result, f()); }
};

template <typename Function>
struct invoker<Function, void>
{
    static inline void invoke(const Function & f, Value &) { f(); }
};

//END ******** invoker ********

} //namespace Private
} //namespace QGlib


# if QGLIB_HAVE_CXX0X

namespace QGlib {
namespace Private {

//BEGIN ******** MemberFunction ********

template <typename T, typename R, typename... Args>
class MemberFunction
{
public:
    inline MemberFunction(R (T::*fn)(Args...), T *obj)
        : m_function(fn), m_object(obj) {}

    inline R operator()(Args&&... args) const
    {
        return (m_object->*m_function)(std::forward<Args>(args)...);
    }

private:
    R (T::*m_function)(Args...);
    T *m_object;
};

template <typename T, typename R, typename... Args>
MemberFunction<T, R, Args...> mem_fn(R (T::*fn)(Args...), T *obj)
{
    return MemberFunction<T, R, Args...>(fn, obj);
}

//END ******** MemberFunction ********
//BEGIN ******** BoundArgumentFunction ********

template <typename ParentFunction, typename R, typename Arg1, typename... Args>
class BoundArgumentFunction
{
public:
    inline BoundArgumentFunction(ParentFunction && fn, Arg1 && arg)
        : m_function(std::forward<ParentFunction>(fn)),
          m_firstArg(std::forward<Arg1>(arg)) {}

    inline R operator()(Args&&... args) const
    {
        return m_function(std::forward<Arg1>(m_firstArg), std::forward<Args>(args)...);
    }

private:
    ParentFunction && m_function;
    Arg1 && m_firstArg;
};

template <typename F, typename R, typename Arg1, typename... Args>
inline BoundArgumentFunction<F, R, Arg1, Args...> partial_bind(F && f, Arg1 && a1)
{
    return BoundArgumentFunction<F, R, Arg1, Args...>(std::forward<F>(f), std::forward<Arg1>(a1));
}

//END ******** BoundArgumentFunction ********
//BEGIN ******** unpackAndInvoke ********

template <typename F, typename R>
inline void unpackAndInvoke(F && function, Value & result,
                            QList<Value>::const_iterator &&,
                            QList<Value>::const_iterator &&)
{
    invoker<F, R>::invoke(function, result);
}

template <typename F, typename R, typename Arg1, typename... Args>
inline void unpackAndInvoke(F && function, Value & result,
                            QList<Value>::const_iterator && argsBegin,
                            QList<Value>::const_iterator && argsEnd)
{
    typedef typename boost::remove_const<
                typename boost::remove_reference<Arg1>::type
            >::type CleanArg1;
    typedef BoundArgumentFunction<F, R, Arg1, Args...> F1;

    CleanArg1 && boundArg = ValueImpl<CleanArg1>::get(*argsBegin);
    F1 && f = partial_bind<F, R, Arg1, Args...>(std::forward<F>(function), std::forward<Arg1>(boundArg));

    unpackAndInvoke< F1, R, Args... >(std::forward<F1>(f), result,
                                      std::forward<QList<Value>::const_iterator>(++argsBegin),
                                      std::forward<QList<Value>::const_iterator>(argsEnd));
}

//END ******** unpackAndInvoke ********
//BEGIN ******** CppClosure ********

template <typename F, typename R, typename... Args>
struct CppClosure<F, R (Args...)>
{
    class ClosureData : public ClosureDataBase
    {
    public:
        inline ClosureData(const F & func, bool passSender)
            : ClosureDataBase(passSender), m_function(func) {}

        virtual void marshaller(Value & result, const QList<Value> & params)
        {
            if (static_cast<unsigned int>(params.size()) < sizeof...(Args)) {
                throw std::logic_error("The signal provides less arguments than what the closure expects");
            }

            unpackAndInvoke<F, R, Args...>(std::forward<F>(m_function), result,
                                           params.constBegin(), params.constEnd());
        }

    private:
        F m_function;
    };

    static inline ClosurePtr create(const F & function, bool passSender)
    {
        return createCppClosure(new ClosureData(function, passSender));
    }
};

//END ******** CppClosure ********

} //namespace Private

//BEGIN ******** QGlib::connect ********

template <typename T, typename R, typename... Args>
SignalHandler connect(void *instance, const char *detailedSignal,
                      T *receiver, R (T::*slot)(Args...), ConnectFlags flags)
{
    typedef QGlib::Private::MemberFunction<T, R, Args...> F;

    F && f = QGlib::Private::mem_fn(slot, receiver);
    ClosurePtr && closure = QGlib::Private::CppClosure<F, R (Args...)>::create(f, flags & PassSender);
    return connect(instance, detailedSignal, closure, flags);
}

//END ******** QGlib::connect ********

} //namespace QGlib

# else //QGLIB_HAVE_CXX0X

#  include <boost/function.hpp>
#  include <boost/preprocessor.hpp>
#  include <boost/bind.hpp>

// include the second part of this file as many times as QGLIB_SIGNAL_MAX_ARGS specifies
#  define BOOST_PP_ITERATION_PARAMS_1 (3,(0, QGLIB_SIGNAL_MAX_ARGS, "QGlib/connectimpl.h"))
#  include BOOST_PP_ITERATE()

#  undef BOOST_PP_ITERATION_PARAMS_1
#  undef QGLIB_SIGNAL_MAX_ARGS

# endif //QGLIB_HAVE_CXX0X


#else // !defined(BOOST_PP_IS_ITERATING) || !BOOST_PP_IS_ITERATING

/*
    This part is included from BOOST_PP_ITERATE(). It defines a CppClosureN class
    (where N is the number of template arguments it takes) and a specialization for class
    CppClosure, so that the CppClosure<R (Args...), F> syntax is supported. This part is
    included multiple times (QGLIB_SIGNAL_MAX_ARGS defines how many), and each time
    it defines those classes with different number of arguments.
    The concept is based on the implementation of boost::function.
*/

# define QGLIB_SIGNAL_IMPL_NUM_ARGS \
    BOOST_PP_ITERATION()

# define QGLIB_SIGNAL_IMPL_TRAILING_TEMPLATE_PARAMS \
    BOOST_PP_ENUM_TRAILING_PARAMS(QGLIB_SIGNAL_IMPL_NUM_ARGS, typename A)

# define QGLIB_SIGNAL_IMPL_TRAILING_TEMPLATE_ARGS \
    BOOST_PP_ENUM_TRAILING_PARAMS(QGLIB_SIGNAL_IMPL_NUM_ARGS, A)

# define QGLIB_SIGNAL_IMPL_TEMPLATE_ARGS \
    BOOST_PP_ENUM_PARAMS(QGLIB_SIGNAL_IMPL_NUM_ARGS, A)

namespace QGlib {
namespace Private {

//BEGIN ******** boostpp CppClosure ********

# define QGLIB_SIGNAL_IMPL_CPPCLOSUREN \
    BOOST_PP_CAT(CppClosure, QGLIB_SIGNAL_IMPL_NUM_ARGS)

# define QGLIB_SIGNAL_IMPL_UNPACK_ARGS_STEP(z, n, list) \
    ,ValueImpl< \
        typename boost::remove_const< \
            typename boost::remove_reference<A ##n>::type \
        >::type \
    >::get(list.at(n))

# define QGLIB_SIGNAL_IMPL_UNPACK_ARGS(list) \
    BOOST_PP_REPEAT(QGLIB_SIGNAL_IMPL_NUM_ARGS, QGLIB_SIGNAL_IMPL_UNPACK_ARGS_STEP, list)

template <typename F, typename R QGLIB_SIGNAL_IMPL_TRAILING_TEMPLATE_PARAMS>
struct QGLIB_SIGNAL_IMPL_CPPCLOSUREN
{
    class ClosureData : public ClosureDataBase
    {
    public:
        inline ClosureData(const F & func, bool passSender)
            : ClosureDataBase(passSender), m_function(func) {}

        virtual void marshaller(Value & result, const QList<Value> & params)
        {
            if (params.size() < QGLIB_SIGNAL_IMPL_NUM_ARGS) {
                throw std::logic_error("The signal provides less arguments than what the closure expects");
            }

# if QGLIB_SIGNAL_IMPL_NUM_ARGS > 0
            boost::function<R ()> callback = boost::bind<R>(m_function
                                                            QGLIB_SIGNAL_IMPL_UNPACK_ARGS(params));
            invoker< boost::function<R ()>, R >::invoke(callback, result);
# else
            invoker< F, R >::invoke(m_function, result);
# endif
        }

    private:
        F m_function;
    };

    static ClosurePtr create(const F & function, bool passSender)
    {
        return createCppClosure(new ClosureData(function, passSender));
    }
};

//partial specialization of struct CppClosure to support the CppClosure<F, R (Args...)> syntax
template <typename F, typename R  QGLIB_SIGNAL_IMPL_TRAILING_TEMPLATE_PARAMS>
struct CppClosure<F, R (QGLIB_SIGNAL_IMPL_TEMPLATE_ARGS)>
    : public QGLIB_SIGNAL_IMPL_CPPCLOSUREN< F, R QGLIB_SIGNAL_IMPL_TRAILING_TEMPLATE_ARGS >
{
};

# undef QGLIB_SIGNAL_IMPL_UNPACK_ARGS
# undef QGLIB_SIGNAL_IMPL_UNPACK_ARGS_STEP
# undef QGLIB_SIGNAL_IMPL_CPPCLOSUREN

//END ******** boostpp CppClosure ********

} //namespace Private

//BEGIN ******** bostpp QGlib::connect ********

# define QGLIB_SIGNAL_IMPL_BIND_ARGS \
    BOOST_PP_COMMA_IF(QGLIB_SIGNAL_IMPL_NUM_ARGS) \
    BOOST_PP_ENUM_SHIFTED_PARAMS(BOOST_PP_INC(QGLIB_SIGNAL_IMPL_NUM_ARGS), _)

template <typename T, typename R QGLIB_SIGNAL_IMPL_TRAILING_TEMPLATE_PARAMS>
SignalHandler connect(void *instance, const char *detailedSignal,
                      T *receiver, R (T::*slot)(QGLIB_SIGNAL_IMPL_TEMPLATE_ARGS),
                      ConnectFlags flags)
{
    boost::function<R (QGLIB_SIGNAL_IMPL_TEMPLATE_ARGS)> f
                = boost::bind(slot, receiver QGLIB_SIGNAL_IMPL_BIND_ARGS);

    ClosurePtr closure = QGlib::Private::CppClosure<
            boost::function<R (QGLIB_SIGNAL_IMPL_TEMPLATE_ARGS)>,
            R (QGLIB_SIGNAL_IMPL_TEMPLATE_ARGS)
        >::create(f, flags & PassSender);

    return connect(instance, detailedSignal, closure, flags);
}

# undef QGLIB_SIGNAL_IMPL_BIND_ARGS

//END ******** bostpp QGlib::connect ********

} //namespace QGlib

# undef QGLIB_SIGNAL_IMPL_TEMPLATE_ARGS
# undef QGLIB_SIGNAL_IMPL_TRAILING_TEMPLATE_ARGS
# undef QGLIB_SIGNAL_IMPL_TRAILING_TEMPLATE_PARAMS
# undef QGLIB_SIGNAL_IMPL_NUM_ARGS

#endif // !defined(BOOST_PP_IS_ITERATING) || !BOOST_PP_IS_ITERATING