forked from commontk/PythonQt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPythonQt.cpp
2345 lines (2108 loc) · 81.4 KB
/
PythonQt.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) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
* 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 library 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.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
* 28359 Bremen, Germany or:
*
* http://www.mevis.de
*
*/
//----------------------------------------------------------------------------------
/*!
// \file PythonQt.cpp
// \author Florian Link
// \author Last changed by $Author: florian $
// \date 2006-05
*/
//----------------------------------------------------------------------------------
#include "PythonQt.h"
#include "PythonQtImporter.h"
#include "PythonQtClassInfo.h"
#include "PythonQtMethodInfo.h"
#include "PythonQtSignal.h"
#include "PythonQtSignalReceiver.h"
#include "PythonQtConversion.h"
#include "PythonQtProperty.h"
#include "PythonQtStdIn.h"
#include "PythonQtStdOut.h"
#include "PythonQtCppWrapperFactory.h"
#include "PythonQtVariants.h"
#include "PythonQtStdDecorators.h"
#include "PythonQtQFileImporter.h"
#include "PythonQtBoolResult.h"
#include "PythonQtSlotDecorator.h"
#include <QDir>
#include <pydebug.h>
#include <vector>
PythonQt* PythonQt::_self = NULL;
int PythonQt::_uniqueModuleCount = 0;
void PythonQt_init_QtGuiBuiltin(PyObject*);
void PythonQt_init_QtCoreBuiltin(PyObject*);
void PythonQt::init(int flags, const QByteArray& pythonQtModuleName)
{
if (!_self) {
_self = new PythonQt(flags, pythonQtModuleName);
PythonQt::priv()->setupSharedLibrarySuffixes();
_self->_p->_PythonQtObjectPtr_metaId = qRegisterMetaType<PythonQtObjectPtr>("PythonQtObjectPtr");
PythonQtConv::registerMetaTypeToPythonConverter(_self->_p->_PythonQtObjectPtr_metaId, PythonQtConv::convertFromPythonQtObjectPtr);
PythonQtConv::registerPythonToMetaTypeConverter(_self->_p->_PythonQtObjectPtr_metaId, PythonQtConv::convertToPythonQtObjectPtr);
PythonQtMethodInfo::addParameterTypeAlias("QObjectList", "QList<QObject*>");
qRegisterMetaType<QList<QObject*> >("QList<void*>");
qRegisterMetaType<QObjectList>("QObjectList");
qRegisterMetaType<QList<QObject*> >("QList<QObject*>");
if (QT_POINTER_SIZE == 8) {
qRegisterMetaType<quint64>("size_t");
} else {
qRegisterMetaType<quint32>("size_t");
}
int stringRefId = qRegisterMetaType<QStringRef>("QStringRef");
PythonQtConv::registerMetaTypeToPythonConverter(stringRefId, PythonQtConv::convertFromStringRef);
int objectPtrListId = qRegisterMetaType<QList<PythonQtObjectPtr> >("QList<PythonQtObjectPtr>");
PythonQtConv::registerMetaTypeToPythonConverter(objectPtrListId, PythonQtConv::convertFromQListOfPythonQtObjectPtr);
PythonQtConv::registerPythonToMetaTypeConverter(objectPtrListId, PythonQtConv::convertToQListOfPythonQtObjectPtr);
PythonQtRegisterToolClassesTemplateConverter(int);
PythonQtRegisterToolClassesTemplateConverter(float);
PythonQtRegisterToolClassesTemplateConverter(double);
PythonQtRegisterToolClassesTemplateConverter(qint32);
PythonQtRegisterToolClassesTemplateConverter(quint32);
PythonQtRegisterToolClassesTemplateConverter(qint64);
PythonQtRegisterToolClassesTemplateConverter(quint64);
#ifdef PYTHONQT_SUPPORT_ML_TYPES
PythonQtMethodInfo::addParameterTypeAlias("QList<MLfloat>", "QList<float>");
PythonQtMethodInfo::addParameterTypeAlias("QVector<MLfloat>", "QVector<float>");
PythonQtMethodInfo::addParameterTypeAlias("QList<MLdouble>", "QList<double>");
PythonQtMethodInfo::addParameterTypeAlias("QVector<MLdouble>", "QVector<double>");
PythonQtMethodInfo::addParameterTypeAlias("QList<MLuint32>", "QList<quint32>");
PythonQtMethodInfo::addParameterTypeAlias("QVector<MLuint32>", "QVector<quint32>");
PythonQtMethodInfo::addParameterTypeAlias("QList<MLint32>", "QList<qint32>");
PythonQtMethodInfo::addParameterTypeAlias("QVector<MLint32>", "QVector<qint32>");
PythonQtMethodInfo::addParameterTypeAlias("QList<MLuint64>", "QList<quint64>");
PythonQtMethodInfo::addParameterTypeAlias("QVector<MLuint64>", "QVector<quint64>");
PythonQtMethodInfo::addParameterTypeAlias("QList<MLint64>", "QList<qint64>");
PythonQtMethodInfo::addParameterTypeAlias("QVector<MLint64>", "QVector<qint64>");
PythonQtMethodInfo::addParameterTypeAlias("QList<MLuint>", "QList<quint64>");
PythonQtMethodInfo::addParameterTypeAlias("QVector<MLuint>", "QVector<quint64>");
PythonQtMethodInfo::addParameterTypeAlias("QList<MLint>", "QList<qint64>");
PythonQtMethodInfo::addParameterTypeAlias("QVector<MLint>", "QVector<qint64>");
#endif
PythonQtMethodInfo::addParameterTypeAlias("QList<qreal>", "QList<double>");
PythonQtMethodInfo::addParameterTypeAlias("QVector<qreal>", "QVector<double>");
PythonQtMethodInfo::addParameterTypeAlias("QList<unsigned int>", "QList<quint32>");
PythonQtMethodInfo::addParameterTypeAlias("QVector<unsigned int>", "QVector<quint32>");
// Qt 4 uses uint, while Qt 5 uses unsigned int, seems to be a moc change...
PythonQtMethodInfo::addParameterTypeAlias("QList<uint>", "QList<quint32>");
PythonQtMethodInfo::addParameterTypeAlias("QVector<uint>", "QVector<quint32>");
PythonQtMethodInfo::addParameterTypeAlias("QList<int>", "QList<qint32>");
PythonQtMethodInfo::addParameterTypeAlias("QVector<int>", "QVector<qint32>");
PythonQtMethodInfo::addParameterTypeAlias("QList<GLint>", "QList<qint32>");
PythonQtMethodInfo::addParameterTypeAlias("QVector<GLint>", "QVector<qint32>");
PythonQtMethodInfo::addParameterTypeAlias("QList<GLuint>", "QList<qint32>");
PythonQtMethodInfo::addParameterTypeAlias("QVector<GLuint>", "QVector<quint32>");
PythonQtMethodInfo::addParameterTypeAlias("QList<GLuint64>", "QList<quint64>");
PythonQtMethodInfo::addParameterTypeAlias("QVector<GLuint64>", "QVector<quint64>");
PythonQtMethodInfo::addParameterTypeAlias("QList<GLint64>", "QList<qint64>");
PythonQtMethodInfo::addParameterTypeAlias("QVector<GLint64>", "QVector<qint64>");
PythonQtMethodInfo::addParameterTypeAlias("QList<QLocale::Country>", "QList<int>");
PythonQtMethodInfo::addParameterTypeAlias("QList<Qt::DayOfWeek>", "QList<int>");
// register some QPairs that are used in the Qt interfaces:
PythonQtRegisterQPairConverter(int, int);
PythonQtRegisterQPairConverter(float, float);
PythonQtRegisterQPairConverter(double, double);
PythonQtRegisterQPairConverter(QString, QString);
PythonQtRegisterQPairConverter(QByteArray, QByteArray);
PythonQtRegisterQPairConverter(double, QColor);
PythonQtRegisterQPairConverter(double, QPointF);
PythonQtRegisterQPairConverter(double, QVariant);
PythonQtRegisterQPairConverter(QString, QSizeF);
PythonQtMethodInfo::addParameterTypeAlias("QPair<qreal,qreal>", "QPair<double,double>");
PythonQtMethodInfo::addParameterTypeAlias("QPair<qreal,QColor>", "QPair<double,QColor>");
PythonQtMethodInfo::addParameterTypeAlias("QPair<qreal,QPointF>", "QPair<double,QPointF>");
PythonQtMethodInfo::addParameterTypeAlias("QPair<qreal,QVariant>", "QPair<double,QVariant>");
PythonQtMethodInfo::addParameterTypeAlias("QPair<QOpenGLTexture::Filter,QOpenGLTexture::Filter>", "QPair<int,int>");
// register some QList/QVector of QPairs that are used in the Qt interfaces:
PythonQtRegisterListTemplateQPairConverter(QVector, double, QVariant);
PythonQtRegisterListTemplateQPairConverter(QVector, double, QColor);
// NOTE: the extra space between the > is needed (and added by the moc)
PythonQtMethodInfo::addParameterTypeAlias("QVector<QPair<qreal,QVariant> >", "QVector<QPair<double,QVariant> >");
PythonQtMethodInfo::addParameterTypeAlias("QVector<QPair<qreal,QColor> >", "QVector<QPair<double,QColor> >");
PythonQtRegisterListTemplateQPairConverter(QList, QByteArray, QByteArray);
PythonQtRegisterListTemplateQPairConverter(QList, QString, QString);
PythonQtRegisterListTemplateQPairConverter(QList, QString, QSizeF);
PythonQtRegisterListTemplateQPairConverter(QList, double, QPointF);
PythonQtRegisterListTemplateQPairConverter(QList, double, double);
// NOTE: the extra space between the > is needed (and added by the moc)
PythonQtMethodInfo::addParameterTypeAlias("QList<QPair<qreal,QPointF> >", "QList<QPair<double,QPointF> >");
PythonQtMethodInfo::addParameterTypeAlias("QList<QPair<qreal,qreal> >", "QList<QPair<double,double> >");
PythonQtRegisterIntegerMapConverter(QMap, QByteArray);
PythonQtRegisterIntegerMapConverter(QMap, QVariant);
PythonQtRegisterIntegerMapConverter(QMap, QString);
PythonQtRegisterIntegerMapConverter(QHash, QByteArray);
PythonQtRegisterIntegerMapConverter(QHash, QVariant);
PythonQtRegisterIntegerMapConverter(QHash, QString);
PythonQtMethodInfo::addParameterTypeAlias("QHash<QNetworkRequest::Attribute,QVariant>", "QHash<int,QVariant>");
PythonQt_init_QtCoreBuiltin(NULL);
PythonQt_init_QtGuiBuiltin(NULL);
PythonQt::self()->addDecorators(new PythonQtStdDecorators());
PythonQt::self()->registerCPPClass("QMetaObject",0, "QtCore", PythonQtCreateObject<PythonQtWrapper_QMetaObject>);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QByteArray);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QDate);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QTime);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QDateTime);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QUrl);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QLocale);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QRect);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QRectF);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QSize);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QSizeF);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QLine);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QLineF);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QPoint);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QPointF);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QRegExp);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QFont);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QPixmap);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QBrush);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QColor);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QPalette);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QIcon);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QImage);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QPolygon);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QRegion);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QBitmap);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QCursor);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QSizePolicy);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QKeySequence);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QPen);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QTextLength);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QTextFormat);
PythonQtRegisterToolClassesTemplateConverterForKnownClass(QMatrix);
PyObject* pack = PythonQt::priv()->packageByName("QtCore");
PyObject* pack2 = PythonQt::priv()->packageByName("Qt");
PyObject* qtNamespace = PythonQt::priv()->getClassInfo("Qt")->pythonQtClassWrapper();
const char* names[16] = {"SIGNAL", "SLOT", "qAbs", "qBound","qDebug","qWarning","qCritical","qFatal"
,"qFuzzyCompare", "qMax","qMin","qRound","qRound64","qVersion","qrand","qsrand"};
for (unsigned int i = 0;i<16; i++) {
PyObject* obj = PyObject_GetAttrString(qtNamespace, names[i]);
if (obj) {
PyModule_AddObject(pack, names[i], obj);
Py_INCREF(obj);
PyModule_AddObject(pack2, names[i], obj);
} else {
std::cerr << "method not found " << names[i] << std::endl;
}
}
int enumValues[] = {
QtDebugMsg,
QtWarningMsg,
QtCriticalMsg,
QtFatalMsg,
QtSystemMsg
};
const char* enumNames[] = {
"QtDebugMsg",
"QtWarningMsg",
"QtCriticalMsg",
"QtFatalMsg",
"QtSystemMsg"
};
for (int i = 0; i<sizeof(enumValues)/sizeof(int); i++) {
PyObject* obj = PyInt_FromLong(enumValues[i]);
PyModule_AddObject(pack, enumNames[i], obj);
Py_INCREF(obj);
PyModule_AddObject(pack2, enumNames[i], obj);
}
_self->priv()->pythonQtModule().addObject("Debug", _self->priv()->_debugAPI);
PyModule_AddObject(pack, "Slot", (PyObject*)&PythonQtSlotDecorator_Type);
PyModule_AddObject(pack, "Signal", (PyObject*)&PythonQtSignalFunction_Type);
PyModule_AddObject(pack, "Property", (PyObject*)&PythonQtProperty_Type);
}
}
void PythonQt::cleanup()
{
if (_self) {
// Remove signal handlers in advance, since destroying them calls back into
// PythonQt::priv()->removeSignalEmitter()
_self->removeSignalHandlers();
delete _self;
_self = NULL;
}
}
PythonQt* PythonQt::self() { return _self; }
PythonQt::PythonQt(int flags, const QByteArray& pythonQtModuleName)
{
_p = new PythonQtPrivate;
_p->_initFlags = flags;
if ((flags & PythonAlreadyInitialized) == 0) {
#ifdef PY3K
Py_SetProgramName(const_cast<wchar_t*>(L"PythonQt"));
#else
Py_SetProgramName(const_cast<char*>("PythonQt"));
#endif
if (flags & IgnoreSiteModule) {
// this prevents the automatic importing of Python site files
Py_NoSiteFlag = 1;
}
Py_Initialize();
}
// add our own python object types for qt object slots
if (PyType_Ready(&PythonQtSlotFunction_Type) < 0) {
std::cerr << "could not initialize PythonQtSlotFunction_Type" << ", in " << __FILE__ << ":" << __LINE__ << std::endl;
}
Py_INCREF(&PythonQtSlotFunction_Type);
if (PyType_Ready(&PythonQtSignalFunction_Type) < 0) {
std::cerr << "could not initialize PythonQtSignalFunction_Type" << ", in " << __FILE__ << ":" << __LINE__ << std::endl;
}
Py_INCREF(&PythonQtSignalFunction_Type);
if (PyType_Ready(&PythonQtSlotDecorator_Type) < 0) {
std::cerr << "could not initialize PythonQtSlotDecorator_Type" << ", in " << __FILE__ << ":" << __LINE__ << std::endl;
}
Py_INCREF(&PythonQtSlotDecorator_Type);
if (PyType_Ready(&PythonQtProperty_Type) < 0) {
std::cerr << "could not initialize PythonQtProperty_Type" << ", in " << __FILE__ << ":" << __LINE__ << std::endl;
}
Py_INCREF(&PythonQtProperty_Type);
PythonQtBoolResult_Type.tp_new = PyType_GenericNew;
if (PyType_Ready(&PythonQtBoolResult_Type) < 0) {
std::cerr << "could not initialize PythonQtBoolResult_Type" << ", in " << __FILE__ << ":" << __LINE__ << std::endl;
}
Py_INCREF(&PythonQtBoolResult_Type);
// according to Python docs, set the type late here, since it can not safely be stored in the struct when declaring it
PythonQtClassWrapper_Type.tp_base = &PyType_Type;
// add our own python object types for classes
if (PyType_Ready(&PythonQtClassWrapper_Type) < 0) {
std::cerr << "could not initialize PythonQtClassWrapper_Type" << ", in " << __FILE__ << ":" << __LINE__ << std::endl;
}
Py_INCREF(&PythonQtClassWrapper_Type);
// add our own python object types for CPP instances
if (PyType_Ready(&PythonQtInstanceWrapper_Type) < 0) {
PythonQt::handleError();
std::cerr << "could not initialize PythonQtInstanceWrapper_Type" << ", in " << __FILE__ << ":" << __LINE__ << std::endl;
}
Py_INCREF(&PythonQtInstanceWrapper_Type);
// add our own python object types for redirection of stdout
if (PyType_Ready(&PythonQtStdOutRedirectType) < 0) {
std::cerr << "could not initialize PythonQtStdOutRedirectType" << ", in " << __FILE__ << ":" << __LINE__ << std::endl;
}
Py_INCREF(&PythonQtStdOutRedirectType);
// add our own python object types for redirection of stdin
if (PyType_Ready(&PythonQtStdInRedirectType) < 0) {
std::cerr << "could not initialize PythonQtStdInRedirectType" << ", in " << __FILE__ << ":" << __LINE__ << std::endl;
}
Py_INCREF(&PythonQtStdInRedirectType);
initPythonQtModule(flags & RedirectStdOut, pythonQtModuleName);
}
PythonQt::~PythonQt() {
delete _p;
_p = NULL;
}
PythonQtPrivate::~PythonQtPrivate() {
delete _defaultImporter;
_defaultImporter = NULL;
{
QHashIterator<QByteArray, PythonQtClassInfo *> i(_knownClassInfos);
while (i.hasNext()) {
delete i.next().value();
}
}
PythonQtConv::global_valueStorage.clear();
PythonQtConv::global_ptrStorage.clear();
PythonQtConv::global_variantStorage.clear();
PythonQtMethodInfo::cleanupCachedMethodInfos();
}
void PythonQt::setRedirectStdInCallback(PythonQtInputChangedCB* callback, void * callbackData)
{
if (!callback) {
std::cerr << "PythonQt::setRedirectStdInCallback - callback parameter is NULL !" << std::endl;
return;
}
PythonQtObjectPtr sys;
PythonQtObjectPtr in;
sys.setNewRef(PyImport_ImportModule("sys"));
// Backup original 'sys.stdin' if not yet done
if( !PyObject_HasAttrString(sys.object(), "pythonqt_original_stdin") ) {
PyObject_SetAttrString(sys.object(), "pythonqt_original_stdin", PyObject_GetAttrString(sys.object(), "stdin"));
}
in = PythonQtStdInRedirectType.tp_new(&PythonQtStdInRedirectType, NULL, NULL);
((PythonQtStdInRedirect*)in.object())->_cb = callback;
((PythonQtStdInRedirect*)in.object())->_callData = callbackData;
// replace the built in file objects with our own objects
PyModule_AddObject(sys.object(), "stdin", in);
// Backup custom 'stdin' into 'pythonqt_stdin'
Py_INCREF(in); // AddObject steals the reference, so increment it
PyModule_AddObject(sys.object(), "pythonqt_stdin", in);
}
void PythonQt::setRedirectStdInCallbackEnabled(bool enabled)
{
PythonQtObjectPtr sys;
sys.setNewRef(PyImport_ImportModule("sys"));
if (enabled) {
if( !PyObject_HasAttrString(sys.object(), "pythonqt_stdin") ) {
PyObject_SetAttrString(sys.object(), "stdin", PyObject_GetAttrString(sys.object(), "pythonqt_stdin"));
}
} else {
if( !PyObject_HasAttrString(sys.object(), "pythonqt_original_stdin") ) {
PyObject_SetAttrString(sys.object(), "stdin", PyObject_GetAttrString(sys.object(), "pythonqt_original_stdin"));
}
}
}
PythonQtImportFileInterface* PythonQt::importInterface()
{
return _self->_p->_importInterface?_self->_p->_importInterface:_self->_p->_defaultImporter;
}
void PythonQt::qObjectNoLongerWrappedCB(QObject* o)
{
if (_self->_p->_noLongerWrappedCB) {
(*_self->_p->_noLongerWrappedCB)(o);
};
}
void PythonQt::registerClass(const QMetaObject* metaobject, const char* package, PythonQtQObjectCreatorFunctionCB* wrapperCreator, PythonQtShellSetInstanceWrapperCB* shell)
{
_p->registerClass(metaobject, package, wrapperCreator, shell);
}
void PythonQtPrivate::registerClass(const QMetaObject* metaobject, const char* package, PythonQtQObjectCreatorFunctionCB* wrapperCreator, PythonQtShellSetInstanceWrapperCB* shell, PyObject* module, int typeSlots)
{
// we register all classes in the hierarchy
const QMetaObject* m = metaobject;
bool first = true;
while (m) {
PythonQtClassInfo* info = lookupClassInfoAndCreateIfNotPresent(m->className());
if (!info->pythonQtClassWrapper()) {
info->setTypeSlots(typeSlots);
info->setupQObject(m);
createPythonQtClassWrapper(info, package, module);
if (m->superClass()) {
PythonQtClassInfo* parentInfo = lookupClassInfoAndCreateIfNotPresent(m->superClass()->className());
info->addParentClass(PythonQtClassInfo::ParentClassInfo(parentInfo));
}
} else if (first && module) {
// There is a wrapper already, but if we got a module, we want to place the wrapper into that module as well,
// since it might have been placed into "private" earlier on.
// If the wrapper was already added to module before, it is just readded, which does no harm.
PyObject* classWrapper = info->pythonQtClassWrapper();
// AddObject steals a reference, so we need to INCREF
Py_INCREF(classWrapper);
PyModule_AddObject(module, info->className(), classWrapper);
}
if (first) {
first = false;
if (wrapperCreator) {
info->setDecoratorProvider(wrapperCreator);
}
if (shell) {
info->setShellSetInstanceWrapperCB(shell);
}
}
m = m->superClass();
}
}
void PythonQtPrivate::createPythonQtClassWrapper(PythonQtClassInfo* info, const char* package, PyObject* module)
{
QByteArray pythonClassName = info->className();
int nestedClassIndex = pythonClassName.indexOf("::");
bool isNested = false;
if (nestedClassIndex>0) {
pythonClassName = pythonClassName.mid(nestedClassIndex + 2);
isNested = true;
}
PyObject* pack = module?module:packageByName(package);
PyObject* pyobj = (PyObject*)createNewPythonQtClassWrapper(info, pack, pythonClassName);
if (isNested) {
QByteArray outerClass = QByteArray(info->className()).mid(0, nestedClassIndex);
PythonQtClassInfo* outerClassInfo = lookupClassInfoAndCreateIfNotPresent(outerClass);
outerClassInfo->addNestedClass(info);
} else {
PyModule_AddObject(pack, info->className(), pyobj);
}
if (!module && package && strncmp(package, "Qt", 2) == 0) {
// since PyModule_AddObject steals the reference, we need a incref once more...
Py_INCREF(pyobj);
// put all qt objects into Qt as well
PyModule_AddObject(packageByName("Qt"), info->className(), pyobj);
}
info->setPythonQtClassWrapper(pyobj);
}
PyObject* PythonQtPrivate::wrapQObject(QObject* obj)
{
if (!obj) {
Py_INCREF(Py_None);
return Py_None;
}
PythonQtInstanceWrapper* wrap = findWrapperAndRemoveUnused(obj);
if (wrap && wrap->_wrappedPtr) {
// uh oh, we want to wrap a QObject, but have a C++ wrapper at that
// address, so probably that C++ wrapper has been deleted earlier and
// now we see a QObject with the same address.
// Do not use the old wrapper anymore.
wrap = NULL;
}
if (!wrap) {
// smuggling it in...
PythonQtClassInfo* classInfo = _knownClassInfos.value(obj->metaObject()->className());
if (!classInfo || classInfo->pythonQtClassWrapper()==NULL) {
registerClass(obj->metaObject());
classInfo = _knownClassInfos.value(obj->metaObject()->className());
}
wrap = createNewPythonQtInstanceWrapper(obj, classInfo);
// mlabDebugConst("MLABPython","new qobject wrapper added " << " " << wrap->_obj->className() << " " << wrap->classInfo()->wrappedClassName().latin1());
} else {
Py_INCREF(wrap);
// mlabDebugConst("MLABPython","qobject wrapper reused " << wrap->_obj->className() << " " << wrap->classInfo()->wrappedClassName().latin1());
}
return (PyObject*)wrap;
}
PyObject* PythonQtPrivate::wrapPtr(void* ptr, const QByteArray& name, bool passOwnership)
{
if (!ptr) {
Py_INCREF(Py_None);
return Py_None;
}
PythonQtInstanceWrapper* wrap = findWrapperAndRemoveUnused(ptr);
PythonQtInstanceWrapper* possibleStillAliveWrapper = NULL;
if (wrap && wrap->_wrappedPtr) {
// we have a previous C++ wrapper... if the wrapper is for a C++ object,
// we are not sure if it may have been deleted earlier and we just see the same C++
// pointer once again. To make sure that we do not reuse a wrapper of the wrong type,
// we compare the classInfo() pointer and only reuse the wrapper if it has the same
// info. This is only needed for non-QObjects, since we know it when a QObject gets deleted.
possibleStillAliveWrapper = wrap;
wrap = NULL;
}
if (!wrap) {
PythonQtClassInfo* info = getClassInfo(name);
if (!info) {
// maybe it is a PyObject, which we can return directly
if (name == "PyObject") {
// do not increment its ref-count, it is the job of the slot returning the value
// to ensure an extra ref on return.
return (PyObject*)ptr;
}
// we do not know the metaobject yet, but we might know it by its name:
if (_knownQObjectClassNames.find(name)!=_knownQObjectClassNames.end()) {
// yes, we know it, so we can convert to QObject
QObject* qptr = (QObject*)ptr;
registerClass(qptr->metaObject());
info = _knownClassInfos.value(qptr->metaObject()->className());
}
}
if (info && info->isQObject()) {
QObject* qptr = (QObject*)ptr;
// if the object is a derived object, we want to switch the class info to the one of the derived class:
if (name!=(qptr->metaObject()->className())) {
info = _knownClassInfos.value(qptr->metaObject()->className());
if (!info) {
registerClass(qptr->metaObject());
info = _knownClassInfos.value(qptr->metaObject()->className());
}
}
wrap = createNewPythonQtInstanceWrapper(qptr, info);
wrap->_ownedByPythonQt = passOwnership;
// mlabDebugConst("MLABPython","new qobject wrapper added " << " " << wrap->_obj->className() << " " << wrap->classInfo()->wrappedClassName().latin1());
return (PyObject*)wrap;
}
// not a known QObject, try to wrap via foreign wrapper factories
PyObject* foreignWrapper = NULL;
for (int i=0; i<_foreignWrapperFactories.size(); i++) {
foreignWrapper = _foreignWrapperFactories.at(i)->wrap(name, ptr);
if (foreignWrapper) {
return foreignWrapper;
}
}
// not a known QObject, so try our wrapper factory:
QObject* wrapper = NULL;
for (int i=0; i<_cppWrapperFactories.size(); i++) {
wrapper = _cppWrapperFactories.at(i)->create(name, ptr);
if (wrapper) {
break;
}
}
if (info) {
// try to downcast in the class hierarchy, which will modify info and ptr if it is successfull
ptr = info->castDownIfPossible(ptr, &info);
// if downcasting found out that the object is a QObject,
// handle it like one:
if (info && info->isQObject()) {
QObject* qptr = (QObject*)ptr;
// if the object is a derived object, we want to switch the class info to the one of the derived class:
if (name!=(qptr->metaObject()->className())) {
registerClass(qptr->metaObject());
info = _knownClassInfos.value(qptr->metaObject()->className());
}
wrap = createNewPythonQtInstanceWrapper(qptr, info);
wrap->_ownedByPythonQt = passOwnership;
// mlabDebugConst("MLABPython","new qobject wrapper added " << " " << wrap->_obj->className() << " " << wrap->classInfo()->wrappedClassName().latin1());
return (PyObject*)wrap;
}
}
if (!info || info->pythonQtClassWrapper()==NULL) {
// still unknown, register as CPP class
registerCPPClass(name.constData());
info = _knownClassInfos.value(name);
}
if (wrapper && (info->metaObject() != wrapper->metaObject())) {
// if we a have a QObject wrapper and the metaobjects do not match, set the metaobject again!
info->setMetaObject(wrapper->metaObject());
}
if (possibleStillAliveWrapper && possibleStillAliveWrapper->classInfo()->inherits(info)) {
wrap = possibleStillAliveWrapper;
Py_INCREF(wrap);
} else {
wrap = createNewPythonQtInstanceWrapper(wrapper, info, ptr);
wrap->_ownedByPythonQt = passOwnership;
}
// mlabDebugConst("MLABPython","new c++ wrapper added " << wrap->_wrappedPtr << " " << wrap->_obj->className() << " " << wrap->classInfo()->wrappedClassName().latin1());
} else {
Py_INCREF(wrap);
//mlabDebugConst("MLABPython","c++ wrapper reused " << wrap->_wrappedPtr << " " << wrap->_obj->className() << " " << wrap->classInfo()->wrappedClassName().latin1());
}
return (PyObject*)wrap;
}
PyObject* PythonQtPrivate::dummyTuple() {
static PyObject* dummyTuple = NULL;
if (dummyTuple==NULL) {
dummyTuple = PyTuple_New(1);
PyTuple_SET_ITEM(dummyTuple, 0 , PyString_FromString("dummy"));
}
return dummyTuple;
}
PythonQtInstanceWrapper* PythonQtPrivate::createNewPythonQtInstanceWrapper(QObject* obj, PythonQtClassInfo* info, void* wrappedPtr) {
// call the associated class type to create a new instance...
PythonQtInstanceWrapper* result = (PythonQtInstanceWrapper*)PyObject_Call(info->pythonQtClassWrapper(), dummyTuple(), NULL);
result->setQObject(obj);
result->_wrappedPtr = wrappedPtr;
result->_ownedByPythonQt = false;
result->_useQMetaTypeDestroy = false;
if (wrappedPtr || obj) {
// if this object is reference counted, we ref it:
PythonQtVoidPtrCB* refCB = info->referenceCountingRefCB();
if (refCB) {
(*refCB)(wrappedPtr);
}
if (wrappedPtr) {
_wrappedObjects.insert(wrappedPtr, result);
} else {
_wrappedObjects.insert(obj, result);
if (obj->parent()== NULL && _wrappedCB) {
// tell someone who is interested that the qobject is wrapped the first time, if it has no parent
(*_wrappedCB)(obj);
}
}
}
return result;
}
PythonQtClassWrapper* PythonQtPrivate::createNewPythonQtClassWrapper(PythonQtClassInfo* info, PyObject* parentModule, const QByteArray& pythonClassName) {
PythonQtClassWrapper* result;
PyObject* className = PyString_FromString(pythonClassName.constData());
PyObject* baseClasses = PyTuple_New(1);
Py_INCREF(&PythonQtInstanceWrapper_Type);
PyTuple_SET_ITEM(baseClasses, 0, (PyObject*)&PythonQtInstanceWrapper_Type);
PyObject* typeDict = PyDict_New();
PyObject* moduleName = PyObject_GetAttrString(parentModule, "__name__");
PyDict_SetItemString(typeDict, "__module__", moduleName);
PyObject* args = Py_BuildValue("OOO", className, baseClasses, typeDict);
// set the class info so that PythonQtClassWrapper_new can read it
_currentClassInfoForClassWrapperCreation = info;
// create the new type object by calling the type
result = (PythonQtClassWrapper *)PyObject_Call((PyObject *)&PythonQtClassWrapper_Type, args, NULL);
Py_DECREF(moduleName);
Py_DECREF(baseClasses);
Py_DECREF(typeDict);
Py_DECREF(args);
Py_DECREF(className);
return result;
}
PyObject* PythonQtPrivate::createEnumValueInstance(PyObject* enumType, unsigned int enumValue)
{
PyObject* args = Py_BuildValue("(i)", enumValue);
PyObject* result = PyObject_Call(enumType, args, NULL);
Py_DECREF(args);
return result;
}
PyObject* PythonQtPrivate::createNewPythonQtEnumWrapper(const char* enumName, PyObject* parentObject) {
PyObject* result;
PyObject* className = PyString_FromString(enumName);
PyObject* baseClasses = PyTuple_New(1);
Py_INCREF(&PyInt_Type);
PyTuple_SET_ITEM(baseClasses, 0, (PyObject*)&PyInt_Type);
PyObject* module = PyObject_GetAttrString(parentObject, "__module__");
PyObject* typeDict = PyDict_New();
PyDict_SetItemString(typeDict, "__module__", module);
PyObject* args = Py_BuildValue("OOO", className, baseClasses, typeDict);
// create the new int derived type object by calling the core type
result = PyObject_Call((PyObject *)&PyType_Type, args, NULL);
Py_DECREF(module);
Py_DECREF(baseClasses);
Py_DECREF(typeDict);
Py_DECREF(args);
Py_DECREF(className);
return result;
}
PythonQtSignalReceiver* PythonQt::getSignalReceiver(QObject* obj)
{
PythonQtSignalReceiver* r = _p->_signalReceivers[obj];
if (!r) {
r = new PythonQtSignalReceiver(obj);
_p->_signalReceivers.insert(obj, r);
}
return r;
}
bool PythonQt::addSignalHandler(QObject* obj, const char* signal, PyObject* module, const QString& objectname)
{
bool flag = false;
PythonQtObjectPtr callable = lookupCallable(module, objectname);
if (callable) {
PythonQtSignalReceiver* r = getSignalReceiver(obj);
flag = r->addSignalHandler(signal, callable);
if (!flag) {
// signal not found
}
} else {
// callable not found
}
return flag;
}
bool PythonQt::addSignalHandler(QObject* obj, const char* signal, PyObject* receiver)
{
bool flag = false;
PythonQtSignalReceiver* r = getSignalReceiver(obj);
if (r) {
flag = r->addSignalHandler(signal, receiver);
}
return flag;
}
bool PythonQt::removeSignalHandler(QObject* obj, const char* signal, PyObject* module, const QString& objectname)
{
bool flag = false;
PythonQtObjectPtr callable = lookupCallable(module, objectname);
if (callable) {
PythonQtSignalReceiver* r = _p->_signalReceivers[obj];
if (r) {
flag = r->removeSignalHandler(signal, callable);
}
} else {
// callable not found
}
return flag;
}
bool PythonQt::removeSignalHandler(QObject* obj, const char* signal, PyObject* receiver)
{
bool flag = false;
PythonQtSignalReceiver* r = _p->_signalReceivers[obj];
if (r) {
flag = r->removeSignalHandler(signal, receiver);
}
return flag;
}
PythonQtObjectPtr PythonQt::lookupCallable(PyObject* module, const QString& name)
{
PythonQtObjectPtr p = lookupObject(module, name);
if (p) {
if (PyCallable_Check(p)) {
return p;
}
}
PyErr_Clear();
return NULL;
}
PythonQtObjectPtr PythonQt::lookupObject(PyObject* module, const QString& name)
{
QStringList l = name.split('.');
PythonQtObjectPtr p = module;
PythonQtObjectPtr prev;
QByteArray b;
for (QStringList::ConstIterator i = l.begin(); i!=l.end() && p; ++i) {
prev = p;
b = (*i).toLatin1();
if (PyDict_Check(p)) {
p = PyDict_GetItemString(p, b.data());
} else {
p.setNewRef(PyObject_GetAttrString(p, b.data()));
}
}
PyErr_Clear();
return p;
}
PythonQtObjectPtr PythonQt::getMainModule() {
//both borrowed
PythonQtObjectPtr dict = PyImport_GetModuleDict();
return PyDict_GetItemString(dict, "__main__");
}
PythonQtObjectPtr PythonQt::importModule(const QString& name)
{
PythonQtObjectPtr mod;
mod.setNewRef(PyImport_ImportModule(name.toLatin1().constData()));
return mod;
}
QVariant PythonQt::evalCode(PyObject* object, PyObject* pycode) {
QVariant result;
clearError();
if (pycode) {
PyObject* dict = NULL;
PyObject* globals = NULL;
if (PyModule_Check(object)) {
dict = PyModule_GetDict(object);
globals = dict;
} else if (PyDict_Check(object)) {
dict = object;
globals = dict;
} else {
dict = PyObject_GetAttrString(object, "__dict__");
globals = PyObject_GetAttrString(PyImport_ImportModule(PyString_AS_STRING(PyObject_GetAttrString(object, "__module__"))),"__dict__");
}
PyObject* r = NULL;
if (dict) {
#ifdef PY3K
r = PyEval_EvalCode(pycode, globals, dict);
#else
r = PyEval_EvalCode((PyCodeObject*)pycode, globals, dict);
#endif
}
if (r) {
result = PythonQtConv::PyObjToQVariant(r);
Py_DECREF(r);
} else {
handleError();
}
} else {
handleError();
}
return result;
}
QVariant PythonQt::evalScript(PyObject* object, const QString& script, int start)
{
QVariant result;
PythonQtObjectPtr p;
PyObject* dict = NULL;
clearError();
if (PyModule_Check(object)) {
dict = PyModule_GetDict(object);
} else if (PyDict_Check(object)) {
dict = object;
}
if (dict) {
p.setNewRef(PyRun_String(script.toLatin1().data(), start, dict, dict));
}
if (p) {
result = PythonQtConv::PyObjToQVariant(p);
} else {
handleError();
}
return result;
}
void PythonQt::evalFile(PyObject* module, const QString& filename)
{
// NOTE: error checking is done by parseFile and evalCode
PythonQtObjectPtr code = parseFile(filename);
if (code) {
evalCode(module, code);
}
}
PythonQtObjectPtr PythonQt::parseFile(const QString& filename)
{
PythonQtObjectPtr p;
p.setNewRef(PythonQtImport::getCodeFromPyc(filename));
clearError();
if (!p) {
handleError();
_p->_hadError = true;
}
return p;
}
PythonQtObjectPtr PythonQt::createModuleFromFile(const QString& name, const QString& filename)
{
PythonQtObjectPtr code = parseFile(filename);
PythonQtObjectPtr module = _p->createModule(name, code);
return module;
}
PythonQtObjectPtr PythonQt::createModuleFromScript(const QString& name, const QString& script)
{
PyErr_Clear();
QString scriptCode = script;
if (scriptCode.isEmpty()) {
// we always need at least a linefeed
scriptCode = "\n";
}
PythonQtObjectPtr pycode;
pycode.setNewRef(Py_CompileString((char*)scriptCode.toLatin1().data(), "", Py_file_input));
PythonQtObjectPtr module = _p->createModule(name, pycode);
return module;
}
PythonQtObjectPtr PythonQt::createUniqueModule()
{
static QString pyQtStr("PythonQt_module");
QString moduleName = pyQtStr+QString::number(_uniqueModuleCount++);
return createModuleFromScript(moduleName);
}
void PythonQt::addObject(PyObject* object, const QString& name, QObject* qObject)
{
if (PyModule_Check(object)) {
PyModule_AddObject(object, name.toLatin1().data(), _p->wrapQObject(qObject));
} else if (PyDict_Check(object)) {
PyDict_SetItemString(object, name.toLatin1().data(), _p->wrapQObject(qObject));
} else {
PyObject_SetAttrString(object, name.toLatin1().data(), _p->wrapQObject(qObject));
}
}
void PythonQt::addVariable(PyObject* object, const QString& name, const QVariant& v)
{
if (PyModule_Check(object)) {
PyModule_AddObject(object, name.toLatin1().data(), PythonQtConv::QVariantToPyObject(v));
} else if (PyDict_Check(object)) {
PyDict_SetItemString(object, name.toLatin1().data(), PythonQtConv::QVariantToPyObject(v));
} else {
PyObject_SetAttrString(object, name.toLatin1().data(), PythonQtConv::QVariantToPyObject(v));
}
}
void PythonQt::removeVariable(PyObject* object, const QString& name)
{
if (PyDict_Check(object)) {
PyDict_DelItemString(object, name.toLatin1().data());
} else {
PyObject_DelAttrString(object, name.toLatin1().data());