summaryrefslogtreecommitdiff
path: root/src/QGlib/signal.cpp
blob: 5acc4db66c9c6dfd603bf996188f0a3aebeb77f0 (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
/*
    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/>.
*/
#include "signal.h"
#include "quark.h"
#include <glib-object.h>
#include <QtCore/QStringList>
#include <QtCore/QDebug>

namespace QGlib {

//BEGIN ******** SignalHandler ********

bool SignalHandler::isConnected() const
{
    return g_signal_handler_is_connected(m_instance, m_id);
}

void SignalHandler::disconnect()
{
    g_signal_handler_disconnect(m_instance, m_id);
}

void SignalHandler::block()
{
    g_signal_handler_block(m_instance, m_id);
}

void SignalHandler::unblock()
{
    g_signal_handler_unblock(m_instance, m_id);
}

//END ******** SignalHandler ********
//BEGIN ******** Signal ********

struct Signal::Private : public QSharedData
{
    Private(uint i) : id(i), m_queryInitialized(false) {}

    uint id;
    GSignalQuery *query() const;

private:
    mutable GSignalQuery m_query;
    mutable bool m_queryInitialized;
};

GSignalQuery *Signal::Private::query() const
{
    if (!m_queryInitialized) {
        g_signal_query(id, &m_query);
        m_queryInitialized = true;
    }
    return &m_query;
}


Signal::Signal(uint id)
    : d(new Private(id))
{
}

Signal::Signal(const Signal & other)
    : d(other.d)
{
}

Signal & Signal::operator=(const Signal & other)
{
    d = other.d;
    return *this;
}

Signal::~Signal()
{
}

bool Signal::isValid() const
{
    return d->id != 0;
}

uint Signal::id() const
{
    return d->id;
}

QString Signal::name() const
{
    return QString::fromUtf8(d->query()->signal_name);
}

Signal::SignalFlags Signal::flags() const
{
    return QFlag(d->query()->signal_flags);
}

Type Signal::instanceType() const
{
    return d->query()->itype;
}

Type Signal::returnType() const
{
    return d->query()->return_type & ~G_SIGNAL_TYPE_STATIC_SCOPE;
}

QList<Type> Signal::paramTypes() const
{
    QList<Type> result;
    for(uint i=0; i<d->query()->n_params; ++i) {
        result.append(d->query()->param_types[i] & ~G_SIGNAL_TYPE_STATIC_SCOPE);
    }
    return result;
}

//static
Signal Signal::lookup(const char *name, Type type)
{
    return Signal(g_signal_lookup(name, type));
}

//static
QList<Signal> Signal::listSignals(Type type)
{
    QList<Signal> result;
    uint n_ids;
    uint *ids = g_signal_list_ids(type, &n_ids);
    for(uint i=0; i<n_ids; ++i) {
        result.append(Signal(ids[i]));
    }
    g_free(ids);
    return result;
}

//END ******** Signal ********
//BEGIN ******** Closure ********

void Closure::ref(bool increaseRef)
{
    if (increaseRef) {
        g_closure_ref(static_cast<GClosure*>(m_object));
    }
}

void Closure::unref()
{
    g_closure_unref(static_cast<GClosure*>(m_object));
}

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

namespace Private {

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

static void c_marshaller(GClosure *closure, GValue *returnValue, uint paramValuesCount,
                         const GValue *paramValues, void *hint, void *data)
{
    Q_UNUSED(data);

    ClosureDataBase *cdata = static_cast<ClosureDataBase*>(closure->data);

    QList<Value> params;
    //the signal sender is always the first argument. if we are instructed not to pass it
    //as an argument to the slot, begin converting from paramValues[1]
    for(uint i = cdata->passSender ? 0 : 1; i<paramValuesCount; ++i) {
        params.append(Value(&paramValues[i]));
    }

    try {
        Value result(returnValue);
        cdata->marshaller(result, params);

        if (returnValue) {
            g_value_copy(result, returnValue);
        }
    } catch (const std::exception & e) {
        QString signalName;
        if (hint != NULL) {
            GSignalInvocationHint *ihint = static_cast<GSignalInvocationHint*>(hint);

            GSignalQuery query;
            g_signal_query(ihint->signal_id, &query);
            signalName = QString::fromUtf8(query.signal_name);

            if (ihint->detail != 0) {
                Quark q(ihint->detail);
                signalName.append(QLatin1String("::"));
                signalName.append(q.toString());
            }
        }

        QString instanceName = params.at(0).get<QString>();

        //attempt to determine the cause of the failure
        QString msg;
        try {
            //dynamic_cast will throw an std::bad_cast if it fails
            dynamic_cast<const InvalidTypeException &>(e);
            //cast succeded, e is indeed an InvalidTypeException
            msg = QLatin1String("One or more of the arguments of the signal are of different "
                                "type than the type that the closure expects");
        } catch (...) {
            try {
                dynamic_cast<const InvalidValueException &>(e);
                //cast succeded, e is indeed an InvalidValueException
                //this is most likely to happen because the signal returns void
                //but the closure returns something non-void. check this first.
                if (returnValue == NULL) {
                    msg = QLatin1String("The signal is defined to return void but the "
                                        "closure returns something non-void");
                } else {
                    msg = QLatin1String("One of the arguments of the signal was not a valid GValue. "
                                        "This is most likely a bug in the code that invoked the signal.");
                }
            } catch (...) {
                msg = QString::fromAscii(e.what());
            }
        }

        qCritical() << "Error during invocation of closure connected to signal"
                    << signalName << "from object" << instanceName << ":" << msg;
    }
}

static void closureDestroyNotify(void *data, GClosure *closure)
{
    Q_UNUSED(data);
    delete static_cast<ClosureDataBase*>(closure->data);
}

ClosurePtr createCppClosure(ClosureDataBase *closureData)
{
    GClosure *closure = g_closure_new_simple(sizeof(GClosure), closureData);
    g_closure_set_marshal(closure, &c_marshaller);
    g_closure_add_finalize_notifier(closure, NULL, &closureDestroyNotify);
    ClosurePtr result = ClosurePtr::wrap(closure);
    g_closure_sink(closure);
    return result;
}

//END ******** Closure internals ********
//BEGIN ******** connect ********

SignalHandler connect(void *instance, const char *detailedSignal,
                      const ClosurePtr & closure, ConnectFlags flags)
{
    uint id = g_signal_connect_closure(instance, detailedSignal, closure,
                                       (flags & ConnectAfter) ? TRUE : FALSE);
    return SignalHandler(instance, id);
}

//END ******** connect ********
//BEGIN ******** emit ********

Value emit(void *instance, const char *detailedSignal, const QList<Value> & args)
{
    Value result;
    Type itype = Type::fromInstance(instance);
    QStringList signalParts = QString::fromUtf8(detailedSignal).split(QLatin1String("::"));
    Quark detail;
    if (signalParts.size() > 1) {
        detail = Quark(signalParts[1]);
    }

    //initialize arguments array
    GValue *values = new GValue[args.size() + 1];
    memset(values, 0, sizeof(GValue) * (args.size() + 1));

    //set instance
    g_value_init(&values[0], itype);
    g_value_set_instance(&values[0], instance);

    try {
        //find the signal and perform sanity checks
        Signal signal = Signal::lookup(signalParts[0].toUtf8(), itype);
        if (!signal.isValid()) {
            throw QString(QLatin1String("Could not find any signal named %1 "
                                        "on this instance type")).arg(signalParts[0]);
        }

        QList<Type> paramTypes = signal.paramTypes();
        if (paramTypes.size() != args.size()) {
            throw QString(QLatin1String("The number of arguments that the signal accepts differ "
                                        "from the number of arguments provided to emit"));
        }

        //set arguments
        for(int i=0; i<args.size(); i++) {
            if (!paramTypes[i].isA(args[i].type())) {
                throw QString(QLatin1String("Argument %1 provided to emit is not of the "
                                            "type that the signal expects")).arg(i);
            } else {
                g_value_init(&values[i+1], args[i].type());
                g_value_copy(args[i], &values[i+1]);
            }
        }

        //initialize return value
        GValue returnValue = QGLIB_G_VALUE_INITIALIZER;
        if (signal.returnType() != Type::None) {
            g_value_init(&returnValue, signal.returnType());
        }

        //emit the signal
        g_signal_emitv(values, signal.id(), detail, &returnValue);

        if (G_IS_VALUE(&returnValue)) {
            result = Value(&returnValue);
            g_value_unset(&returnValue);
        }
    } catch (const QString & msg) {
        QString instanceName = Value(&values[0]).toString();

        qCritical() << "Error during emission of signal" << detailedSignal
                    << "on object"<< instanceName << ":" << msg;
    }

    //cleanup
    for(int i=0; i<args.size() + 1; i++) {
        g_value_unset(&values[i]);
    }
    delete[] values;

    return result;
}

//END ******** emit ********

} //namespace Private
} //namespace QGlib