-
Notifications
You must be signed in to change notification settings - Fork 19
/
pysidesignal.cpp
1344 lines (1163 loc) · 50.5 KB
/
pysidesignal.cpp
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2020 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include <sbkpython.h>
#include "pysidesignal.h"
#include "pysidesignal_p.h"
#include "pysideqobject.h"
#include "pysideutils.h"
#include "pysidestaticstrings.h"
#include "pysideweakref.h"
#include "signalmanager.h"
#include <shiboken.h>
#include <sbkstaticstrings.h>
#include <QtCore/QByteArray>
#include <QtCore/QDebug>
#include <QtCore/QHash>
#include <QtCore/QObject>
#include <QtCore/QMetaMethod>
#include <QtCore/QMetaObject>
#include <pep384ext.h>
#include <signature.h>
#include <sbkenum.h>
#include <algorithm>
#include <optional>
#include <utility>
#include <cstring>
static constexpr char QT_SIGNAL_SENTINEL = '2';
using namespace Qt::StringLiterals;
QDebug operator<<(QDebug debug, const PySideSignalData::Signature &s)
{
QDebugStateSaver saver(debug);
debug.noquote();
debug.nospace();
debug << "Signature(\"" << s.signature << '"';
if (s.attributes)
debug << ", attributes=" << s.attributes;
debug << ')';
return debug;
}
QDebug operator<<(QDebug debug, const PySideSignalData &d)
{
QDebugStateSaver saver(debug);
debug.noquote();
debug.nospace();
debug << "PySideSignalData(\"" << d.signalName << "\", "
<< d.signatures;
if (!d.signalArguments.isEmpty())
debug << ", signalArguments=" << d.signalArguments;
debug << ')';
return debug;
}
QDebug operator<<(QDebug debug, const PySideSignalInstancePrivate &d)
{
QDebugStateSaver saver(debug);
debug.noquote();
debug.nospace();
debug << "PySideSignalInstancePrivate(\"" << d.signalName
<< "\", \"" << d.signature << '"';
if (d.attributes)
debug << ", attributes=" << d.attributes;
if (d.homonymousMethod)
debug << ", homonymousMethod=" << d.homonymousMethod;
debug << ')';
return debug;
}
static bool connection_Check(PyObject *o)
{
if (o == nullptr || o == Py_None)
return false;
static QByteArray typeName = QByteArrayLiteral("PySide")
+ QByteArray::number(QT_VERSION_MAJOR)
+ QByteArrayLiteral(".QtCore.QMetaObject.Connection");
return std::strcmp(o->ob_type->tp_name, typeName.constData()) == 0;
}
static std::optional<QByteArrayList> parseArgumentNames(PyObject *argArguments)
{
QByteArrayList result;
if (argArguments == nullptr)
return result;
// Prevent a string from being split into a sequence of characters
if (PySequence_Check(argArguments) == 0 || PyUnicode_Check(argArguments) != 0)
return std::nullopt;
const Py_ssize_t argumentSize = PySequence_Size(argArguments);
result.reserve(argumentSize);
for (Py_ssize_t i = 0; i < argumentSize; ++i) {
Shiboken::AutoDecRef item(PySequence_GetItem(argArguments, i));
if (PyUnicode_Check(item.object()) == 0)
return std::nullopt;
Shiboken::AutoDecRef strObj(PyUnicode_AsUTF8String(item));
const char *s = PyBytes_AsString(strObj);
if (s == nullptr)
return std::nullopt;
result.append(QByteArray(s));
}
return result;
}
namespace PySide::Signal {
static QByteArray buildSignature(const QByteArray &, const QByteArray &);
static void instanceInitialize(PySideSignalInstance *, PyObject *, PySideSignal *, PyObject *, int);
static PySideSignalData::Signature parseSignature(PyObject *);
static PyObject *buildQtCompatible(const QByteArray &);
} // PySide::Signal
extern "C"
{
// Signal methods
static int signalTpInit(PyObject *, PyObject *, PyObject *);
static void signalFree(void *);
static void signalInstanceFree(void *);
static PyObject *signalGetItem(PyObject *self, PyObject *key);
static PyObject *signalGetAttr(PyObject *self, PyObject *name);
static PyObject *signalToString(PyObject *self);
static PyObject *signalDescrGet(PyObject *self, PyObject *obj, PyObject *type);
// Signal Instance methods
static PyObject *signalInstanceConnect(PyObject *, PyObject *, PyObject *);
static PyObject *signalInstanceDisconnect(PyObject *, PyObject *);
static PyObject *signalInstanceEmit(PyObject *, PyObject *);
static PyObject *signalInstanceGetItem(PyObject *, PyObject *);
static PyObject *signalInstanceCall(PyObject *self, PyObject *args, PyObject *kw);
static PyObject *signalCall(PyObject *, PyObject *, PyObject *);
static PyObject *metaSignalCheck(PyObject *, PyObject *);
static PyMethodDef MetaSignal_tp_methods[] = {
{"__instancecheck__", reinterpret_cast<PyCFunction>(metaSignalCheck),
METH_O|METH_STATIC, nullptr},
{nullptr, nullptr, 0, nullptr}
};
static PyTypeObject *createMetaSignalType()
{
PyType_Slot PySideMetaSignalType_slots[] = {
{Py_tp_methods, reinterpret_cast<void *>(MetaSignal_tp_methods)},
{Py_tp_base, reinterpret_cast<void *>(&PyType_Type)},
{Py_tp_free, reinterpret_cast<void *>(PyObject_GC_Del)},
{Py_tp_dealloc, reinterpret_cast<void *>(Sbk_object_dealloc)},
{0, nullptr}
};
PyType_Spec PySideMetaSignalType_spec = {
"2:PySide6.QtCore.MetaSignal",
0,
// sizeof(PyHeapTypeObject) is filled in by SbkType_FromSpec
// which calls PyType_Ready which calls inherit_special.
0,
Py_TPFLAGS_DEFAULT,
PySideMetaSignalType_slots,
};
return SbkType_FromSpec(&PySideMetaSignalType_spec);
}
static PyTypeObject *PySideMetaSignal_TypeF()
{
static auto *type = createMetaSignalType();
return type;
}
static PyTypeObject *createSignalType()
{
PyType_Slot PySideSignalType_slots[] = {
{Py_mp_subscript, reinterpret_cast<void *>(signalGetItem)},
{Py_tp_getattro, reinterpret_cast<void *>(signalGetAttr)},
{Py_tp_descr_get, reinterpret_cast<void *>(signalDescrGet)},
{Py_tp_call, reinterpret_cast<void *>(signalCall)},
{Py_tp_str, reinterpret_cast<void *>(signalToString)},
{Py_tp_init, reinterpret_cast<void *>(signalTpInit)},
{Py_tp_new, reinterpret_cast<void *>(PyType_GenericNew)},
{Py_tp_free, reinterpret_cast<void *>(signalFree)},
{Py_tp_dealloc, reinterpret_cast<void *>(Sbk_object_dealloc)},
{0, nullptr}
};
PyType_Spec PySideSignalType_spec = {
"2:PySide6.QtCore.Signal",
sizeof(PySideSignal),
0,
Py_TPFLAGS_DEFAULT,
PySideSignalType_slots,
};
return SbkType_FromSpecWithMeta(&PySideSignalType_spec, PySideMetaSignal_TypeF());
}
PyTypeObject *PySideSignal_TypeF(void)
{
static auto *type = createSignalType();
return type;
}
static PyObject *signalInstanceRepr(PyObject *obSelf)
{
auto *self = reinterpret_cast<PySideSignalInstance *>(obSelf);
const auto *typeName = Py_TYPE(obSelf)->tp_name;
return Shiboken::String::fromFormat("<%s %s at %p>", typeName,
self->d ? self->d->signature.constData()
: "(no signature)", obSelf);
}
static PyMethodDef SignalInstance_methods[] = {
{"connect", reinterpret_cast<PyCFunction>(signalInstanceConnect),
METH_VARARGS|METH_KEYWORDS, nullptr},
{"disconnect", signalInstanceDisconnect, METH_VARARGS, nullptr},
{"emit", signalInstanceEmit, METH_VARARGS, nullptr},
{nullptr, nullptr, 0, nullptr} /* Sentinel */
};
static PyTypeObject *createSignalInstanceType()
{
PyType_Slot PySideSignalInstanceType_slots[] = {
{Py_mp_subscript, reinterpret_cast<void *>(signalInstanceGetItem)},
{Py_tp_call, reinterpret_cast<void *>(signalInstanceCall)},
{Py_tp_methods, reinterpret_cast<void *>(SignalInstance_methods)},
{Py_tp_repr, reinterpret_cast<void *>(signalInstanceRepr)},
{Py_tp_new, reinterpret_cast<void *>(PyType_GenericNew)},
{Py_tp_free, reinterpret_cast<void *>(signalInstanceFree)},
{Py_tp_dealloc, reinterpret_cast<void *>(Sbk_object_dealloc)},
{0, nullptr}
};
PyType_Spec PySideSignalInstanceType_spec = {
"2:PySide6.QtCore.SignalInstance",
sizeof(PySideSignalInstance),
0,
Py_TPFLAGS_DEFAULT,
PySideSignalInstanceType_slots,
};
return SbkType_FromSpec(&PySideSignalInstanceType_spec);
}
PyTypeObject *PySideSignalInstance_TypeF(void)
{
static auto *type = createSignalInstanceType();
return type;
}
static int signalTpInit(PyObject *obSelf, PyObject *args, PyObject *kwds)
{
static PyObject * const emptyTuple = PyTuple_New(0);
static const char *kwlist[] = {"name", "arguments", nullptr};
char *argName = nullptr;
PyObject *argArguments = nullptr;
if (!PyArg_ParseTupleAndKeywords(emptyTuple, kwds,
"|sO:QtCore.Signal{name, arguments}",
const_cast<char **>(kwlist), &argName, &argArguments))
return -1;
bool tupledArgs = false;
auto *self = reinterpret_cast<PySideSignal *>(obSelf);
if (!self->data)
self->data = new PySideSignalData;
if (argName)
self->data->signalName = argName;
auto argumentNamesOpt = parseArgumentNames(argArguments);
if (!argumentNamesOpt.has_value()) {
PyErr_SetString(PyExc_TypeError, "'arguments' must be a sequence of strings.");
return -1;
}
self->data->signalArguments = argumentNamesOpt.value();
for (Py_ssize_t i = 0, i_max = PyTuple_Size(args); i < i_max; i++) {
PyObject *arg = PyTuple_GetItem(args, i);
if (PySequence_Check(arg) && !Shiboken::String::check(arg) && !PyEnumMeta_Check(arg)) {
tupledArgs = true;
self->data->signatures.append(PySide::Signal::parseSignature(arg));
}
}
if (!tupledArgs)
self->data->signatures.append(PySide::Signal::parseSignature(args));
return 0;
}
static void signalFree(void *vself)
{
auto *pySelf = reinterpret_cast<PyObject *>(vself);
auto *self = reinterpret_cast<PySideSignal *>(vself);
if (self->data) {
delete self->data;
self->data = nullptr;
}
Py_XDECREF(self->homonymousMethod);
self->homonymousMethod = nullptr;
PepExt_TypeCallFree(Py_TYPE(pySelf)->tp_base, self);
}
static PyObject *signalGetItem(PyObject *obSelf, PyObject *key)
{
auto *self = reinterpret_cast<PySideSignal *>(obSelf);
QByteArray sigKey;
if (key) {
sigKey = PySide::Signal::parseSignature(key).signature;
} else {
sigKey = self->data == nullptr || self->data->signatures.isEmpty()
? PySide::Signal::voidType() : self->data->signatures.constFirst().signature;
}
auto sig = PySide::Signal::buildSignature(self->data->signalName, sigKey);
return Shiboken::String::fromCString(sig.constData());
}
static PyObject *signalToString(PyObject *obSelf)
{
auto *self = reinterpret_cast<PySideSignal *>(obSelf);
QByteArray result;
if (self->data == nullptr || self->data->signatures.isEmpty()) {
result = "<invalid>"_ba;
} else {
for (const auto &signature : std::as_const(self->data->signatures)) {
if (!result.isEmpty())
result += "; "_ba;
result += PySide::Signal::buildSignature(self->data->signalName,
signature.signature);
}
}
return Shiboken::String::fromCString(result.constData());
}
static PyObject *signalGetAttr(PyObject *obSelf, PyObject *name)
{
auto *self = reinterpret_cast<PySideSignal *>(obSelf);
if (PyUnicode_CompareWithASCIIString(name, "signatures") != 0)
return PyObject_GenericGetAttr(obSelf, name);
auto nelems = self->data->signatures.count();
PyObject *tuple = PyTuple_New(nelems);
for (Py_ssize_t idx = 0; idx < nelems; ++idx) {
QByteArray sigKey = self->data->signatures.at(idx).signature;
auto sig = PySide::Signal::buildSignature(self->data->signalName, sigKey);
PyObject *entry = Shiboken::String::fromCString(sig.constData());
PyTuple_SetItem(tuple, idx, entry);
}
return tuple;
}
static void signalInstanceFree(void *vself)
{
auto *pySelf = reinterpret_cast<PyObject *>(vself);
auto *self = reinterpret_cast<PySideSignalInstance *>(vself);
PySideSignalInstancePrivate *dataPvt = self->d;
if (dataPvt) {
Py_XDECREF(dataPvt->homonymousMethod);
if (dataPvt->next) {
Py_DECREF(dataPvt->next);
dataPvt->next = nullptr;
}
delete dataPvt;
self->d = nullptr;
}
self->deleted = true;
PepExt_TypeCallFree(Py_TYPE(pySelf)->tp_base, self);
}
// PYSIDE-1523: PyFunction_Check is not accepting compiled functions and
// PyMethod_Check is not allowing compiled methods, therefore also lookup
// "im_func" and "__code__" attributes, we allow for that with a dedicated
// function handling both.
struct FunctionArgumentsResult
{
PyObject *function = nullptr;
PepCodeObject *objCode = nullptr;
PyObject *functionName = nullptr;
bool isMethod = false;
};
static FunctionArgumentsResult extractFunctionArgumentsFromSlot(PyObject *slot)
{
FunctionArgumentsResult ret;
ret.isMethod = PyMethod_Check(slot);
const bool isFunction = PyFunction_Check(slot);
if (ret.isMethod || isFunction) {
ret.function = ret.isMethod ? PyMethod_GET_FUNCTION(slot) : slot;
ret.objCode = reinterpret_cast<PepCodeObject *>(PyFunction_GET_CODE(ret.function));
ret.functionName = PepFunction_GetName(ret.function);
} else if (PySide::isCompiledMethod(slot)) {
// PYSIDE-1523: PyFunction_Check and PyMethod_Check are not accepting compiled forms, we
// just go by attributes.
ret.isMethod = true;
ret.function = PyObject_GetAttr(slot, PySide::PySideName::im_func());
// Not retaining a reference inline with what PyMethod_GET_FUNCTION does.
Py_DECREF(ret.function);
ret.functionName = PyObject_GetAttr(ret.function, PySide::PySideMagicName::name());
// Not retaining a reference inline with what PepFunction_GetName does.
Py_DECREF(ret.functionName);
ret.objCode = reinterpret_cast<PepCodeObject *>(
PyObject_GetAttr(ret.function, PySide::PySideMagicName::code()));
// Not retaining a reference inline with what PyFunction_GET_CODE does.
Py_XDECREF(ret.objCode);
// Should not happen, but lets handle it gracefully, maybe Nuitka one day
// makes these optional, or somebody defined a type named like it without
// it being actually being that.
if (ret.objCode == nullptr)
ret.function = nullptr;
} else if (strcmp(Py_TYPE(slot)->tp_name, "compiled_function") == 0) {
ret.isMethod = false;
ret.function = slot;
ret.functionName = PyObject_GetAttr(ret.function, PySide::PySideMagicName::name());
// Not retaining a reference inline with what PepFunction_GetName does.
Py_DECREF(ret.functionName);
ret.objCode = reinterpret_cast<PepCodeObject *>(
PyObject_GetAttr(ret.function, PySide::PySideMagicName::code()));
// Not retaining a reference inline with what PyFunction_GET_CODE does.
Py_XDECREF(ret.objCode);
// Should not happen, but lets handle it gracefully, maybe Nuitka one day
// makes these optional, or somebody defined a type named like it without
// it being actually being that.
if (ret.objCode == nullptr)
ret.function = nullptr;
}
// any other callback
return ret;
}
struct ArgCount
{
int min;
int max;
};
// Return a pair of minimum / arg count "foo(p1, p2=0)" -> {1, 2}
ArgCount argCount(const FunctionArgumentsResult &args)
{
Q_ASSERT(args.objCode);
ArgCount result{-1, -1};
if ((PepCode_GET_FLAGS(args.objCode) & CO_VARARGS) == 0) {
result.min = result.max = PepCode_GET_ARGCOUNT(args.objCode);
if (args.function != nullptr) {
if (auto *defaultArgs = PepFunction_GetDefaults(args.function))
result.min -= PyTuple_Size(defaultArgs);
}
}
return result;
}
// Find Signal Instance for argument count.
static PySideSignalInstance *findSignalInstance(PySideSignalInstance *source, int argCount)
{
for (auto *si = source; si != nullptr; si = si->d->next) {
if (si->d->argCount == argCount)
return si;
}
return nullptr;
}
static PySideSignalInstance *findSignalInstanceForSlot(PySideSignalInstance *source,
PyObject *slot)
{
Q_ASSERT(slot != nullptr && slot != Py_None);
// Check signature of the slot (method or function) to match signal
const auto args = extractFunctionArgumentsFromSlot(slot);
if (args.function != nullptr && source->d->next != nullptr) {
auto slotArgRange = argCount(args);
if (args.isMethod) {
slotArgRange.min -= 1;
slotArgRange.max -= 1;
}
// Get signature args
// Iterate the possible types of connection for this signal and compare
// it with slot arguments
for (int slotArgs = slotArgRange.max; slotArgs >= slotArgRange.min; --slotArgs) {
if (auto *matchedSlot = findSignalInstance(source, slotArgs))
return matchedSlot;
}
}
return source;
}
static PyObject *signalInstanceConnect(PyObject *self, PyObject *args, PyObject *kwds)
{
PyObject *slot = nullptr;
PyObject *type = nullptr;
static const char *kwlist[] = {"slot", "type", nullptr};
if (!PyArg_ParseTupleAndKeywords(args, kwds,
"O|O:SignalInstance", const_cast<char **>(kwlist), &slot, &type))
return nullptr;
auto *source = reinterpret_cast<PySideSignalInstance *>(self);
if (!source->d)
return PyErr_Format(PyExc_RuntimeError, "cannot connect uninitialized SignalInstance");
if (source->deleted)
return PyErr_Format(PyExc_RuntimeError, "Signal source has been deleted");
Shiboken::AutoDecRef pyArgs(PyList_New(0));
bool match = false;
if (Py_TYPE(slot) == PySideSignalInstance_TypeF()) {
PySideSignalInstance *sourceWalk = source;
//find best match
while (sourceWalk && !match) {
auto *targetWalk = reinterpret_cast<PySideSignalInstance *>(slot);
while (targetWalk && !match) {
if (QMetaObject::checkConnectArgs(sourceWalk->d->signature,
targetWalk->d->signature)) {
PyList_Append(pyArgs, sourceWalk->d->source);
Shiboken::AutoDecRef sourceSignature(PySide::Signal::buildQtCompatible(sourceWalk->d->signature));
PyList_Append(pyArgs, sourceSignature);
PyList_Append(pyArgs, targetWalk->d->source);
Shiboken::AutoDecRef targetSignature(PySide::Signal::buildQtCompatible(targetWalk->d->signature));
PyList_Append(pyArgs, targetSignature);
match = true;
}
targetWalk = reinterpret_cast<PySideSignalInstance *>(targetWalk->d->next);
}
sourceWalk = reinterpret_cast<PySideSignalInstance *>(sourceWalk->d->next);
}
} else {
// Adding references to pyArgs
PyList_Append(pyArgs, source->d->source);
// Check signature of the slot (method or function) to match signal
PySideSignalInstance *matchedSlot = findSignalInstanceForSlot(source, slot);
Shiboken::AutoDecRef signature(PySide::Signal::buildQtCompatible(matchedSlot->d->signature));
PyList_Append(pyArgs, signature);
PyList_Append(pyArgs, slot);
match = true;
}
if (type)
PyList_Append(pyArgs, type);
if (match) {
Shiboken::AutoDecRef tupleArgs(PyList_AsTuple(pyArgs));
Shiboken::AutoDecRef pyMethod(PyObject_GetAttr(source->d->source,
PySide::PySideName::qtConnect()));
if (pyMethod.isNull()) // PYSIDE-79: check if pyMethod exists.
return PyErr_Format(PyExc_RuntimeError, "method 'connect' vanished!");
PyObject *result = PyObject_CallObject(pyMethod, tupleArgs);
if (connection_Check(result))
return result;
Py_XDECREF(result);
}
if (!PyErr_Occurred()) // PYSIDE-79: inverse the logic. A Null return needs an error.
PyErr_Format(PyExc_RuntimeError, "Failed to connect signal %s.",
source->d->signature.constData());
return nullptr;
}
static int argCountInSignature(const char *signature)
{
return QByteArrayView{signature}.count(',') + 1;
}
static PyObject *signalInstanceEmit(PyObject *self, PyObject *args)
{
auto *source = reinterpret_cast<PySideSignalInstance *>(self);
if (!source->d)
return PyErr_Format(PyExc_RuntimeError, "cannot emit uninitialized SignalInstance");
// PYSIDE-2201: Check if the object has vanished meanwhile.
// Tried to revive it without exception, but this gives problems.
if (source->deleted)
return PyErr_Format(PyExc_RuntimeError, "The SignalInstance object was already deleted");
Shiboken::AutoDecRef pyArgs(PyList_New(0));
Py_ssize_t numArgsGiven = PySequence_Size(args);
int numArgsInSignature = argCountInSignature(source->d->signature);
// If number of arguments given to emit is smaller than the first source signature expects,
// it is possible it's a case of emitting a signal with default parameters.
// Search through all the overloaded signals with the same name, and try to find a signature
// with the same number of arguments as given to emit, and is also marked as a cloned method
// (which in metaobject parlance means a signal with default parameters).
// @TODO: This should be improved to take into account argument types as well. The current
// assumption is there are no signals which are both overloaded on argument types and happen to
// have signatures with default parameters.
if (numArgsGiven < numArgsInSignature) {
PySideSignalInstance *possibleDefaultInstance = source;
while ((possibleDefaultInstance = possibleDefaultInstance->d->next)) {
if (possibleDefaultInstance->d->attributes & QMetaMethod::Cloned
&& argCountInSignature(possibleDefaultInstance->d->signature) == numArgsGiven) {
source = possibleDefaultInstance;
break;
}
}
}
Shiboken::AutoDecRef sourceSignature(PySide::Signal::buildQtCompatible(source->d->signature));
PyList_Append(pyArgs, sourceSignature);
for (Py_ssize_t i = 0, max = PyTuple_Size(args); i < max; i++)
PyList_Append(pyArgs, PyTuple_GetItem(args, i));
Shiboken::AutoDecRef pyMethod(PyObject_GetAttr(source->d->source,
PySide::PySideName::qtEmit()));
Shiboken::AutoDecRef tupleArgs(PyList_AsTuple(pyArgs));
return PyObject_CallObject(pyMethod.object(), tupleArgs);
}
static PyObject *signalInstanceGetItem(PyObject *self, PyObject *key)
{
auto *firstSignal = reinterpret_cast<PySideSignalInstance *>(self);
const auto &sigName = firstSignal->d->signalName;
const auto sigKey = PySide::Signal::parseSignature(key).signature;
const auto sig = PySide::Signal::buildSignature(sigName, sigKey);
for (auto *data = firstSignal; data != nullptr; data = data->d->next) {
if (data->d->signature == sig) {
auto *result = reinterpret_cast<PyObject *>(data);
Py_INCREF(result);
return result;
}
}
// Build error message with candidates
QByteArray message = "Signature \"" + sig + "\" not found for signal: \""
+ sigName + "\". Available candidates: ";
for (auto *data = firstSignal; data != nullptr; data = data->d->next) {
if (data != firstSignal)
message += ", ";
message += '"' + data->d->signature + '"';
}
return PyErr_Format(PyExc_IndexError, message.constData());
}
static inline void warnDisconnectFailed(PyObject *aSlot, const QByteArray &signature)
{
if (PyErr_Occurred() != nullptr) { // avoid "%S" invoking str() when an error is set.
PyObject *exc{};
PyObject *inst{};
PyObject *tb{};
PyErr_Fetch(&exc, &inst, &tb);
PyErr_WarnFormat(PyExc_RuntimeWarning, 0, "Failed to disconnect (%s) from signal \"%s\".",
Py_TYPE(aSlot)->tp_name, signature.constData());
PyErr_Restore(exc, inst, tb);
} else {
PyErr_WarnFormat(PyExc_RuntimeWarning, 0, "Failed to disconnect (%S) from signal \"%s\".",
aSlot, signature.constData());
}
}
static PyObject *signalInstanceDisconnect(PyObject *self, PyObject *args)
{
auto *source = reinterpret_cast<PySideSignalInstance *>(self);
if (!source->d)
return PyErr_Format(PyExc_RuntimeError, "cannot disconnect uninitialized SignalInstance");
Shiboken::AutoDecRef pyArgs(PyList_New(0));
PyObject *slot = Py_None;
if (PyTuple_Check(args) && PyTuple_Size(args))
slot = PyTuple_GetItem(args, 0);
bool match = false;
if (Py_TYPE(slot) == PySideSignalInstance_TypeF()) {
auto *target = reinterpret_cast<PySideSignalInstance *>(slot);
if (QMetaObject::checkConnectArgs(source->d->signature, target->d->signature)) {
PyList_Append(pyArgs, source->d->source);
Shiboken::AutoDecRef source_signature(PySide::Signal::buildQtCompatible(source->d->signature));
PyList_Append(pyArgs, source_signature);
PyList_Append(pyArgs, target->d->source);
Shiboken::AutoDecRef target_signature(PySide::Signal::buildQtCompatible(target->d->signature));
PyList_Append(pyArgs, target_signature);
match = true;
}
} else if (connection_Check(slot)) {
PyList_Append(pyArgs, slot);
match = true;
} else {
// try the matching signature, fall back to first
auto *matchedSlot = slot != Py_None ? findSignalInstanceForSlot(source, slot) : source;
PyList_Append(pyArgs, matchedSlot->d->source);
Shiboken::AutoDecRef signature(PySide::Signal::buildQtCompatible(matchedSlot->d->signature));
PyList_Append(pyArgs, signature);
// disconnect all, so we need to use the c++ signature disconnect(qobj, signal, 0, 0)
if (slot == Py_None)
PyList_Append(pyArgs, slot);
PyList_Append(pyArgs, slot);
match = true;
}
if (match) {
Shiboken::AutoDecRef tupleArgs(PyList_AsTuple(pyArgs));
Shiboken::AutoDecRef pyMethod(PyObject_GetAttr(source->d->source,
PySide::PySideName::qtDisconnect()));
PyObject *result = PyObject_CallObject(pyMethod, tupleArgs);
if (result != Py_True)
warnDisconnectFailed(slot, source->d->signature);
return result;
}
warnDisconnectFailed(slot, source->d->signature);
Py_RETURN_FALSE;
}
// PYSIDE-68: Supply the missing __get__ function
static PyObject *signalDescrGet(PyObject *self, PyObject *obj, PyObject * /*type*/)
{
auto *signal = reinterpret_cast<PySideSignal *>(self);
// Return the unbound signal if there is nothing to bind it to.
if (obj == nullptr || obj == Py_None
|| !PySide::isQObjectDerived(Py_TYPE(obj), true)) {
Py_INCREF(self);
return self;
}
// PYSIDE-68-bis: It is important to respect the already cached instance.
Shiboken::AutoDecRef name(Py_BuildValue("s", signal->data->signalName.data()));
auto *dict = SbkObject_GetDict_NoRef(obj);
auto *inst = PyDict_GetItem(dict, name);
if (inst) {
Py_INCREF(inst);
return inst;
}
inst = reinterpret_cast<PyObject *>(PySide::Signal::initialize(signal, name, obj));
PyObject_SetAttr(obj, name, inst);
return inst;
}
static PyObject *signalCall(PyObject *self, PyObject *args, PyObject *kw)
{
auto *signal = reinterpret_cast<PySideSignal *>(self);
// Native C++ signals can't be called like functions, thus we throw an exception.
// The only way calling a signal can succeed (the Python equivalent of C++'s operator() )
// is when a method with the same name as the signal is attached to an object.
// An example is QProcess::error() (don't check the docs, but the source code of qprocess.h).
if (!signal->homonymousMethod)
return PyErr_Format(PyExc_TypeError, "native Qt signal is not callable");
// Check if there exists a method with the same name as the signal, which is also a static
// method in C++ land.
Shiboken::AutoDecRef homonymousMethod(PepExt_Type_CallDescrGet(signal->homonymousMethod,
nullptr, nullptr));
if (PyCFunction_Check(homonymousMethod.object())
&& (PyCFunction_GET_FLAGS(homonymousMethod.object()) & METH_STATIC))
return PyObject_Call(homonymousMethod, args, kw);
// Assumes homonymousMethod is not a static method.
ternaryfunc callFunc = PepExt_Type_GetCallSlot(Py_TYPE(signal->homonymousMethod));
return callFunc(homonymousMethod, args, kw);
}
// This function returns a borrowed reference.
static inline PyObject *_getRealCallable(PyObject *func)
{
static const auto *SignalType = PySideSignal_TypeF();
static const auto *SignalInstanceType = PySideSignalInstance_TypeF();
// If it is a signal, use the (maybe empty) homonymous method.
if (Py_TYPE(func) == SignalType) {
auto *signal = reinterpret_cast<PySideSignal *>(func);
return signal->homonymousMethod;
}
// If it is a signal instance, use the (maybe empty) homonymous method.
if (Py_TYPE(func) == SignalInstanceType) {
auto *signalInstance = reinterpret_cast<PySideSignalInstance *>(func);
return signalInstance->d->homonymousMethod;
}
return func;
}
// This function returns a borrowed reference.
static PyObject *_getHomonymousMethod(PySideSignalInstance *inst)
{
if (inst->d->homonymousMethod)
return inst->d->homonymousMethod;
// PYSIDE-1730: We are searching methods with the same name not only at the same place,
// but walk through the whole mro to find a hidden method with the same name.
auto signalName = inst->d->signalName;
Shiboken::AutoDecRef name(Shiboken::String::fromCString(signalName));
auto *mro = Py_TYPE(inst->d->source)->tp_mro;
const Py_ssize_t n = PyTuple_Size(mro);
for (Py_ssize_t idx = 0; idx < n; idx++) {
auto *sub_type = reinterpret_cast<PyTypeObject *>(PyTuple_GetItem(mro, idx));
Shiboken::AutoDecRef tpDict(PepType_GetDict(sub_type));
auto *hom = PyDict_GetItem(tpDict, name);
if (hom != nullptr && PyCallable_Check(hom) != 0) {
if (auto *realFunc = _getRealCallable(hom))
return realFunc;
}
}
return nullptr;
}
static PyObject *signalInstanceCall(PyObject *self, PyObject *args, PyObject *kw)
{
auto *PySideSignal = reinterpret_cast<PySideSignalInstance *>(self);
auto *hom = _getHomonymousMethod(PySideSignal);
if (!hom) {
PyErr_Format(PyExc_TypeError, "native Qt signal instance '%s' is not callable",
PySideSignal->d->signalName.constData());
return nullptr;
}
Shiboken::AutoDecRef homonymousMethod(PepExt_Type_CallDescrGet(hom, PySideSignal->d->source,
nullptr));
return PyObject_Call(homonymousMethod, args, kw);
}
static PyObject *metaSignalCheck(PyObject * /* klass */, PyObject *arg)
{
if (PyType_IsSubtype(Py_TYPE(arg), PySideSignalInstance_TypeF()))
Py_RETURN_TRUE;
Py_RETURN_FALSE;
}
} // extern "C"
namespace PySide::Signal {
static const char *MetaSignal_SignatureStrings[] = {
"PySide6.QtCore.MetaSignal.__instancecheck__(self,object:object)->bool",
nullptr}; // Sentinel
static const char *Signal_SignatureStrings[] = {
"PySide6.QtCore.Signal(self,*types:type,name:str=nullptr,arguments:typing.List[str]=nullptr)",
"1:PySide6.QtCore.Signal.__get__(self,instance:None,owner:Optional[typing.Any])->"
"PySide6.QtCore.Signal",
"0:PySide6.QtCore.Signal.__get__(self,instance:PySide6.QtCore.QObject,"
"owner:Optional[typing.Any])->PySide6.QtCore.SignalInstance",
nullptr}; // Sentinel
static const char *SignalInstance_SignatureStrings[] = {
"PySide6.QtCore.SignalInstance.connect(self,slot:object,"
"type:PySide6.QtCore.Qt.ConnectionType=PySide6.QtCore.Qt.ConnectionType.AutoConnection)"
"->PySide6.QtCore.QMetaObject.Connection",
"PySide6.QtCore.SignalInstance.disconnect(self,slot:object=nullptr)->bool",
"PySide6.QtCore.SignalInstance.emit(self,*args:typing.Any)",
nullptr}; // Sentinel
void init(PyObject *module)
{
if (InitSignatureStrings(PySideMetaSignal_TypeF(), MetaSignal_SignatureStrings) < 0)
return;
Py_INCREF(PySideMetaSignal_TypeF());
auto *obMetaSignal_Type = reinterpret_cast<PyObject *>(PySideMetaSignal_TypeF());
PyModule_AddObject(module, "MetaSignal", obMetaSignal_Type);
if (InitSignatureStrings(PySideSignal_TypeF(), Signal_SignatureStrings) < 0)
return;
Py_INCREF(PySideSignal_TypeF());
auto *obSignal_Type = reinterpret_cast<PyObject *>(PySideSignal_TypeF());
PyModule_AddObject(module, "Signal", obSignal_Type);
if (InitSignatureStrings(PySideSignalInstance_TypeF(), SignalInstance_SignatureStrings) < 0)
return;
Py_INCREF(PySideSignalInstance_TypeF());
auto *obSignalInstance_Type = reinterpret_cast<PyObject *>(PySideSignalInstance_TypeF());
PyModule_AddObject(module, "SignalInstance", obSignalInstance_Type);
}
bool checkType(PyObject *pyObj)
{
if (pyObj)
return PyType_IsSubtype(Py_TYPE(pyObj), PySideSignal_TypeF());
return false;
}
bool checkInstanceType(PyObject *pyObj)
{
return pyObj != nullptr
&& PyType_IsSubtype(Py_TYPE(pyObj), PySideSignalInstance_TypeF()) != 0;
}
void updateSourceObject(PyObject *source)
{
// TODO: Provide for actual upstream exception handling.
// For now we'll just return early to avoid further issues.
if (source == nullptr) // Bad input
return;
Shiboken::AutoDecRef mroIterator(PyObject_GetIter(source->ob_type->tp_mro));
if (mroIterator.isNull()) // Not iterable
return;
Shiboken::AutoDecRef mroItem{};
auto *dict = SbkObject_GetDict_NoRef(source);
// PYSIDE-1431: Walk the mro and update. But see PYSIDE-1751 below.
while ((mroItem.reset(PyIter_Next(mroIterator))), mroItem.object()) {
PyObject *key{};
PyObject *value{};
Py_ssize_t pos = 0;
auto *type = reinterpret_cast<PyTypeObject *>(mroItem.object());
Shiboken::AutoDecRef tpDict(PepType_GetDict(type));
while (PyDict_Next(tpDict, &pos, &key, &value)) {
if (PyObject_TypeCheck(value, PySideSignal_TypeF())) {
// PYSIDE-1751: We only insert an instance into the instance dict, if a signal
// of the same name is in the mro. This is the equivalent action
// as PyObject_SetAttr, but filtered by existing signal names.
if (!PyDict_GetItem(dict, key)) {
auto *inst = PyObject_New(PySideSignalInstance, PySideSignalInstance_TypeF());
Shiboken::AutoDecRef signalInstance(reinterpret_cast<PyObject *>(inst));
auto *si = reinterpret_cast<PySideSignalInstance *>(signalInstance.object());
instanceInitialize(si, key, reinterpret_cast<PySideSignal *>(value),
source, 0);
if (PyDict_SetItem(dict, key, signalInstance) == -1)
return; // An error occurred while setting the attribute
}
}
}
}
if (PyErr_Occurred()) // An iteration error occurred
return;
}
// PYSIDE-2840: For an enum registered in Qt, return the C++ name.
// Ignore flags here; their underlying enums are of Python type flags anyways.
static QByteArray getQtEnumTypeName(PyTypeObject *type)
{
if (!Shiboken::Enum::checkType(type))
return {};
Shiboken::AutoDecRef qualName(PyObject_GetAttr(reinterpret_cast<PyObject *>(type),
Shiboken::PyMagicName::qualname()));
QByteArray result = Shiboken::String::toCString(qualName.object());
result.replace(".", "::");
const auto metaType = QMetaType::fromName(result);
return metaType.isValid() && metaType.flags().testFlag(QMetaType::IsEnumeration)
? result : QByteArray{};
}
QByteArray getTypeName(PyObject *obType)
{
if (PyType_Check(obType)) {
auto *type = reinterpret_cast<PyTypeObject *>(obType);
if (PyType_IsSubtype(type, SbkObject_TypeF()))
return Shiboken::ObjectType::getOriginalName(type);
// Translate Python types to Qt names
if (Shiboken::String::checkType(type))
return QByteArrayLiteral("QString");
if (type == &PyLong_Type)
return QByteArrayLiteral("int");
if (type == &PyFloat_Type)
return QByteArrayLiteral("double");
if (type == &PyBool_Type)
return QByteArrayLiteral("bool");
if (type == &PyList_Type)
return QByteArrayLiteral("QVariantList");
if (type == &PyDict_Type)
return QByteArrayLiteral("QVariantMap");
QByteArray enumName = getQtEnumTypeName(type);
return enumName.isEmpty() ? "PyObject"_ba : enumName;
}
if (obType == Py_None) // Must be checked before as Shiboken::String::check accepts Py_None
return voidType();
if (Shiboken::String::check(obType)) {
QByteArray result = Shiboken::String::toCString(obType);
if (result == "qreal")
result = sizeof(qreal) == sizeof(double) ? "double" : "float";
return result;
}
return {};
}
static QByteArray buildSignature(const QByteArray &name, const QByteArray &signature)
{
return QMetaObject::normalizedSignature(name + '(' + signature + ')');
}
static PySideSignalData::Signature parseSignature(PyObject *args)
{